问:
Laravel - Not receiving fields from nested inputs
I'm using Laravel 5.3 and the same blade view to create/edit a casa(house in portuguese) and contato(contact in portuguese).

I have a form to submit into 2 tables(contatos casas). It was working fine until I changed the name of the first 6 fields  (table contatos).

It was:

{!! Form::text('nome_contato') !!}

Now it is:

{!! Form::text('contato[nome_contato]') !!}

I had to do it, because the first one wasn't populating the input to edit it. But now it is telling me that those fields are empty even if they're not.

CasaRequest.php ↓↓

```<code>public function rules()
    {
        return [
            'nome_contato'  => 'required|max:255',
            'telefone'      => 'required|numeric|digits_between:10,11',
            'celular1'      => 'required|numeric|digits_between:10,11',
            'celular2'      => 'numeric|digits_between:10,11',
            'celular3'      => 'numeric|digits_between:10,11',
            'skype'         => 'max:255',
            'nome'          => 'required|max:100',
            'descricao'     => 'required|min:50|max:2000',
            'endereco'      => 'required|max:255',
            'numero'        => 'numeric|min:0',
            'bairro'        => 'required|max:100',
             (etc........)
            ];
}
</code>```

creteedit.blade.php ↓↓

```<code>    @if(isset($casa))
        {!! Form::model($casa, ['route' => ['casas.update', $casa->id], 'method' => 'put', 'class' => 'register']) !!}
    @else
        {!! Form::open(['route' => 'casas.store', 'class' => 'register']) !!}
    @endif

    <!-- First step Contatos -->
    <div class="row">
        <div class="form-group row">
            <div class="col l2 offset-l1">
                Nome para contato
            </div>
            <div class="col l8">
                {!! Form::text('contato[nome_contato]') !!}
                <span class="red-text text-lighten-1">{!!$errors->first('nome_contato')!!}</span>
                </div>
            </div>

            <div class="form-group row">
                <div class="col l2 offset-l1">
                    Telefone
                <div class="col l8">
                    {!! Form::text('contato[telefone]') !!}
                    <span class="red-text text-lighten-1">{!!$errors->first('telefone')!!}</span>
                </div>
            </div>

            <div class="form-group row">
                <div class="col l2 offset-l1">
                    Celular 1
                <div class="col l8">
                    {!! Form::text('contato[celular1]') !!}
                    <span class="red-text text-lighten-1">{!!$errors->first('celular1')!!}</span>
                </div>
            </div>

            <div class="form-group row">
                <div class="col l2 offset-l1">
                    Celular 2
                </div>
                <div class="col l8">
                    {!! Form::text('contato[celular2]') !!}
                    <span class="red-text text-lighten-1">{!!$errors->first('celular2')!!}</span>
                </div>

        <!-- Here comes more fields from the table `contatos` -->

<!-- Second step Casas -->

<div class="form-group row">
            <div class="col l2 offset-l1">
                    <label class="right">Nome<span class="red-text">*</span></label>
                </div>
                <div class="col l8">
                    {!! Form::text('nome') !!}
                    <span class="red-text text-lighten-1">{!!$errors->first('nome')!!}</span>
                </div>
            </div>

            <div class="form-group row">
                <div class="col l2 offset-l1">
                    <label class="right">Descrição<span class="red-text">*</span></label>
                </div>
                <div class="col l8">
                    {!! Form::textarea('descricao') !!}
                    <span class="red-text text-lighten-1">{!!$errors->first('descricao')!!}</span>
                </div>
            </div>

            <div class="form-group row">
                <div class="col l2 offset-l1">
                    <label class="right">Endereço <span class="red-text">*</span></label>
                </div>
                <div class="col l5">
                    {!! Form::text('endereco') !!}
                    <span class="red-text text-lighten-1">{!!$errors->first('endereco')!!}</span>
                </div>
                <div class="col l1 offset-l1 ">
                    <label class="right">Número</label>
                </div>
                <div class="col l1">
                    {!! Form::text('numero') !!}
                    <span class="red-text text-lighten-1">{!!$errors->first('numero')!!}</span>
                </div>
            </div>
</code>```

The fields from second step are working, only from first step are not, because of theirs name: contato[field_name].

答:
It's a nested input, you have to use dots.

Eg:

```<code>$request->input('contato.nome_contato')
</code>```

Same thing for rules :

```<code>'contato.nome_contato' => 'required|max:255',
</code>```

Body:
I'm using Laravel 5.3 and the same blade view to create/edit a casa(house in portuguese) and contato(contact in portuguese).

I have a form to submit into 2 tables(contatos casas). It was working fine until I changed the name of the first 6 fields  (table contatos).

It was:

{!! Form::text('nome_contato') !!}

Now it is:

{!! Form::text('contato[nome_contato]') !!}

I had to do it, because the first one wasn't populating the input to edit it. But now it is telling me that those fields are empty even if they're not.

CasaRequest.php ↓↓

public function rules()
    {
        return [
            'nome_contato'  => 'required|max:255',
            'telefone'      => 'required|numeric|digits_between:10,11',
            'celular1'      => 'required|numeric|digits_between:10,11',
            'celular2'      => 'numeric|digits_between:10,11',
            'celular3'      => 'numeric|digits_between:10,11',
            'skype'         => 'max:255',
            'nome'          => 'required|max:100',
            'descricao'     => 'required|min:50|max:2000',
            'endereco'      => 'required|max:255',
            'numero'        => 'numeric|min:0',
            'bairro'        => 'required|max:100',
             (etc........)
            ];
}

creteedit.blade.php ↓↓

    @if(isset($casa))
        {!! Form::model($casa, ['route' => ['casas.update', $casa->id], 'method' => 'put', 'class' => 'register']) !!}
    @else
        {!! Form::open(['route' => 'casas.store', 'class' => 'register']) !!}
    @endif

                Nome para contato

                {!! Form::text('contato[nome_contato]') !!}
                {!!$errors->first('nome_contato')!!}

                    Telefone

                    {!! Form::text('contato[telefone]') !!}
                    {!!$errors->first('telefone')!!}

                    Celular 1

                    {!! Form::text('contato[celular1]') !!}
                    {!!$errors->first('celular1')!!}

                    Celular 2

                    {!! Form::text('contato[celular2]') !!}
                    {!!$errors->first('celular2')!!}

                    Nome*

                    {!! Form::text('nome') !!}
                    {!!$errors->first('nome')!!}

                    Descrição*

                    {!! Form::textarea('descricao') !!}
                    {!!$errors->first('descricao')!!}

                    Endereço *

                    {!! Form::text('endereco') !!}
                    {!!$errors->first('endereco')!!}

                    Número

                    {!! Form::text('numero') !!}
                    {!!$errors->first('numero')!!}

The fields from second step are working, only from first step are not, because of theirs name: contato[field_name].

Body:
It's a nested input, you have to use dots.

Eg:

$request->input('contato.nome_contato')

Same thing for rules :

'contato.nome_contato' => 'required|max:255',


来源: stackexchange

问:
How to remove first appearance in stream when searching for duplicates?
I have a Stream of objects, which define the equals and hashcode based on an id that they have. So I know that using stream.distinct() I will get a stream that does not have any duplicate, but it will keep the first appearance, rather than the last one.

This is clearly stated in the docs:

For ordered streams, the selection of distinct elements is stable
       * (for duplicated elements, the element appearing first in the encounter
       * order is preserved.)

So how can I have a stream that doesn't have duplicates, but keeping the last appearance instead?

For example if I have this list of items 1,2,3,1,4,5.

If I apply the distinct() I will get 1,2,3,4,5, and I am expecting: 2,3,1,4,5. How can I achieve this?

答:
A customized toMap collector with access-order LinkedHashMap is a good start, for example:

```<code>Stream.of( 1, 2, 3, 1, 4, 5 )
        .collect( Collectors.toMap(
                key -> key,
                value -> value,
                ( oldValue, newValue ) -> newValue,
                () -> new LinkedHashMap<>( 16, 0.75f, true )
        ) )
        .values()
        .stream()
        .forEach( System.out::println );
</code>```

The task of preserving the last appearance of an item implies that you will have to fully consume the original stream anyway before producing the first element of the new stream, so collecting and creating a new stream is not that bad. Reversing, applying distinct, and reversing again, as suggested in comments, will fully consume both the original and "distinct" stream, so using a specialized collector should be better.

ContentLicense: CC BY-SA 3.0

Body:
A customized toMap collector with access-order LinkedHashMap is a good start, for example:

Stream.of( 1, 2, 3, 1, 4, 5 )
        .collect( Collectors.toMap(
                key -> key,
                value -> value,
                ( oldValue, newValue ) -> newValue,
                () -> new LinkedHashMap<>( 16, 0.75f, true )
        ) )
        .values()
        .stream()
        .forEach( System.out::println );

The task of preserving the last appearance of an item implies that you will have to fully consume the original stream anyway before producing the first element of the new stream, so collecting and creating a new stream is not that bad. Reversing, applying distinct, and reversing again, as suggested in comments, will fully consume both the original and "distinct" stream, so using a specialized collector should be better.


问:
Custom date format in Excel VBA
I am trying to use the custom format to change the date from English to French. The custom code in regular Excel is [$-C0C]d mmmm;@ and yields the output as 20 juillet.

When using the following VBA code:

Format(Range("B2"), "[$-C0C]d mmmm;@")

The output is 20 July

[$-C0C] is supposed to be the code for French Canada

答:
Try this

```<code>'~~> Replace Sheet1 below with the sheet code name of the cell which has date
Debug.Print Sheet1.Evaluate("text(B2, ""[$-C0C]d mmmm;@"")")
</code>```

Explanation: The format function can only take one of the pre-defined values as mentioned in Format Function (Visual Basic for Applications). Check out the section User-Defined Date/Time Formats (Format Function) And hence we use an alternative method.

Title: Custom date format in Excel VBA

Body:
Try this

'~~> Replace Sheet1 below with the sheet code name of the cell which has date
Debug.Print Sheet1.Evaluate("text(B2, ""[$-C0C]d mmmm;@"")")

Explanation: The format function can only take one of the pre-defined values as mentioned in Format Function (Visual Basic for Applications). Check out the section User-Defined Date/Time Formats (Format Function) And hence we use an alternative method.


问:
What is a reliable way to detect whether a file or directory has changed in the most recent commit?
I have a web project which I deploy to an ec2 instance simply by pushing new commits.  I use the post-recieve git hook remotely to execute a shell-script which 'deploys' the project by checking it out into a production directory.  The steps are, run npm install on the express app, npm install on the frontend (a create-react-app app), then run npm run build (which basically utilizes web-pack to build an optimized distribution folder from my node source code).

These steps are expensive and in many cases not needed. E.G. if all I did was update a Node component in srcs/components/ then npm run build should run, but npm install on the server and frontend shouldn't.  If all I have done is added a comment to my express app, no scripts should run.

My currently server-side deploy script looks like this:

```<code>#!/usr/bin/env bash

GIT_WORK_TREE=/home/ec2-user/absiteProd git checkout -f

### TODO: conditional NPM work

pm2 restart index
</code>```

My question is then how can I use git (or grep, sed, awk, etc..) to reliably tell me when either /home/ec2-user/absiteProd/frontend/package.json,
/home/ec2-user/absiteProd/server/package.json or anything in 'home/ec2-user/absiteProd/frontend/sources` has changed?

Currently I'm having some success with:

```<code>if `git log --stat -n 1` | grep --quite frontend/src/* ; then
   cd home/ec2-user/frontend
   npm run build
fi
</code>```

But since this seems like such a common requirement in app deployment,  I feel like there must be a simpler way?

答:
You can find a similar need in this thread:

How do I find a last commit for the given directory inside the repository?

I want to avoid rebuilding the specific part of the project if there were no changes in it since the last build, so I need to find the sha of the last time the directory was changed.

You can compare the last commit where an element is modified, using git rev-list:

```<code>git rev-list -1 HEAD -- frontend/package.json
git rev-list -1 HEAD -- absiteProd/server/package.json
git rev-list -1 HEAD -- frontend/src
</code>```

with the current HEAD SHA1 (git rev-parse, the --verify is optional):

```<code>git rev-parse --verify HEAD
</code>```

That is:

```<code>h=$(git rev-parse --verify HEAD)
b=false
if [[ "$(git rev-list -1 HEAD -- frontend/package.json)" == "${h}" ]]; then b=true; fi
if [[ "$(git rev-list -1 HEAD -- frontend/package.json)" == "${h}" ]]; then b=true; fi
if [[ "$(git rev-list -1 HEAD -- frontend/package.json)" == "${h}" ]]; then b=true; fi
if !b; then exit 0; fi
cd home/ec2-user/frontend
npm run build
</code>```

Body:
I have a web project which I deploy to an ec2 instance simply by pushing new commits.  I use the post-recieve git hook remotely to execute a shell-script which 'deploys' the project by checking it out into a production directory.  The steps are, run npm install on the express app, npm install on the frontend (a create-react-app app), then run npm run build (which basically utilizes web-pack to build an optimized distribution folder from my node source code).

These steps are expensive and in many cases not needed. E.G. if all I did was update a Node component in srcs/components/ then npm run build should run, but npm install on the server and frontend shouldn't.  If all I have done is added a comment to my express app, no scripts should run.

My currently server-side deploy script looks like this:

#!/usr/bin/env bash

GIT_WORK_TREE=/home/ec2-user/absiteProd git checkout -f

### TODO: conditional NPM work

pm2 restart index

My question is then how can I use git (or grep, sed, awk, etc..) to reliably tell me when either /home/ec2-user/absiteProd/frontend/package.json,
/home/ec2-user/absiteProd/server/package.json or anything in 'home/ec2-user/absiteProd/frontend/sources` has changed?

Currently I'm having some success with:

if `git log --stat -n 1` | grep --quite frontend/src/* ; then
   cd home/ec2-user/frontend
   npm run build
fi

But since this seems like such a common requirement in app deployment,  I feel like there must be a simpler way?

Body:
You can find a similar need in this thread:

How do I find a last commit for the given directory inside the repository?

I want to avoid rebuilding the specific part of the project if there were no changes in it since the last build, so I need to find the sha of the last time the directory was changed.

You can compare the last commit where an element is modified, using git rev-list:

git rev-list -1 HEAD -- frontend/package.json
git rev-list -1 HEAD -- absiteProd/server/package.json
git rev-list -1 HEAD -- frontend/src

with the current HEAD SHA1 (git rev-parse, the --verify is optional):

git rev-parse --verify HEAD

That is:

h=$(git rev-parse --verify HEAD)
b=false
if [[ "$(git rev-list -1 HEAD -- frontend/package.json)" == "${h}" ]]; then b=true; fi
if [[ "$(git rev-list -1 HEAD -- frontend/package.json)" == "${h}" ]]; then b=true; fi
if [[ "$(git rev-list -1 HEAD -- frontend/package.json)" == "${h}" ]]; then b=true; fi
if !b; then exit 0; fi
cd home/ec2-user/frontend
npm run build


问:
'Chaincode fingerprint does not match' when querying from other peer
I set up a network on several servers. On one of the servers, the compiled chaincode is consistently different from the chaincode on other servers, resulting in the message:

```<code>Error: Error endorsing query: rpc error: code = Unknown desc = Error executing chaincode: Could not get deployment transaction from LSCC for mycc:1.0 - Get ChaincodeDeploymentSpec for mycc/torchplatformchannel from LSCC error: chaincode fingerprint mismatch data mismatch - <nil>
</code>```

I don't know how chaincode is compiled exactly, but when I run a number of peers on my own laptop, with the same configuration, the hash always matches. I use the normal command to install the chaincode on the peer from the cli (fabric-tools) container (peer chaincode install -n mycc -v 1.0 -p chaincode_example02). The host machines are similar:

```<code>root@fabric:~# uname -a
Linux fabric 4.4.0-81-generic #104-Ubuntu SMP Wed Jun 14 08:17:06 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
</code>```

Other server:

```<code>Linux fabric2 4.4.0-75-generic #96-Ubuntu SMP Thu Apr 20 09:56:33 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
</code>```

Docker versions are the same:

```<code>root@fabric:~# docker version
Client:
 Version:      17.06.0-ce
 API version:  1.30
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:23:31 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.06.0-ce
 API version:  1.30 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:19:04 2017
 OS/Arch:      linux/amd64
 Experimental: false
</code>```

Images are the same:

```<code>root@fabric:~# docker images
hyperledger/fabric-tools   x86_64-1.0.0-beta   ae6b0f53cb70        3 weeks ago         1.32GB
hyperledger/fabric-peer    x86_64-1.0.0-beta   e01c2b645f11        3 weeks ago         182MB
hyperledger/fabric-ca      x86_64-1.0.0-beta   e549e8c53c2e        3 weeks ago         238MB
</code>```

But the chaincode actually IS different:

```<code>root@286f0cd4bc82:/var/hyperledger/production/chaincodes# md5sum mycc.1.0
a96076f0cadf7c0e5c8da50ee5195078  mycc.1.0
root@286f0cd4bc82:/var/hyperledger/production/chaincodes# ls -la mycc.1.0
-rw-r--r-- 1 root root 2441 Jul  4 12:55 mycc.1.0
</code>```

And on the other side:

```<code>root@6089fc35a6d9:/var/hyperledger/production/chaincodes# md5sum mycc.1.0
918307de80ef18de378c63e4138ccdf5  mycc.1.0
root@6089fc35a6d9:/var/hyperledger/production/chaincodes# ls -la mycc.1.0
-rw-r--r-- 1 root root 2448 Jul  4 12:53 mycc.1.0
</code>```

What could be the reason for a chaincode not having the same hash on a different peer?

答:
When you install a chaincode the basic flow works as following:

It's being packed into archive file considering all dependencies including transitive

Copied inside docker container with golang environment and got compiled there

Next peer builds up new chaincode container and moves compiled binary if I'm not mistaken into /usr/bin/local/chaincode

Now, you problem is that most likely $GOPATH in your computers differes and therefore installing same chaincode on different machines brings different dependencies ending up with different finger results.

What you need to do is to have your chaincode packed at one place and distribute the package to have it installed.

peer chaincode package -n name -v 1.0 -p path_to_your_chaincode

This will produce packed file which you will be able to use later. You can find more details here.

Body:
I set up a network on several servers. On one of the servers, the compiled chaincode is consistently different from the chaincode on other servers, resulting in the message:

Error: Error endorsing query: rpc error: code = Unknown desc = Error executing chaincode: Could not get deployment transaction from LSCC for mycc:1.0 - Get ChaincodeDeploymentSpec for mycc/torchplatformchannel from LSCC error: chaincode fingerprint mismatch data mismatch - <nil>

I don't know how chaincode is compiled exactly, but when I run a number of peers on my own laptop, with the same configuration, the hash always matches. I use the normal command to install the chaincode on the peer from the cli (fabric-tools) container (peer chaincode install -n mycc -v 1.0 -p chaincode_example02). The host machines are similar:

root@fabric:~# uname -a
Linux fabric 4.4.0-81-generic #104-Ubuntu SMP Wed Jun 14 08:17:06 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Other server:

Linux fabric2 4.4.0-75-generic #96-Ubuntu SMP Thu Apr 20 09:56:33 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Docker versions are the same:

root@fabric:~# docker version
Client:
 Version:      17.06.0-ce
 API version:  1.30
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:23:31 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.06.0-ce
 API version:  1.30 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:19:04 2017
 OS/Arch:      linux/amd64
 Experimental: false

Images are the same:

root@fabric:~# docker images
hyperledger/fabric-tools   x86_64-1.0.0-beta   ae6b0f53cb70        3 weeks ago         1.32GB
hyperledger/fabric-peer    x86_64-1.0.0-beta   e01c2b645f11        3 weeks ago         182MB
hyperledger/fabric-ca      x86_64-1.0.0-beta   e549e8c53c2e        3 weeks ago         238MB

But the chaincode actually IS different:

root@286f0cd4bc82:/var/hyperledger/production/chaincodes# md5sum mycc.1.0
a96076f0cadf7c0e5c8da50ee5195078  mycc.1.0
root@286f0cd4bc82:/var/hyperledger/production/chaincodes# ls -la mycc.1.0
-rw-r--r-- 1 root root 2441 Jul  4 12:55 mycc.1.0

And on the other side:

root@6089fc35a6d9:/var/hyperledger/production/chaincodes# md5sum mycc.1.0
918307de80ef18de378c63e4138ccdf5  mycc.1.0
root@6089fc35a6d9:/var/hyperledger/production/chaincodes# ls -la mycc.1.0
-rw-r--r-- 1 root root 2448 Jul  4 12:53 mycc.1.0

What could be the reason for a chaincode not having the same hash on a different peer?


问:
how to check if function(s) have been executed?
I am new to javascript and i am facing a situation here

```<code>if (function1() && function2() == true){
   //do something here

 }
   else{

   //do something else

}
</code>```

how do i ensure that function1() and function2() are executed and have true value ?

答:
What you have done is correct. Since you using && they both execute and when they both return true then only it enters the if.

As a side note, your code can be shorten to

```<code>if (function1() && function2()){
</code>```

Body:
I am new to javascript and i am facing a situation here

if (function1() && function2() == true){
   //do something here

 }
   else{

   //do something else

}

how do i ensure that function1() and function2() are executed and have true value ?

Body:
What you have done is correct. Since you using && they both execute and when they both return true then only it enters the if.

As a side note, your code can be shorten to

if (function1() && function2()){


问:
trying to create submenus
Editing for revision, as you can see the menu and its submenu is hiding behind the banner or picture

Is there something wrong with the code? as it only appears on firefox, all the other web browsers i.e Safari, Chrome, IE and Opera work well

```<code>  <BODY ONSELECTSTART="return false;" BGCOLOR="#FFFFFF" TEXT="#000000">
  <table border="0" align="center" width="800">
  <tr>
  <td align="left" width="200"><a href="index.html"><img
  src="images/logo1.gif" width="135" height="57" border="0"></a></td>
  <td width="399" align="right"><img src="images/medical_innovations.gif"
  width="335" height="60"></td>
  <td align="right" width="187"><div class="body"><b>Tel: 1-905-475-2380<br>
  Toll Free: 1-877-50KOSIM<br  />Fax: 905-475-2303<br  />
  email: <a href="email_sales.php">sales@kosim.ca</a></b></div></td>
  </tr>
  </table>
  <table align="center" width="800" bgcolor="EDF0F7" cellspacing="0"
  cellpadding="0">
  <tr>
  <td width="86" height="25"></td>
  <td width="2"><img src="images/spacer.jpg"></td>
  <td align="center" width="46"><a href="index.html"
  onMouseOver="movr(1);return true;" onMouseOut="mout(1);return true;"
 onClick="return true;"><img name=img1 border=0
 src="images/link_off_home.jpg"></a></td>
 <td width="2"><img src="images/spacer.jpg"></td>
 <td align="center" width="63"><a href="products/index.html"
 onMouseOver="movr(2);return true;" onMouseOut="mout(2);return true;"
  onClick="return true;"><img name=img2 border=0
  src="images/link_off_products.jpg"></a></td>
  <td width="2"><img src="images/spacer.jpg"></td>
  <td align="center" width="66"><a href="about.html"
  onMouseOver="movr(3);return true;" onMouseOut="mout(3);return true;"
  onClick="return true;"><img name=img3 border=0
  src="images/link_off_about.jpg"></a></td>
  <td width="2"><img src="images/spacer.jpg"></td>
  <td align="center" width="99"><a href="events.html"
  onMouseOver="movr(4);return true;" onMouseOut="mout(4);return true;"
  onClick="return true;"><img name=img4 border=0
  src="images/link_off_events.jpg">    </a>     </td>
  <td width="10"><img src="images/spacer.jpg"></td>
  <td align="center" width="111"><a href="customer_service.html"
  onMouseOver="movr(5);return true;" onMouseOut="mout(5);return true;"
  onClick="return true;"><img name=img5 border=0
  src="images/link_off_cs.jpg"></a></td>
  <td width="10"><img src="images/spacer.jpg"></td>
  <td align="center" width="73"><a href="contact_us.html"
  onMouseOver="movr(6);return true;" onMouseOut="mout(6);return true;"
  onClick="return true;"><img name=img6 border=0
  src="images/link_off_contact.jpg"></a></td>
  <td width="90"><img src="images/spacer.jpg"></td>
  <td width="136"></td>
  </tr>
  </table>

  <table align="center" width="800" border="0" cellpadding="0"
  cellspacing="0">
  <tr>
  <td valign="top" bgcolor="EDF0F7">
  <!-- side bar - products -->
  <table width="175" height="494" border="0" align="center" cellpadding="3"
  cellspacing="0" style="border: 1px solid #ADBCDB">
 <tr>
 <td width="167" height="24" align="center" bgcolor="DDDDDD"><font
 face="arial" size="2" color="000000"><b>Products</b></td>
 </tr>
 <tr bgcolor="#EDF0F7" onMouseOver="this.bgColor='FFFFFF';"
 onMouseOut="this.bgColor='#EDF0F7';">
 <td height="23" valign="middle">
 <ul>
<li>
<label for="acu">Acupuncture</label>
<input id="acu" type="checkbox">
  <ul>
  <li><a href="http://kosim.ca/products/needles.html">Needles</a></li>
  <li><a href="http://kosim.ca/products/acu_models.html">Acupuncture Models</a></li>
  <li><a href="http://kosim.ca/products/electro-therapeutic_devices.html">Electro-Therapeutic Devices</a></li>
  <li><a href="http://kosim.ca/products/others.html">Cupping & Tools</a>
 </li>
  <li><a href="http://kosim.ca/products/books.html">Books</a></li>
  </ul>
  </ul>
<ul>
<li>
<label for="ana">Anatomical</label>
<input id="ana" type="checkbox">
<ul>
  <li><a href="products/charts.html">Charts</a>
  <li><a href="products/models_series_1.html">Model 1</a></li>
  <li><a href="products/models_series_2.html">Model 2</a></li>
  <li><a href="products/models_series_3.html">Model 3</a></li>
</ul>
</li>
</ul>
 <ul>
<li>
<label for="Clinical">Clinical Supplies</label>
<input id="Clinical" type="checkbox">
<ul>
<a href="http://kosim.ca/products/clinic_supplies.html">Clinic Supplies</a>
</li>
</ul>
</ul>
<ul>
<li>
 <label for="Diag">Diagnostic Equipment</label>
<input id="Diag" type="checkbox">
<ul>
      <li><a href="http://kosim.ca/products/hand_evaluation.html">Hand
Evaluation</a></li>
      <li><a href="http://kosim.ca/products/rom_measurement.html">Range of
Motion</a></li>
      <li><a href="http://kosim.ca/products/diagnostic_equip.html">Adjusting
& Diagnostic</a></li>
</ul>

<tr bgcolor="#EDF0F7" onMouseOver="this.bgColor='FFFFFF';"
onMouseOut="this.bgColor='#EDF0F7';">
<td height="23" align="center" valign="middle" bgcolor="#D6D6D6"><a
href="monthly_specials.html" target="_blank" class="special" style="text-
decoration:none"><b><em>Monthly Special!</em></b></a></td>
</tr>
<tr></tr>
</table>
<table width="99%">
<tr>
<td height="0" align="left" valign="middle"> </td>
</tr>
<tr>
<td align="center"><br><a href="order_form.php"><img
src="images/howtoorder.jpg"
width="78" height="95" border="0"></a></td>
</tr>
<tr>
<td align="center"><br>

</td>
</tr>
</table></td>

<td width="620" align="center" valign="top">
<!-- body -->

<script src="bookmark.js" type="text/javascript"></script>
<script src='prototype.js' type='text/javascript'></script>
<script src='effects.js' type='text/javascript'></script>
<script src='rotatingbanner.js' type='text/javascript'></script>

<TABLE width="501" cellspacing="1" cellpadding="0" border="0">
<TR>
<TD valign="top"><div id='rotational-banner-container' style='height:
323px;'>
<div id='progress-bar' style='padding-top: 130px; padding-left:0;' >
<center><img src="images/blue-spoke.gif"></center></div>
<div id='rotational-banner' style='display:none;' >
<div><a href="about.html"><img src="images/rotate_banner_1.jpg" width="590"
height="300" border="0"></a></div>
<div><a href="products/chiropractic_tables.html"><img src="images/banner-
CHIROPRACTIC.jpg" width="590" height="300" border="0"></a></div>
<div><a href="products/laser_therapy.html"><img src="images/banner-
LASER.jpg"
width="590" height="300" border="0"></a></div>
<div><a href="products/massage_therapy.html"><img src="images/banner-
MASSAGE.jpg" width="590" height="300" border="0"></a></div>
<div><a href="products/hi-lo.html"><img src="images/banner-
PHYSIOTHERAPY.jpg"
width="590" height="300" border="0"></a></div>
<div><a href="products/exercise_rehab.html"><img src="images/banner-
EXERCISE.jpg" width="590" height="300" border="0"></a></div>
<div><a href="products/clinic_supplies.html"><img src="images/Strength-
Tape_Banner_2.jpg" width="590" height="300" border="0"></a></div>
<div><a href="products/pillows.html#30-5001"><img
src="images/rotate_banner_2.jpg" width="590" height="300" border="0"></a>
</div>
<div><a href="monthly_specials.html"><img src="images/rotate_banner_3.jpg"
width="590" height="300" border="0"></a></div>
</div>
</TD></TR>
</table>
<table>
<tr><td></td></tr>
</code>```

答:
Doing this with pure CSS, you can use the "checkbox hack". Just tie a label to an input[type="checkbox"] via the for attribute, and show the menu when the input is :checked. You'll also probably want to style the links and the label the same.

li > ul, ul input[type="checkbox"] {
    display: none;
}
ul input[type="checkbox"]:checked + ul {
    display: block;
}

ul a, ul label {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>
    <label for="acu">acupuncture</label>
    <input id="acu" type="checkbox">
    <ul>
      <li>Needles</li>
      <li>Acupuncture Models</li>
      <li>Electro-Therapeutic Devices</li>
      <li>Cupping & Tools
      </li>
      <li>Books</li>
    </ul></code>```

Title: trying to create submenus

Body:
Editing for revision, as you can see the menu and its submenu is hiding behind the banner or picture

Is there something wrong with the code? as it only appears on firefox, all the other web browsers i.e Safari, Chrome, IE and Opera work well

Tel: 1-905-475-2380

  Toll Free: 1-877-50KOSIM
Fax: 905-475-2303

  email: sales@kosim.ca

 Products

Acupuncture
<input id="acu" type="checkbox">

Needles

Acupuncture Models

Electro-Therapeutic Devices

Cupping & Tools

Books

Anatomical
<input id="ana" type="checkbox">

Charts

Model 1

Model 2

Model 3

Clinical Supplies
<input id="Clinical" type="checkbox">

Clinic Supplies

 Diagnostic Equipment
<input id="Diag" type="checkbox">

Hand
Evaluation

Range of
Motion

Adjusting
& Diagnostic

Monthly Special!

Body:
Doing this with pure CSS, you can use the "checkbox hack". Just tie a label to an input[type="checkbox"] via the for attribute, and show the menu when the input is :checked. You'll also probably want to style the links and the label the same.

li > ul, ul input[type="checkbox"] {
    display: none;
}
ul input[type="checkbox"]:checked + ul {
    display: block;
}

ul a, ul label {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}

<ul>
  <li>
    <label for="acu">acupuncture</label>
    <input id="acu" type="checkbox">
    <ul>
      <li><a href="http://kosim.ca/products/needles.html">Needles</a></li>
      <li><a href="http://kosim.ca/products/acu_models.html">Acupuncture Models</a></li>
      <li><a href="http://kosim.ca/products/electro-therapeutic_devices.html">Electro-Therapeutic Devices</a></li>
      <li><a href="http://kosim.ca/products/others.html">Cupping & Tools</a>
      </li>
      <li><a href="http://kosim.ca/products/books.html">Books</a></li>
    </ul>


问:
CreateProcess Failed, unexpected error
I try to create process(calc.exe), but the program does not run correctly. It just crashes after start. I thing the problem is with LPWSTR variable, but I don't have idea how to fix it.

Below is my code.

```<code>#include "stdafx.h"
#include <Windows.h>
#include <cstdio>
#include <string>

using namespace std;

void NewProcess(LPWSTR cmd) {

    printf("Argv Inside funcion: %s\n", cmd[1]);
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    if (!CreateProcess(NULL,
        cmd,
        NULL,
        NULL,
        FALSE,
        0,
        NULL,
        NULL,
        &si,
        &pi)
        )
    {
        printf("CreateProcess failed (%d).\n", GetLastError());
        return;
    }

    printf("Process ID: %d Started", pi.dwProcessId);

    WaitForSingleObject(pi.hProcess, INFINITE);
    printf("\nProcess ID: %d Terminated!", pi.dwProcessId);

    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
}

void main(int argc, TCHAR *argv[])
{
    char text[] = "calc.exe";
    wchar_t wtext[20];
    mbstowcs(wtext, text, strlen(text) + 1);
    LPWSTR ptr = wtext;

    NewProcess(ptr);
    getchar();
}
</code>```

答:
Your printf is interpreting the first character of the command as a pointer to a (non-wide) C string.

Use

```<code>wprintf(L"Argv Inside funcion: %s\n", cmd);
</code>```

and you don't need to complicate main so much (there are no multibyte characters in "calc.exe", so there's nothing to convert):

```<code>int main(int argc, TCHAR *argv[])
{
    auto application[] = L"calc.exe";
    NewProcess(application);
    getchar();
}
</code>```

Title: CreateProcess Failed, unexpected error

Body:
I try to create process(calc.exe), but the program does not run correctly. It just crashes after start. I thing the problem is with LPWSTR variable, but I don't have idea how to fix it.

Below is my code.

#include "stdafx.h"
#include <Windows.h>
#include <cstdio>
#include <string>

using namespace std;

void NewProcess(LPWSTR cmd) {

    printf("Argv Inside funcion: %s\n", cmd[1]);
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    if (!CreateProcess(NULL,
        cmd,
        NULL,
        NULL,
        FALSE,
        0,
        NULL,
        NULL,
        &si,
        &pi)
        )
    {
        printf("CreateProcess failed (%d).\n", GetLastError());
        return;
    }

    printf("Process ID: %d Started", pi.dwProcessId);

    WaitForSingleObject(pi.hProcess, INFINITE);
    printf("\nProcess ID: %d Terminated!", pi.dwProcessId);

    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
}

void main(int argc, TCHAR *argv[])
{
    char text[] = "calc.exe";
    wchar_t wtext[20];
    mbstowcs(wtext, text, strlen(text) + 1);
    LPWSTR ptr = wtext;

    NewProcess(ptr);
    getchar();
}

Body:
Your printf is interpreting the first character of the command as a pointer to a (non-wide) C string.

Use

wprintf(L"Argv Inside funcion: %s\n", cmd);

and you don't need to complicate main so much (there are no multibyte characters in "calc.exe", so there's nothing to convert):

int main(int argc, TCHAR *argv[])
{
    auto application[] = L"calc.exe";
    NewProcess(application);
    getchar();
}


问:
WPF Crash with no stacktrace
I have a big application that randomly throws an exception.
This exception has no reproduction path, and no clear stacktrace in the logs:

```<code>AppDomain.CurrentDomain.UnhandledException System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Windows.Data.ListCollectionView.RestoreLiveShaping()
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at FullDownloadManager.App.Main()
</code>```

As you can see it is a concurrency problem with some collection being changed while UI thread refreshes and iterates through the list.

The problem is to find where is it happening since there is no track of where it occurred.

Does anyone knows a way to detect where this exception is being thrown?

Thanks,

Update:
I'm reviewing all bingings to collections of my program and I found an interesting scenario that might be the reason:

First I have a CollectionViewSource bound with an ObservableCollection

```<code><CollectionViewSource x:Key="deviceViewSource" Source="{Binding ElementName=_this, Path=Devices}"
                          IsLiveGroupingRequested="True">
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription Converter="{StaticResource deviceGroupConverter}" />
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>
</code>```

As the Source is Syncrhonized it might not be a problem. Note that I set LiveGrouping to true

Now it's the interesting part:

```<code><ItemsControl ItemsSource="{Binding Source={StaticResource deviceViewSource}, Path=Groups}"
    <ItemsControl.ItemTemplate>
            <DataTemplate>
                . . .
                <ItemsControl ItemsSource="{Binding Items}" >
                      . . .
                </ItemsControl>
             </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
</code>```

If Items or Groups of CollectionViewSource is not thread-safe, I might have a problem??

Update2:
I confirmed that the problem is with CollectionViewSource and Groupping.
Since I couldn't solve this problem, my solution was to manually group and sync the UI.

As suggested BindingOperations.EnableCollectionSynchronization might solve this issue but I haven't tried.

Anyway, it's weird that CollectionViewSource is not thread-safe, even tough I'm using an ObservableCollection as a Source.

答:
You could try to use

BindingOperations.EnableCollectionSynchronization(myCollection, myLockObject);

That should, at least, eliminate all threading related issues.
This is available since .NET 4.5, just in case you are still using a lower version.

Title: WPF Crash with no stacktrace

Body:
I have a big application that randomly throws an exception.
This exception has no reproduction path, and no clear stacktrace in the logs:

AppDomain.CurrentDomain.UnhandledException System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Windows.Data.ListCollectionView.RestoreLiveShaping()
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at FullDownloadManager.App.Main()

As you can see it is a concurrency problem with some collection being changed while UI thread refreshes and iterates through the list.

The problem is to find where is it happening since there is no track of where it occurred.

Does anyone knows a way to detect where this exception is being thrown?

Thanks,

Update:
I'm reviewing all bingings to collections of my program and I found an interesting scenario that might be the reason:

First I have a CollectionViewSource bound with an ObservableCollection

<CollectionViewSource x:Key="deviceViewSource" Source="{Binding ElementName=_this, Path=Devices}"
                          IsLiveGroupingRequested="True">
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription Converter="{StaticResource deviceGroupConverter}" />
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>

As the Source is Syncrhonized it might not be a problem. Note that I set LiveGrouping to true

Now it's the interesting part:

<ItemsControl ItemsSource="{Binding Source={StaticResource deviceViewSource}, Path=Groups}"
    <ItemsControl.ItemTemplate>
            <DataTemplate>
                . . .
                <ItemsControl ItemsSource="{Binding Items}" >
                      . . .
                </ItemsControl>
             </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

If Items or Groups of CollectionViewSource is not thread-safe, I might have a problem??

Update2:
I confirmed that the problem is with CollectionViewSource and Groupping.
Since I couldn't solve this problem, my solution was to manually group and sync the UI.

As suggested BindingOperations.EnableCollectionSynchronization might solve this issue but I haven't tried.

Anyway, it's weird that CollectionViewSource is not thread-safe, even tough I'm using an ObservableCollection as a Source.


问:
Javascript reassign variable and not break reference
Assuming the following:

let __somevar__ = { hi: 'john' };
Object.defineProperty(window, 'somevar', {
    set: (value)=>{
        __somevar__ = value;
    },
    get: ()=>{
        return __somevar__;
    }
})

let newvar = window.somevar;

// Is it possible to keep the window.somevar reference so that is always uses the setters/getters?
// obviously this actually reassigns newvar instead of using the window.somevar setter.
newvar = { hi: 'senica' }

// These are different now.
console.log(newvar, window.somevar);

// Object.assign won't work because getters/setters are not enumerable.

// A proxy would work, but that's not my question.```

Not super important...was just curious.

Thanks!

答:
This code:

```<code>let newvar = window.somevar;
</code>```

the newvar will contains refrence to somevar.

With

```<code>newvar = { hi: 'senica' };
</code>```

You do override newvar value (the reference) to the new object. That doesn't do anything with somevar.

Body:
Assuming the following:

let __somevar__ = { hi: 'john' };
Object.defineProperty(window, 'somevar', {
    set: (value)=>{
        __somevar__ = value;
    },
    get: ()=>{
        return __somevar__;
    }
})

let newvar = window.somevar;

// Is it possible to keep the window.somevar reference so that is always uses the setters/getters?
// obviously this actually reassigns newvar instead of using the window.somevar setter.
newvar = { hi: 'senica' }

// These are different now.
console.log(newvar, window.somevar);

// Object.assign won't work because getters/setters are not enumerable.

// A proxy would work, but that's not my question.

Not super important...was just curious.

Thanks!

Body:
This code:

let newvar = window.somevar;

the newvar will contains refrence to somevar.

With

newvar = { hi: 'senica' };

You do override newvar value (the reference) to the new object. That doesn't do anything with somevar.


问:
css rotate a pseudo :after or :before content:""
anyway to make a rotation work on the pseudo

```<code>content:"\24B6"?
</code>```

I'm trying to rotate a unicode symbol.

答:
```<code>.process-list:after{
    content: "\2191";
    position: absolute;
    top:50%;
    right:-8px;
    background-color: #ea1f41;
    width:35px;
    height: 35px;
    border:2px solid #ffffff;
    border-radius: 5px;
    color: #ffffff;
    z-index: 10000;
    -webkit-transform: rotate(50deg) translateY(-50%);
    -moz-transform: rotate(50deg) translateY(-50%);
    -ms-transform: rotate(50deg) translateY(-50%);
    -o-transform: rotate(50deg) translateY(-50%);
    transform: rotate(50deg) translateY(-50%);
}
</code>```

you can check this code . i hope you will easily understand.

Body:
anyway to make a rotation work on the pseudo

content:"\24B6"?

I'm trying to rotate a unicode symbol.

Body:
.process-list:after{
    content: "\2191";
    position: absolute;
    top:50%;
    right:-8px;
    background-color: #ea1f41;
    width:35px;
    height: 35px;
    border:2px solid #ffffff;
    border-radius: 5px;
    color: #ffffff;
    z-index: 10000;
    -webkit-transform: rotate(50deg) translateY(-50%);
    -moz-transform: rotate(50deg) translateY(-50%);
    -ms-transform: rotate(50deg) translateY(-50%);
    -o-transform: rotate(50deg) translateY(-50%);
    transform: rotate(50deg) translateY(-50%);
}

you can check this code . i hope you will easily understand.


问:
How to properly include HTML in android project?
I want to make an app, but I don't know anything about Java.
I've decided to add a webpage to my app, which would include all the required styling and logic from JavaScript.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView webView = (WebView)findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient());
    webView.loadUrl("file:///android_asset/www/index.html");
}
</code>```

However,  I get error:

```<code>Error:(13, 53) error: cannot find symbol variable webView
Error:(13, 9) error: cannot find symbol class WebView
Error:(13, 28) error: cannot find symbol class WebView
</code>```

答:
You must add

import android.webkit.WebView;

Body:
I want to make an app, but I don't know anything about Java.
I've decided to add a webpage to my app, which would include all the required styling and logic from JavaScript.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView webView = (WebView)findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient());
    webView.loadUrl("file:///android_asset/www/index.html");
}

However,  I get error:

Error:(13, 53) error: cannot find symbol variable webView
Error:(13, 9) error: cannot find symbol class WebView
Error:(13, 28) error: cannot find symbol class WebView


问:
When should this-> be used?
I was wondering if this-> should be used both:

```<code>void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}
</code>```

I'm wondering if the latter is necessary to be proper or if isEnabled = enabled would suffice.

Thanks

答:
```<code>this->
</code>```

is needed when using the member directly would be ambiguous. This could happen with template code.

Consider this:

```<code>#include <iostream>

template <class T>
class Foo
{
   public:
      Foo() {}
   protected:
      void testing() { std::cout << ":D" << std::endl; }
};

template <class T>
class Bar : public Foo<T>
{
   public:
      void subtest() { testing(); }
};

int main()
{
   Bar<int> bar;
   bar.subtest();
}
</code>```

This will fail since calling testing() is dependent on a template parameter. To say that you mean the function you will have to do this->testing(); or Foo<T>::testing();

Error message:

```<code>temp.cpp: In member function ‘void Bar<T>::subtest()’:
temp.cpp:16:32: error: there are no arguments to ‘testing’ that depend on a template parameter, so a declaration of ‘testing’ must be available [-fpermissive]
temp.cpp:16:32: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
</code>```

ContentLicense: CC BY-SA 2.5

Title: When should this-> be used?

Body:
I was wondering if this-> should be used both:

void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}

I'm wondering if the latter is necessary to be proper or if isEnabled = enabled would suffice.

Thanks

Body:
this->

is needed when using the member directly would be ambiguous. This could happen with template code.

Consider this:

#include <iostream>

template <class T>
class Foo
{
   public:
      Foo() {}
   protected:
      void testing() { std::cout << ":D" << std::endl; }
};

template <class T>
class Bar : public Foo<T>
{
   public:
      void subtest() { testing(); }
};

int main()
{
   Bar<int> bar;
   bar.subtest();
}

This will fail since calling testing() is dependent on a template parameter. To say that you mean the function you will have to do this->testing(); or Foo<T>::testing();

Error message:

temp.cpp: In member function ‘void Bar<T>::subtest()’:
temp.cpp:16:32: error: there are no arguments to ‘testing’ that depend on a template parameter, so a declaration of ‘testing’ must be available [-fpermissive]
temp.cpp:16:32: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)


问:
PHP & MYSQL -- how to dispaly "Already booked please select another date" message
I want to display this message "Already booked - please select another date" If two clients select the same product (pg_no)and date (Date). UNIQUE CONSTRAINT</p>

```<code><?php
//connecting string
include("dbconnect.php");

//assigning
$name=$_REQUEST['Name'];
$tele=$_REQUEST['Tele'];
$city=$_REQUEST['City'];

// UNIQUE CONSTRAINT
$pg_no=$_REQUEST['pg_no']; //product
$date=$_REQUEST['Date'];       //date

//checking if pg_no and Date are same
$check = mysqli_query($db_connect,"SELECT * FROM lstclient WHERE pg_no='{$pg_no}', Date='{$date}'");

{
    echo "Already booked please select another date<br/>";
}
//if not the insert data
else
{
    $query = mysqli_query($db_connect,"INSERT  INTO  lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}

// link closing
mysqli_close($db_connect);

// messaging
if($query)
{
    header("location:index.php?note=failed");
}
else
{
    header("location:index.php?note=success");
}
?>
</code>```

答:
You have two simple options here.

Option 1 - Assign the message to a variable

Instead of echoing your error message, store it in a variable which has a default value (for example, "Success"). Then, where you do the final header() part of your code, return this variable as note:

```<code>$my_str = "Already booked please select another date<br/>";

...

header("location:index.php?note=$my_str");
</code>```

Then on the HTML side, you just need to print the value of $_GET['note'].

Option 2 - See Samuel Fonseca's answer

He beat me to it!

Body:
I want to display this message "Already booked - please select another date" If two clients select the same product (pg_no)and date (Date). UNIQUE CONSTRAINT

<?php
//connecting string
include("dbconnect.php");

//assigning
$name=$_REQUEST['Name'];
$tele=$_REQUEST['Tele'];
$city=$_REQUEST['City'];

// UNIQUE CONSTRAINT
$pg_no=$_REQUEST['pg_no']; //product
$date=$_REQUEST['Date'];       //date

//checking if pg_no and Date are same
$check = mysqli_query($db_connect,"SELECT * FROM lstclient WHERE pg_no='{$pg_no}', Date='{$date}'");

{
    echo "Already booked please select another date
";
}
//if not the insert data
else
{
    $query = mysqli_query($db_connect,"INSERT  INTO  lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}

// link closing
mysqli_close($db_connect);

// messaging
if($query)
{
    header("location:index.php?note=failed");
}
else
{
    header("location:index.php?note=success");
}
?>

Body:
You have two simple options here.

Option 1 - Assign the message to a variable

Instead of echoing your error message, store it in a variable which has a default value (for example, "Success"). Then, where you do the final header() part of your code, return this variable as note:

$my_str = "Already booked please select another date<br/>";

...

header("location:index.php?note=$my_str");

Then on the HTML side, you just need to print the value of $_GET['note'].

Option 2 - See Samuel Fonseca's answer

He beat me to it!


问:
Plot histogram for discrete data
I'm struggling a lot to plot histogram using R for the following data:

```<code>ip_addr_player_id,event_name,level,time_to_finish,

118.93.180.241, Puzzle Complete, Puzzle 1,33.28 seconds
</code>```

This is a single row of data. I need to pot histogram of the number player vs the number of levels played. I was able to successfully plot scatter plot, points, lines etc. but no histogram.

```<code>on Xaxis: number of levels.
Yaxis: Number of player.
</code>```

Each ip address is unique and multiple levels can be played by single ip address. I have attached a sample picture.

答:
I think what you are looking for is actually a bar plot, not a histogram. geom_bar is meant to be used for that. For example:

```<code>library(ggplot2)
ggplot(diamonds, aes(cut)) + geom_bar()
</code>```

ContentLicense: CC BY-SA 4.0

Title: Plot histogram for discrete data

Body:
I'm struggling a lot to plot histogram using R for the following data:

ip_addr_player_id,event_name,level,time_to_finish,

118.93.180.241, Puzzle Complete, Puzzle 1,33.28 seconds

This is a single row of data. I need to pot histogram of the number player vs the number of levels played. I was able to successfully plot scatter plot, points, lines etc. but no histogram.

on Xaxis: number of levels.
Yaxis: Number of player.

Each ip address is unique and multiple levels can be played by single ip address. I have attached a sample picture.

Body:
I think what you are looking for is actually a bar plot, not a histogram. geom_bar is meant to be used for that. For example:

library(ggplot2)
ggplot(diamonds, aes(cut)) + geom_bar()


问:
How to make the caret in Bootstrap multiselect plugin to appear on extreme right and vertically centered
I am using this plugin in my asp.net web application project and the problem is that the caret in the dropdown appears very next to the option text.
Currently chrome inspector gives me this path to the caret

```<code>.multiselect dropdown-toggle btn btn-default multiselect-selected-text caret
</code>```

but any change there isn't working and I don't know how to get it to right via css. Any help would be appreciated greatly. Thanks!

答:
Copying answer from this.
Just extend Bootstrap's .caret class:

```<code>.caret {
position: absolute;
left: 90%;
top: 45%;
}
</code>```

I answered it here because someone may just search it as multiselect bootstrap's plugin caret position solution. The original answer is linked and credit goes all to that guy.

Body:
I am using this plugin in my asp.net web application project and the problem is that the caret in the dropdown appears very next to the option text.
Currently chrome inspector gives me this path to the caret

.multiselect dropdown-toggle btn btn-default multiselect-selected-text caret

but any change there isn't working and I don't know how to get it to right via css. Any help would be appreciated greatly. Thanks!

Body:
Copying answer from this.
Just extend Bootstrap's .caret class:

.caret {
position: absolute;
left: 90%;
top: 45%;
}

I answered it here because someone may just search it as multiselect bootstrap's plugin caret position solution. The original answer is linked and credit goes all to that guy.


问:
Read value from file, after 12 times ","
i have file, where i have separated values via "," - but it's not .csv extension.

I'm trying to get in C# sum from each row, which start from 0.

To this sum, should be taken always value after 12th of ","

```<code>0,P2CZ,1,0,400,400,802,802,18,18,1299,,5,248721,2487221,2
1,1,2487221,1,1_EG_3ST2_1/22,,0,460,18,0
0,,2,0,400,400,982,982,18,18,13999,,9,2321,248731,24878/121,24872021,,,,,,
1,1,2482021,1,1_EG_9_ST2_1/22,,0,460,18,0
1,3,2487821,1,1_EG_U9_ST2_1/22,,0,1042,18,0
1,4,248781,1,1_EG_U9_ST2_1/22,,0,1042,18,0
0,,3,0,2000,2000,80,80,18,18,14/0999,,1,,,,,,,,,,2000,80,1.3,,,,0,0,,,
</code>```

So in this style:

1st row, after 12th "," is value "5",

2nd row skipped, because of 1 on the beginning,

3rd row, after 12th "," is value "9",

4-6 rows skipped, because of 1 on the beginning,

7th row, after 12th "," is value "1"

So sum is 5 + 9 + 1 = 15.

I already input read lines with patch + data taken from label and + extension.

But what next ? How should i handle this ?

```<code>int count = File.ReadLines(patch + label97.Text + ".ext").Count(line => !line.All(char.IsWhiteSpace));
</code>```

答: You should first perform a string split on the character ',' and save the split string as an array. Then you can access the 0th element to see if it is 0 or 1, and then the 12th element for summing.</p>

Body:
i have file, where i have separated values via "," - but it's not .csv extension.

I'm trying to get in C# sum from each row, which start from 0.

To this sum, should be taken always value after 12th of ","

0,P2CZ,1,0,400,400,802,802,18,18,1299,,5,248721,2487221,2
1,1,2487221,1,1_EG_3ST2_1/22,,0,460,18,0
0,,2,0,400,400,982,982,18,18,13999,,9,2321,248731,24878/121,24872021,,,,,,
1,1,2482021,1,1_EG_9_ST2_1/22,,0,460,18,0
1,3,2487821,1,1_EG_U9_ST2_1/22,,0,1042,18,0
1,4,248781,1,1_EG_U9_ST2_1/22,,0,1042,18,0
0,,3,0,2000,2000,80,80,18,18,14/0999,,1,,,,,,,,,,2000,80,1.3,,,,0,0,,,

So in this style:

1st row, after 12th "," is value "5",

2nd row skipped, because of 1 on the beginning,

3rd row, after 12th "," is value "9",

4-6 rows skipped, because of 1 on the beginning,

7th row, after 12th "," is value "1"

So sum is 5 + 9 + 1 = 15.

I already input read lines with patch + data taken from label and + extension.

But what next ? How should i handle this ?

int count = File.ReadLines(patch + label97.Text + ".ext").Count(line => !line.All(char.IsWhiteSpace));


问:
C# Deserialize html inside json property
How can I decode with console application a html string inside json property like this?:

```<code>{
    "type":"text",
    "html":"\n\n\n <div class=\"class\">\n          <ul>\n\n\n  <li class=\"class1\">\n\n\n\n\n\n<a href=\"url\" class=\"class2\"   title='title'  \n >\n    title\n</a>\n\n  ..."
}
</code>```

thanks in advance!

答:
Create a class:

```<code>public class JsonClass
{
public string type{get;set;}
public string html{get;set;}
}
</code>```

Add a reference to Newtonsoft (
http://www.newtonsoft.com/json)

Next, deserialize the content:

```<code>string json = @"{
     //your json
}";
var response =
JsonConvert.DeserializeObject<JsonClass>(json);

var html = response.html;
</code>```

The html variable will contain the results

Body:
How can I decode with console application a html string inside json property like this?:

{
    "type":"text",
    "html":"\n\n\n
\n
\n\n\n
\n\n\n\n\n\n\n    title\n\n\n  ..."
}

thanks in advance!

Body:
Create a class:

public class JsonClass
{
public string type{get;set;}
public string html{get;set;}
}

Add a reference to Newtonsoft (
http://www.newtonsoft.com/json)

Next, deserialize the content:

string json = @"{
     //your json
}";
var response =
JsonConvert.DeserializeObject<JsonClass>(json);

var html = response.html;

The html variable will contain the results


问:
Why can't I access AutoCompleteBox in any function other than Main Window in WPF?
I am trying to do a

```<code>codebox.ItemsSource = codesList;
codebox.PopulateComplete();
</code>```

from the Populating event I have created and I get the error

"The name 'codebox' does not exist in the current context'

This was working when I just populated it from the MainWindow. Anyone know what I am missing?

Thanks!

答:
This looks like it's because codebox is not visible from the scope of where your  Populating event handler is declared. When the Populating event handler is within MainWindow, the codebox control is "visible"  to that code. See here for more info.

Where is your Populating event handler declared?

Also, note that the sender parameter in the Populating event should be a reference to codebox. You could simply cast this to an AutoCompleteBox, and it should work fine, e.g.:

```<code>private void Codebox_Populating(object sender, PopulatingEventArgs e)
{
    AutoCompleteBox _codebox = sender as AutoCompleteBox;

    // Use _codebox here instead of codebox
}
</code>```

Body:
I am trying to do a

codebox.ItemsSource = codesList;
codebox.PopulateComplete();

from the Populating event I have created and I get the error

"The name 'codebox' does not exist in the current context'

This was working when I just populated it from the MainWindow. Anyone know what I am missing?

Thanks!

Body:
This looks like it's because codebox is not visible from the scope of where your  Populating event handler is declared. When the Populating event handler is within MainWindow, the codebox control is "visible"  to that code. See here for more info.

Where is your Populating event handler declared?

Also, note that the sender parameter in the Populating event should be a reference to codebox. You could simply cast this to an AutoCompleteBox, and it should work fine, e.g.:

private void Codebox_Populating(object sender, PopulatingEventArgs e)
{
    AutoCompleteBox _codebox = sender as AutoCompleteBox;

    // Use _codebox here instead of codebox
}


问:
Rendering multiple base64 images with Angular 4 causes performance problems
I'm on a project for a private application and we're using Angular 4 (currently 4.1.2 version) and we have a page where multiple base64 images are being rendered on html. The problem is: When these images are loaded there's a hude drop in performance.

To be more specific, we receive these images from a rest service, and load the images inside a table using something like this:

```<code><tr *ngFor="let i of dataArray;">
    <td>
       <span>
         <img [src]="i.avatar !== null && i.avatar !== undefined ? 'data:image/png;base64,'+i.avatar : 'assets/img/avatar.png'">
       </span>
    </td>
<tr>
</code>```

There's some kind of optimization that could be done, or something that i'm missing here? As I said, when these images are loaded (there are about 30 images), all the application gets laggy, the menu almost stops working makes any action very hard to be executed. This is happening on both Chrome and Firefox, and to be honest I'm not sure if this is a Angular, Html or what issue.

Thanks

答:
Draw to a canvas instead, weirdly it uses less memory

HTML:

```<code><canvas id='displayImage' ></canvas>
</code>```

Javascript:

```<code>    var img = new Image;

    img.onload(function(
       var cv=document.getElementById("displayImage");
       cv.width = this.naturalWidth;
       cv.height = this.naturalHeight;
       cv.getContext("2d").drawImage(this, 0, 0);
    ));
    img.src="base64 Image string";
</code>```

Using this trick, I saved about a gig of RAM per image, and cut processing by 1/100th.

If you want to get fancy, you can use your existing code, but attach a load event that takes the image, puts it on a canvas, removes the image element and places the canvas there.  This way each time an image is added, it gets automatically turned into a canvas.

Body:
I'm on a project for a private application and we're using Angular 4 (currently 4.1.2 version) and we have a page where multiple base64 images are being rendered on html. The problem is: When these images are loaded there's a hude drop in performance.

To be more specific, we receive these images from a rest service, and load the images inside a table using something like this:

There's some kind of optimization that could be done, or something that i'm missing here? As I said, when these images are loaded (there are about 30 images), all the application gets laggy, the menu almost stops working makes any action very hard to be executed. This is happening on both Chrome and Firefox, and to be honest I'm not sure if this is a Angular, Html or what issue.

Thanks

Body:
Draw to a canvas instead, weirdly it uses less memory

HTML:

<canvas id='displayImage' ></canvas>

Javascript:

    var img = new Image;

    img.onload(function(
       var cv=document.getElementById("displayImage");
       cv.width = this.naturalWidth;
       cv.height = this.naturalHeight;
       cv.getContext("2d").drawImage(this, 0, 0);
    ));
    img.src="base64 Image string";

Using this trick, I saved about a gig of RAM per image, and cut processing by 1/100th.

If you want to get fancy, you can use your existing code, but attach a load event that takes the image, puts it on a canvas, removes the image element and places the canvas there.  This way each time an image is added, it gets automatically turned into a canvas.


问:
Gulpjs combine two tasks into a single task
I currently have two tasks, that both compile sass files. I would still like to concat the two directories into separate files but it seems that it would be more maintainable if I could simply create a 'sass' task that would be responsible for all of the sass compilation.

```<code>// Compile Our Sass
gulp.task('bootstrap-sass', function() {
  return gulp.src('./public/bower/bootstrap-sass/lib/*.scss')
    .pipe(sass())
    .pipe(contcat('bootstrap.css'))
    .pipe(gulp.dest('./public/dist/css'));
});

gulp.task('site-sass', function() {
  return gulp.src('./public/app/scss/*.scss')
    .pipe(sass())
    .pipe(contcat('site.css'))
    .pipe(gulp.dest('./public/dist/css'));
});
</code>```

UPDATE:

I've tried this:

```<code>// Compile Our Sass
gulp.task('sass', function() {
  var bootstrap = function() {
    return gulp
      .src('./public/bower/bootstrap-sass/lib/*.scss')
      .pipe(sass())
      .pipe(concat('bootstrap.css'))
      .pipe(gulp.dest('./public/dist/css'));
  };

  var site = function() {
    return gulp
      .src('./public/src/scss/*.scss')
      .pipe(sass())
      .pipe(concat('site.css'))
      .pipe(gulp.dest('./public/dist/css'));
  };

  return Promise.all([bootstrap, site]);
});
</code>```

But now it appears that neither file is being compiled. Any suggestions on what I am doing wrong?

答:
In Gulp version 4, we have parallel, so you can do:

```<code>// Compile Our Sass
gulp.task('bootstrap-sass', function() {
  return gulp.src('./public/bower/bootstrap-sass/lib/*.scss')
    .pipe(sass())
    .pipe(concat('bootstrap.css'))
    .pipe(gulp.dest('./public/dist/css'));
});

gulp.task('site-sass', function() {
  return gulp.src('./public/app/scss/*.scss')
    .pipe(sass())
    .pipe(concat('site.css'))
    .pipe(gulp.dest('./public/dist/css'));
});

gulp.task('sass', gulp.parallel('bootstrap-sass', 'site-sass')); // Combine
</code>```

You can also write it as a single task by doing:

```<code>gulp.task('sass', gulp.parallel(
  function() {
      return gulp.src('./public/bower/bootstrap-sass/lib/*.scss')
        .pipe(sass())
        .pipe(concat('bootstrap.css'))
        .pipe(gulp.dest('./public/dist/css'));
  },
  function() {
      return gulp.src('./public/app/scss/*.scss')
        .pipe(sass())
        .pipe(concat('site.css'))
        .pipe(gulp.dest('./public/dist/css'));
  }));
</code>```

I prefer the first method because it is easier to maintain

Body:
I currently have two tasks, that both compile sass files. I would still like to concat the two directories into separate files but it seems that it would be more maintainable if I could simply create a 'sass' task that would be responsible for all of the sass compilation.

// Compile Our Sass
gulp.task('bootstrap-sass', function() {
  return gulp.src('./public/bower/bootstrap-sass/lib/*.scss')
    .pipe(sass())
    .pipe(contcat('bootstrap.css'))
    .pipe(gulp.dest('./public/dist/css'));
});

gulp.task('site-sass', function() {
  return gulp.src('./public/app/scss/*.scss')
    .pipe(sass())
    .pipe(contcat('site.css'))
    .pipe(gulp.dest('./public/dist/css'));
});

UPDATE:

I've tried this:

// Compile Our Sass
gulp.task('sass', function() {
  var bootstrap = function() {
    return gulp
      .src('./public/bower/bootstrap-sass/lib/*.scss')
      .pipe(sass())
      .pipe(concat('bootstrap.css'))
      .pipe(gulp.dest('./public/dist/css'));
  };

  var site = function() {
    return gulp
      .src('./public/src/scss/*.scss')
      .pipe(sass())
      .pipe(concat('site.css'))
      .pipe(gulp.dest('./public/dist/css'));
  };

  return Promise.all([bootstrap, site]);
});

But now it appears that neither file is being compiled. Any suggestions on what I am doing wrong?

Body:
In Gulp version 4, we have parallel, so you can do:

// Compile Our Sass
gulp.task('bootstrap-sass', function() {
  return gulp.src('./public/bower/bootstrap-sass/lib/*.scss')
    .pipe(sass())
    .pipe(concat('bootstrap.css'))
    .pipe(gulp.dest('./public/dist/css'));
});

gulp.task('site-sass', function() {
  return gulp.src('./public/app/scss/*.scss')
    .pipe(sass())
    .pipe(concat('site.css'))
    .pipe(gulp.dest('./public/dist/css'));
});

gulp.task('sass', gulp.parallel('bootstrap-sass', 'site-sass')); // Combine

You can also write it as a single task by doing:

gulp.task('sass', gulp.parallel(
  function() {
      return gulp.src('./public/bower/bootstrap-sass/lib/*.scss')
        .pipe(sass())
        .pipe(concat('bootstrap.css'))
        .pipe(gulp.dest('./public/dist/css'));
  },
  function() {
      return gulp.src('./public/app/scss/*.scss')
        .pipe(sass())
        .pipe(concat('site.css'))
        .pipe(gulp.dest('./public/dist/css'));
  }));

I prefer the first method because it is easier to maintain


问:
How to produce xml response using REST DSL in Apache Camel
Im trying to consume and produce xml response using rest DSL in Apache camel but it ends with an exception how can i marshal my output POJO object to xml. Below is sy Apache Camel route

```<code><camelContext id="camelContext-02bcd908-03ed-4c2c-878a-b87e3a3668ca"
        xmlns="http://camel.apache.org/schema/blueprint">
        <restConfiguration bindingMode="xml" component="servlet"
            contextPath="/camel-example-servlet-rest-blueprint/rest" port="8181">
            <dataFormatProperty key="mustBeJAXBElement" value="true" />
        </restConfiguration>
        <!-- defines the rest services using the context-path /user -->
        <rest consumes="application/xml" path="/user" produces="application/xml">
            <description>User rest service</description>
            <!-- this is a rest GET to view an user by the given id -->
            <get outType="org.apache.camel.example.rest.User" uri="/{id}">
                <description>Find user by id</description>
                <to uri="bean:userService?method=getUser(${header.id})" />
            </get>
            <!-- this is a rest GET to find all users -->
            <get outType="org.apache.camel.example.rest.User[]" uri="/findAll">
                <description>Find all users</description>
                <to uri="bean:userService?method=listUsers" />
            </get>
        </rest>
    </camelContext>
</code>```

Here is exception im getting

java.io.IOException: org.apache.camel.InvalidPayloadException: No body available of type: javax.xml.bind.JAXBElement but has value: [org.apache.camel.example.rest.User@7f98bc82, org.apache.camel.example.rest.User@4502b96] of type: java.util.TreeMap.Values on: Message[ID-NISB-TEC-C3880-56991-1499145269945-37-3]. Exchange[ID-NISB-TEC-C3880-56991-1499145269945-37-2]
    at org.apache.camel.converter.jaxb.JaxbDataFormat.marshal(JaxbDataFormat.java:153)
    at org.apache.camel.processor.MarshalProcessor.process(MarshalProcessor.java:69)
    at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:109)
    at org.apache.camel.processor.MarshalProcessor.process(MarshalProcessor.java:50)

答:
You can try change your bindingMode to "off".

And when you create the get method, you can use the "consumes" and "produces" parameter equals "application/xml", something like this:

```<code> <get outType="org.apache.camel.example.rest.User[]" uri="/findAll"consumes="application/xml" produces="application/xml">
    <description>Find all users</description>
    <to uri="bean:userService?method=listUsers" />
 </get>
</code>```

Body:
Im trying to consume and produce xml response using rest DSL in Apache camel but it ends with an exception how can i marshal my output POJO object to xml. Below is sy Apache Camel route

<camelContext id="camelContext-02bcd908-03ed-4c2c-878a-b87e3a3668ca"
        xmlns="http://camel.apache.org/schema/blueprint">
        <restConfiguration bindingMode="xml" component="servlet"
            contextPath="/camel-example-servlet-rest-blueprint/rest" port="8181">
            <dataFormatProperty key="mustBeJAXBElement" value="true" />
        </restConfiguration>

        <rest consumes="application/xml" path="/user" produces="application/xml">
            <description>User rest service</description>

            <get outType="org.apache.camel.example.rest.User" uri="/{id}">
                <description>Find user by id</description>
                <to uri="bean:userService?method=getUser(${header.id})" />
            </get>

            <get outType="org.apache.camel.example.rest.User[]" uri="/findAll">
                <description>Find all users</description>
                <to uri="bean:userService?method=listUsers" />
            </get>
        </rest>
    </camelContext>

Here is exception im getting

java.io.IOException: org.apache.camel.InvalidPayloadException: No body available of type: javax.xml.bind.JAXBElement but has value: [org.apache.camel.example.rest.User@7f98bc82, org.apache.camel.example.rest.User@4502b96] of type: java.util.TreeMap.Values on: Message[ID-NISB-TEC-C3880-56991-1499145269945-37-3]. Exchange[ID-NISB-TEC-C3880-56991-1499145269945-37-2]
    at org.apache.camel.converter.jaxb.JaxbDataFormat.marshal(JaxbDataFormat.java:153)
    at org.apache.camel.processor.MarshalProcessor.process(MarshalProcessor.java:69)
    at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:109)
    at org.apache.camel.processor.MarshalProcessor.process(MarshalProcessor.java:50)

Body:
You can try change your bindingMode to "off".

And when you create the get method, you can use the "consumes" and "produces" parameter equals "application/xml", something like this:

 <get outType="org.apache.camel.example.rest.User[]" uri="/findAll"consumes="application/xml" produces="application/xml">
    <description>Find all users</description>
    <to uri="bean:userService?method=listUsers" />
 </get>


问:
Replace every cell in a matrix with the average of adjcent cells
Requirement: Must be done in-place.

For example:

Given matrix

```<code>1, 2, 3
4, 5, 6
7, 8, 9
</code>```

Should replace by the average of its  sum of 3*3 neighbor cells and its own:

```<code>(1+2+4+5)/4,       (2+1+3+4+5+6)/6 ,            (3+2+6+5)/4
(1+2+5+4+7+8)/6,   (1+2+3+4+5+6+7+8+9)/9,       (2+3+5+6+8+9)/6
(4+5+7+8)/4,       (4+5+6+7+8+9)/6,             (5+6+8+9)/4
</code>```

which is:

```<code>All floating number convert to int

3,      3.5(3), 4             3, 3, 4
4.5(4),  5, 5.5(5)  =>        4, 5, 5
6,      6.5(6), 7             6, 6, 7
</code>```

I tried to just iterate over the matrix and update each cell, but I found this will affect the future calculation:

Say I update the original 1 to 3, but when I when I tried to update the original 2, the original 1 becomes 3 now.

Copying the original matrix for calculating average is a workaround but it's a bad idea, Could we achieve that without using that much space?

答:
You must have some kind of cache for the result data so you can keep reference to the original data. I don't think there is a way around it.

If the data set is large, you could optimize by using a smaller data buffer (like looking through a keyhole) and 'scrolling' the input matrix as you update it. In your case, you could use a buffer as small as 3x3.
It is a compromise between speed and space though. The smaller your buffer, the worse the performance will be.

To visualize the problem, starting from the top-left (0,0) of the dataset:

(result values are rounded down for simplicity)

First step: update first 4 cells (prime the buffer)

```<code>// Data Set        // Data Viewport // Result Set
01,02,03,04,05     01,02,03         04,04,??
06,07,08,09,10     06,07,08         06,07,??
11,12,13,14,15     11,12,13         ??,??,??
16,17,18,19,20
21,22,23,24,25
</code>```

then for each iteration..

( new values indicated with [xx] )

++ update first column in Data Set from Result Set

```<code>// Data Set        // Data Viewport   // Result Set
[04],02,03,04,05   01,02,03         04,04,??
[06],07,08,09,10   06,07,08         06,07,??
 11 ,12,13,14,15   11,12,13         ??,??,??
 16 ,17,18,19,20
 21 ,22,23,24,25
</code>```

++ shift Data Viewport and Result Set right 1 column

```<code>// Data Set        // Data Viewport // Result Set
[04],02,03,04,05   02,03,04         04,[03],??
[06],07,08,09,10   07,08,09         07,[08],??
 11 ,12,13,14,15   12,13,14         ??, ?? ,??
 16 ,17,18,19,20
 21 ,22,23,24,25
</code>```

++ update middle column of Result Set

```<code>// Data Set        // Data Viewport // Result Set
[04],02,03,04,05   02,03,04         04,[05],??
[06],07,08,09,10   07,08,09         07,[08],??
 11 ,12,13,14,15   12,13,14         ??, ?? ,??
 16 ,17,18,19,20
 21 ,22,23,24,25
</code>```

At the following iteration, the data state would be:

```<code>// Data Set        // Data Viewport // Result Set
04,[04],03,04,05   03,04,05         05,[06],??
06,[07],08,09,10   08,09,10         08,[09],??
11, 12 ,13,14,15   13,14,15         ??, ?? ,??
16, 17 ,18,19,20
21, 22 ,23,24,25
</code>```

.. etc

Don't forget to handle the other edge cases.

*The Data Viewport representation is just for visualization. In code, the actual viewport would be the result buffer.

Body:
Requirement: Must be done in-place.

For example:

Given matrix

1, 2, 3
4, 5, 6
7, 8, 9

Should replace by the average of its  sum of 3*3 neighbor cells and its own:

(1+2+4+5)/4,       (2+1+3+4+5+6)/6 ,            (3+2+6+5)/4
(1+2+5+4+7+8)/6,   (1+2+3+4+5+6+7+8+9)/9,       (2+3+5+6+8+9)/6
(4+5+7+8)/4,       (4+5+6+7+8+9)/6,             (5+6+8+9)/4

which is:

All floating number convert to int

3,      3.5(3), 4             3, 3, 4
4.5(4),  5, 5.5(5)  =>        4, 5, 5
6,      6.5(6), 7             6, 6, 7

I tried to just iterate over the matrix and update each cell, but I found this will affect the future calculation:

Say I update the original 1 to 3, but when I when I tried to update the original 2, the original 1 becomes 3 now.

Copying the original matrix for calculating average is a workaround but it's a bad idea, Could we achieve that without using that much space?

Body:
You must have some kind of cache for the result data so you can keep reference to the original data. I don't think there is a way around it.

If the data set is large, you could optimize by using a smaller data buffer (like looking through a keyhole) and 'scrolling' the input matrix as you update it. In your case, you could use a buffer as small as 3x3.
It is a compromise between speed and space though. The smaller your buffer, the worse the performance will be.

To visualize the problem, starting from the top-left (0,0) of the dataset:

(result values are rounded down for simplicity)

First step: update first 4 cells (prime the buffer)

// Data Set        // Data Viewport // Result Set
01,02,03,04,05     01,02,03         04,04,??
06,07,08,09,10     06,07,08         06,07,??
11,12,13,14,15     11,12,13         ??,??,??
16,17,18,19,20
21,22,23,24,25

then for each iteration..

( new values indicated with [xx] )

++ update first column in Data Set from Result Set

// Data Set        // Data Viewport   // Result Set
[04],02,03,04,05   01,02,03         04,04,??
[06],07,08,09,10   06,07,08         06,07,??
 11 ,12,13,14,15   11,12,13         ??,??,??
 16 ,17,18,19,20
 21 ,22,23,24,25

++ shift Data Viewport and Result Set right 1 column

// Data Set        // Data Viewport // Result Set
[04],02,03,04,05   02,03,04         04,[03],??
[06],07,08,09,10   07,08,09         07,[08],??
 11 ,12,13,14,15   12,13,14         ??, ?? ,??
 16 ,17,18,19,20
 21 ,22,23,24,25

++ update middle column of Result Set

// Data Set        // Data Viewport // Result Set
[04],02,03,04,05   02,03,04         04,[05],??
[06],07,08,09,10   07,08,09         07,[08],??
 11 ,12,13,14,15   12,13,14         ??, ?? ,??
 16 ,17,18,19,20
 21 ,22,23,24,25

At the following iteration, the data state would be:

// Data Set        // Data Viewport // Result Set
04,[04],03,04,05   03,04,05         05,[06],??
06,[07],08,09,10   08,09,10         08,[09],??
11, 12 ,13,14,15   13,14,15         ??, ?? ,??
16, 17 ,18,19,20
21, 22 ,23,24,25

.. etc

Don't forget to handle the other edge cases.

*The Data Viewport representation is just for visualization. In code, the actual viewport would be the result buffer.


问:
Why doesn't a simple "Hello World"-style program compile with Turbo C++?
I have started learning C++ for my programming class. I have downloaded this "Hello World" program:

```<code>#include <iostream>
using namespace std;

int main()
{
    cout << "Hello, World!";
    return 0;
}
</code>```

but Turbo C++ complains:

```<code>Error D:\HELLO.CPP 1: Unable to open include file 'IOSTREAM'
Error D:\HELLO.CPP 2: Declaration syntax error
Error D:\HELLO.CPP 6: Undefined symbol 'cout'
</code>```

What's wrong with this very simple program? How can I correct these errors?

答:
Turbo C++ is a very old compiler and it is a little bit different from the GNU C++ compiler. The code you shared will work perfectly with the GNU compiler but to run it with Turbo C++ you need to make a few changes:

1. Change the name of header file from iostream to iostream.h

2. And remove the line "using namespace std" It is not required in Turbo C++.
Here is the modified code:

```<code>#include <iostream.h>

int main()
{
  cout << "Hello, World!";
  return 0;
}
</code>```

Body:
I have started learning C++ for my programming class. I have downloaded this "Hello World" program:

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello, World!";
    return 0;
}

but Turbo C++ complains:

Error D:\HELLO.CPP 1: Unable to open include file 'IOSTREAM'
Error D:\HELLO.CPP 2: Declaration syntax error
Error D:\HELLO.CPP 6: Undefined symbol 'cout'

What's wrong with this very simple program? How can I correct these errors?

Body:
Turbo C++ is a very old compiler and it is a little bit different from the GNU C++ compiler. The code you shared will work perfectly with the GNU compiler but to run it with Turbo C++ you need to make a few changes:

1. Change the name of header file from iostream to iostream.h

2. And remove the line "using namespace std" It is not required in Turbo C++.
Here is the modified code:

#include <iostream.h>

int main()
{
  cout << "Hello, World!";
  return 0;
}


问:
Promise not getting resolved when using Page Object Model with Protractor
I'm trying to implement the Page Object Model in my project, and I'm having trouble getting it to work. I want to the title of the current page using browser.getTitle(), which works perfectly when used directly in login.spec.js, but doesn't work when moved to login.po.js. Here's what my setup currently looks like:

login.spec.js

```<code>var LoginPage = require('../../pages/user/login.po.js'),
    expect = require('chai').expect;

describe('Login', function() {
    var page;

    beforeEach(function () {
        page = new LoginPage();
    });

    it('should be able to get the page title', function() {
        expect(page.getLoginPageTitle).to.equal('Test');
    });
});
</code>```

login.po.js

```<code>'use strict';

var LoginPage = function(){
    browser.get('http://localhost:3000/');
};

LoginPage.prototype = Object.create({}, {
    getLoginPageTitle: {get: function() {
        browser.getTitle().then(function(res){
            return res;
        });
    }}
});

module.exports = LoginPage;
</code>```

And the error I get:
    AssertionError: expected undefined to equal 'Test'

Upon further investigating, it seems like the browser.getTitle() promise in my login.po.js isn't getting resolved.

Any ideas on what I'm doing wrong? The page loads correctly in Chrome and Chrome shows the correct page title.

答:
you should add an extra return in your PageObject. You are returning the result of the resolved promise browser.getTitle(), but not the promise itself, see below.

'use strict';

var LoginPage = function() {
  browser.get('http://localhost:3000/');
};

LoginPage.prototype = Object.create({}, {
  getLoginPageTitle: {
    get: function() {
      return browser.getTitle();
    }
  }
});

module.exports = LoginPage;```

Body:
I'm trying to implement the Page Object Model in my project, and I'm having trouble getting it to work. I want to the title of the current page using browser.getTitle(), which works perfectly when used directly in login.spec.js, but doesn't work when moved to login.po.js. Here's what my setup currently looks like:

login.spec.js

var LoginPage = require('../../pages/user/login.po.js'),
    expect = require('chai').expect;

describe('Login', function() {
    var page;

    beforeEach(function () {
        page = new LoginPage();
    });

    it('should be able to get the page title', function() {
        expect(page.getLoginPageTitle).to.equal('Test');
    });
});

login.po.js

'use strict';

var LoginPage = function(){
    browser.get('http://localhost:3000/');
};

LoginPage.prototype = Object.create({}, {
    getLoginPageTitle: {get: function() {
        browser.getTitle().then(function(res){
            return res;
        });
    }}
});

module.exports = LoginPage;

And the error I get:
    AssertionError: expected undefined to equal 'Test'

Upon further investigating, it seems like the browser.getTitle() promise in my login.po.js isn't getting resolved.

Any ideas on what I'm doing wrong? The page loads correctly in Chrome and Chrome shows the correct page title.


问:
Cleanup ExUnit test examples
I have the following tests in phoenix app:

```<code>defmodule TattooBackend.Web.API.V1.PasswordControllerTest do
  use TattooBackend.Web.ConnCase, async: true
  use Bamboo.Test

  alias TattooBackend.Web.Endpoint
  alias TattooBackend.Accounts.Account
  alias TattooBackend.Repo
  alias Phoenix.Token
  alias Comeonin.Bcrypt
  import TattooBackend.AuthenticationRequiredTest

  test "without passwords", %{conn: conn} do
    account = insert(:account)
    token   = Token.sign(Endpoint, "account_id", account.id)

    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create))

    assert json_response(conn, 422)
  end

  test "with wrong password confirmation", %{conn: conn} do
    account = insert(:account)
    token   = Token.sign(Endpoint, "account_id", account.id)
    params  = %{password: "new-password", password_confirmation: "password"}

    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create, params))

    assert json_response(conn, 422)
  end
end
</code>```

Those lines are repeated over tests:

```<code>account = insert(:account)
token   = Token.sign(Endpoint, "account_id", account.id)
</code>```

Any idea how to make it more DRY?

答:
If you want to execute those two lines in all tests, you can put the repetitive code in a setup callback and then use pattern matching to fetch those in each test:

```<code>defmodule TattooBackend.Web.API.V1.PasswordControllerTest do
  ...

  setup do
    account = insert(:account)
    token   = Token.sign(Endpoint, "account_id", account.id)
    [account: account, token: token]
  end

  test "without passwords", %{conn: conn, account: account, token: token} do
    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create))

    assert json_response(conn, 422)
  end

  test "with wrong password confirmation", %{conn: conn, account: account, token: token} do
    params  = %{password: "new-password", password_confirmation: "password"}

    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create, params))

    assert json_response(conn, 422)
  end
end
</code>```

setup will execute its code before each test and then pass the account and token to each test.

Title: Cleanup ExUnit test examples

Body:
I have the following tests in phoenix app:

defmodule TattooBackend.Web.API.V1.PasswordControllerTest do
  use TattooBackend.Web.ConnCase, async: true
  use Bamboo.Test

  alias TattooBackend.Web.Endpoint
  alias TattooBackend.Accounts.Account
  alias TattooBackend.Repo
  alias Phoenix.Token
  alias Comeonin.Bcrypt
  import TattooBackend.AuthenticationRequiredTest

  test "without passwords", %{conn: conn} do
    account = insert(:account)
    token   = Token.sign(Endpoint, "account_id", account.id)

    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create))

    assert json_response(conn, 422)
  end

  test "with wrong password confirmation", %{conn: conn} do
    account = insert(:account)
    token   = Token.sign(Endpoint, "account_id", account.id)
    params  = %{password: "new-password", password_confirmation: "password"}

    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create, params))

    assert json_response(conn, 422)
  end
end

Those lines are repeated over tests:

account = insert(:account)
token   = Token.sign(Endpoint, "account_id", account.id)

Any idea how to make it more DRY?

Body:
If you want to execute those two lines in all tests, you can put the repetitive code in a setup callback and then use pattern matching to fetch those in each test:

defmodule TattooBackend.Web.API.V1.PasswordControllerTest do
  ...

  setup do
    account = insert(:account)
    token   = Token.sign(Endpoint, "account_id", account.id)
    [account: account, token: token]
  end

  test "without passwords", %{conn: conn, account: account, token: token} do
    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create))

    assert json_response(conn, 422)
  end

  test "with wrong password confirmation", %{conn: conn, account: account, token: token} do
    params  = %{password: "new-password", password_confirmation: "password"}

    conn =
      conn
      |> put_req_header("authorization", "#{token}")
      |> post(api_v1_password_path(conn, :create, params))

    assert json_response(conn, 422)
  end
end

setup will execute its code before each test and then pass the account and token to each test.


问:
Office Word Add-in compatibility
I have a MS Word Add in and it is rejected by MS when I submit to Office store because it is not compatible with MS Word 2013 and MS Word 2016. But I just want to use my add in in MS Word online environment, how can I config my add on manifest file to prevent using from MS Word?

If it is impossible, can we prevent using from MS 2013? I see this add-in only available for MS Word 2016 and Word online only. How can we config it?

Please help me,
Thanks

答:
I had the same problem. The solution is easy.
You must change your manifest xml. If you add the requirements for Word API 1.1 Office 2013 disappears automaticly when you submit it to the Office Store.

```<code><Requirements>
    <Sets DefaultMinVersion="1.1">
    <Set Name="WordApi" MinVersion="1.1"/>
    </Sets>
</Requirements>
</code>```

For some crazy reason the order of the elements in the manifext xml is important. Add Requirements between Hosts and DefaultSettings.

Title: Office Word Add-in compatibility

Body:
I had the same problem. The solution is easy.
You must change your manifest xml. If you add the requirements for Word API 1.1 Office 2013 disappears automaticly when you submit it to the Office Store.

<Requirements>
    <Sets DefaultMinVersion="1.1">
    <Set Name="WordApi" MinVersion="1.1"/>
    </Sets>
</Requirements>

For some crazy reason the order of the elements in the manifext xml is important. Add Requirements between Hosts and DefaultSettings.


问:
How to have border color change on image hover/mousover?
I know how to add a border to images, but how do I change the color of the border on image hover/mouseover, I would like to to this to multiple images on the same page, so far I have failed to find a plugin that does this.

I spent like 5 hours looking for a plugin to do this, feel my pain!!!

Basically, I want an image to do what a button does. When user hovers the mouse over the button the color of the border changes.

答:
If you want to add a border on hovering the element, then:

```<code><style>
.nameofclass:hover {
border: 1px solid red;
}
</style>
</code>```

The above CSS will apply a red border with 1px width. Change the nameofclass to name of the element e.g image/button you're trying to add effects on.

NOTE: The

```

I hope it helps, if you need help, feel free to ask.

UPDATE: Use the following code for adding box shadow!

-webkit-box-shadow: 3px 3px 18px 3px rgba(0,0,0,0.91) ;
box-shadow: 3px 3px 18px 3px rgba(0,0,0,0.91) ;

Just copy paste it under the code I gave you before in this very answer.

Body:
If you want to add a border on hovering the element, then:

<style>
.nameofclass:hover {
border: 1px solid red;
}
</style>

The above CSS will apply a red border with 1px width. Change the nameofclass to name of the element e.g image/button you're trying to add effects on.

NOTE: The <style> tag is added within the <head> tag. Something like:

<head>
    <style>
    .nameofclass:hover {
    border: 1px solid red;
    }
    </style>
</head>

I hope it helps, if you need help, feel free to ask.

UPDATE: Use the following code for adding box shadow!

-webkit-box-shadow: 3px 3px 18px 3px rgba(0,0,0,0.91) ;
box-shadow: 3px 3px 18px 3px rgba(0,0,0,0.91) ;

Just copy paste it under the code I gave you before in this very answer.