问:
Marklogic JSON document field index
I have a ML database with all json documents.. I am having an issue with field creation for this documents.. Say I have a document

```<code>{
    "id": "1452016",
    "name": "ALEXA488",
    "identifyingInfo": {
        "preparation": {
            "chemicalConjugations": [{
                "name": "ALEXA 488"
            }]
        }
    }
}
</code>```

I created a field for top level json element name ..

```<code>{
 "field-name": "concept_name",
 "field-path": [
  {
    "path": "/name",
    "weight": 1
  }
  ],
  "word-lexicon" :["http://marklogic.com/collation/en/S1"]
}
</code>```

I created a field range index as well on this field..

Now when I do the search like this

```<code>xquery version "1.0-ml";
import module namespace search = "http://marklogic.com/appservices/search" at "/MarkLogic/appservices/search/search.xqy";

let $search := ' (concept_name:(*ALEXA*))'

let $options :=
   <options xmlns="http://marklogic.com/appservices/search">
    <constraint name="collection">
        <collection prefix=""/>
    </constraint>
    <constraint name="concept_name">
        <word>
            <field name="concept_name" collation="http://marklogic.com/collation/en/S1"/>
        </word>
    </constraint>
    <term>
        <term-option>case-insensitive</term-option>
        <term-option>punctuation-insensitive</term-option>
        <term-option>whitespace-insensitive</term-option>
        <term-option>wildcarded</term-option>
    </term>
    <return-facets>false</return-facets>
    <return-values>false</return-values>
    <return-constraints>false</return-constraints>
    <return-frequencies>false</return-frequencies>
    <return-qtext>false</return-qtext>
    <search-option>format-json</search-option>
    <search-option>score-simple</search-option>
</options>

let $start := 1
let $page-length :=1

 let $result := search:search($search, $options, $start, $page-length)

return $result
</code>```

The search is matching the top level name and also identifyingInfo/preparation/chemicalConjugations/name..

What should be the field path, so that it only matches the top level json element, in this case name ?

答:
I got this to work. Replace your constraint with:

```<code><constraint name="concept_name">
  <value>
    <field name="concept_name" />
  </value>
</constraint>
</code>```

In your field, turn on field value searches and trailing wildcard searches.

I created three docs in a database; one just like your sample, one that had "ALEXA" only in /name, and one that had "ALEXA" only in the other name. My test correctly found the two documents.

Title: Marklogic JSON document field index

Body:
I have a ML database with all json documents.. I am having an issue with field creation for this documents.. Say I have a document

{
    "id": "1452016",
    "name": "ALEXA488",
    "identifyingInfo": {
        "preparation": {
            "chemicalConjugations": [{
                "name": "ALEXA 488"
            }]
        }
    }
}

I created a field for top level json element name ..

{
 "field-name": "concept_name",
 "field-path": [
  {
    "path": "/name",
    "weight": 1
  }
  ],
  "word-lexicon" :["http://marklogic.com/collation/en/S1"]
}

I created a field range index as well on this field..

Now when I do the search like this

xquery version "1.0-ml";
import module namespace search = "http://marklogic.com/appservices/search" at "/MarkLogic/appservices/search/search.xqy";

let $search := ' (concept_name:(*ALEXA*))'

let $options :=
   <options xmlns="http://marklogic.com/appservices/search">
    <constraint name="collection">
        <collection prefix=""/>
    </constraint>
    <constraint name="concept_name">
        <word>
            <field name="concept_name" collation="http://marklogic.com/collation/en/S1"/>
        </word>
    </constraint>
    <term>
        <term-option>case-insensitive</term-option>
        <term-option>punctuation-insensitive</term-option>
        <term-option>whitespace-insensitive</term-option>
        <term-option>wildcarded</term-option>
    </term>
    <return-facets>false</return-facets>
    <return-values>false</return-values>
    <return-constraints>false</return-constraints>
    <return-frequencies>false</return-frequencies>
    <return-qtext>false</return-qtext>
    <search-option>format-json</search-option>
    <search-option>score-simple</search-option>
</options>

let $start := 1
let $page-length :=1

 let $result := search:search($search, $options, $start, $page-length)

return $result

The search is matching the top level name and also identifyingInfo/preparation/chemicalConjugations/name..

What should be the field path, so that it only matches the top level json element, in this case name ?

Body:
I got this to work. Replace your constraint with:

<constraint name="concept_name">
  <value>
    <field name="concept_name" />
  </value>
</constraint>

In your field, turn on field value searches and trailing wildcard searches.

I created three docs in a database; one just like your sample, one that had "ALEXA" only in /name, and one that had "ALEXA" only in the other name. My test correctly found the two documents.


来源: stackexchange

问:
How to write a query joining multiple tables that returns a result set with null for columns
If i have these tables

```<code>address         quarter
------------  ----------
address_id     quarter_id
quarter_id     quarter_name
address_name   quarter_code
</code>```

If the user provides the address information (address_name) the quarter will be identified because the address is within a quarter. But if the user doesn't provide an address but a quarter the address information will not be available.

```<code>Select      address.address_name,
            quarter.quarter_code
From        address
some_join   quarter on  address.quarter_id = quarter.quarter_id
where       address.address_name like @param
or          quarter.quarter_code = @param
</code>```

I want a result like this if the where clause matches on the address_name condition.

```<code>address_name  | quarter_code
stress eight     14400459
</code>```

But if the user types 14400459

```<code>address_name  | quarter_code
null            14400459
</code>```

I had difficult to formulate this question. It's been a long time since I saw sql joins and this kind of thing get out of mind so easily.

答:
The right join can be tricky; here is how it should be constructed, plus you want the first non-null value to match the parameter:

```<code>select *
from address as a
right join quarter as q
on q.quarter_id = a.quarter_id
and coalesce(a.address_name, q.quarter_code) = @param
</code>```

Or better yet:

```<code>select *
from address as a
right join quarter as q
on q.quarter_id = a.quarter_id
and (
    a.address_name = @param
    or
    q.quarter_code = @param
    )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If i have these tables

address         quarter
------------  ----------
address_id     quarter_id
quarter_id     quarter_name
address_name   quarter_code

If the user provides the address information (address_name) the quarter will be identified because the address is within a quarter. But if the user doesn't provide an address but a quarter the address information will not be available.

Select      address.address_name,
            quarter.quarter_code
From        address
some_join   quarter on  address.quarter_id = quarter.quarter_id
where       address.address_name like @param
or          quarter.quarter_code = @param

I want a result like this if the where clause matches on the address_name condition.

address_name  | quarter_code
stress eight     14400459

But if the user types 14400459

address_name  | quarter_code
null            14400459

I had difficult to formulate this question. It's been a long time since I saw sql joins and this kind of thing get out of mind so easily.

Body:
The right join can be tricky; here is how it should be constructed, plus you want the first non-null value to match the parameter:

select *
from address as a
right join quarter as q
on q.quarter_id = a.quarter_id
and coalesce(a.address_name, q.quarter_code) = @param

Or better yet:

select *
from address as a
right join quarter as q
on q.quarter_id = a.quarter_id
and (
    a.address_name = @param
    or
    q.quarter_code = @param
    )


问:
How to write const ref without allowing temporary creation
I want to be able to supply functions which take an existing object of a given type by const reference.

i.e. I want by-const-ref-but-no-temporaries-created. [edited this phrase to clarify it!]

I can't think of any way to express that in C++ directly:

1 void fn(const T & t)

will create a temporary T from an S if a (non-explicit) T(S) exists.

2 void fn(T & t)

will only allow a non-const t as an argument (I need this to work for const t's as well).

3 void fn(T && t)

requires a non-const rvalue.

4 void fn(const T && t)

requires a const rvalue

Is there any way to do this - accept any argument by reference, const, without allowing a temp to be created?

Failed thoughts:

Supplying #2 and #4 without supply the other two, and now we have an unambiguous fn that takes a reference to any existing T (but won't silently generate a temporary)?

Nope, that isn't adequate either, because I need to also be able to bind to a const T & - Where the target object is itself been passed in by const reference to our caller...

I guess I see no way to achieve this except in the case where I can control T to ensure it doesn't supply an implicit T(S).

Am I right, or am I overlooking some solution?

答:
If this is a free function then you can do as nwp suggests and add an overload taking a rvalue reference and deleting it.

```<code>void fn(const SomeType& t)
{
    // stuff to do with const lvalue
}

void fn(SomeType&&) = delete; // compiler error if you give me an rvalue
</code>```

This works because a rvalue reference is preferred over a reference to const.  So when overload resolution kicks in and you pass a temporary the compiler will select void fn(const T&&) as the best match.  After that it will see that the function is deleted and it will issue a compiler error

Body:
If this is a free function then you can do as nwp suggests and add an overload taking a rvalue reference and deleting it.

void fn(const SomeType& t)
{
    // stuff to do with const lvalue
}

void fn(SomeType&&) = delete; // compiler error if you give me an rvalue

This works because a rvalue reference is preferred over a reference to const.  So when overload resolution kicks in and you pass a temporary the compiler will select void fn(const T&&) as the best match.  After that it will see that the function is deleted and it will issue a compiler error


问:
Delphi SOAP Server - Document/Literal - Possible?
We're using Delphi2005 with Delphi2007 patches, also experimenting with DelphiXE SOAP libraries.  But I've hit a snag...
We've got an internal service that our app has been consuming for a year now. The service uses document/literal convention, and is used by several systems on several platforms (java, .Net, and ours - Delphi2005).  Now we need to become a publisher and not just a consumer.  So we're building a server service.  And the WSDL is coming out wrong.  I consume the "official" WSDL as document/literal, and when I try to serve it back as a service, it comes out as RPC style.  Even though I've set the options of the HTTPSoapPascalInvoker.Converter to be [soLiteralParams, soDocument].
Now that I do some more searching, I find statements like this:
"Delphi for Win32 does not support creating Document Literal Soap Servers."
[ http://www.experts-exchange.com/Programming/Languages/Pascal/Delphi/Q_22664248.html ]

That quote is a few years old. Does anyone know if it still applies?

I AM in a position to move this portion of the project to Delphi2010 or XE if necessary, but I'd rather not (throws a wrench into our automated build process).  Including the SOAP libs is ok, and we already do that.

So, if anyone knows whether it's possible to write a Win32 Delphi web service in 2005, 2010 or XE that will produce a WSDL that conforms to document/literal, I'd be very, very happy.

答: You can use WST. It is compatible with Delphi. Better check out from svn as the 0.5 release is actualy outdated. </p>

ContentLicense: CC BY-SA 2.5


问:
How does this float square root approximation work?
I found a rather strange but working square root approximation for floats; I really don't get it. Can someone explain me why this code works?

```<code>float sqrt(float f)
{
    const int result = 0x1fbb4000 + (*(int*)&f >> 1);
    return *(float*)&result;
}
</code>```

I've test it a bit and it outputs values off of std::sqrt() by about 1 to 3%. I know of the Quake III's fast inverse square root and I guess it's something similar here (without the newton iteration) but I'd really appreciate an explanation of how it works.

(nota: I've tagged it both c and c++ since it's both valid-ish (see comments) C and C++ code)

答:
Let y = sqrt(x),

it follows from the properties of logarithms that log(y) = 0.5 * log(x) (1)

Interpreting a normal float as an integer gives INT(x) = Ix = L * (log(x) + B - σ) (2)

where L = 2^N, N the number of bits of the significand, B is the exponent bias, and σ is a free factor to tune the approximation.

Combining (1) and (2) gives: Iy = 0.5 * (Ix + (L * (B - σ)))

Which is written in the code as (*(int*)&x >> 1) + 0x1fbb4000;

Find the σ so that the constant equals 0x1fbb4000 and determine whether it's optimal.

Body:
I found a rather strange but working square root approximation for floats; I really don't get it. Can someone explain me why this code works?

float sqrt(float f)
{
    const int result = 0x1fbb4000 + (*(int*)&f >> 1);
    return *(float*)&result;
}

I've test it a bit and it outputs values off of std::sqrt() by about 1 to 3%. I know of the Quake III's fast inverse square root and I guess it's something similar here (without the newton iteration) but I'd really appreciate an explanation of how it works.

(nota: I've tagged it both c and c++ since it's both valid-ish (see comments) C and C++ code)


问:
R nested lists indexing with another list
I am facing some nested list blues in R.

I have two nested lists like the ones shown below, except that each is of size 200 million. I am interested in indexing aaa with bIdx i.e. pluck out the corresponding entries from aaa based on the index specified in bIdx. For example, after the operation we would pluck 1,8,10 entries from aaa[[6]] i.e. "TopNews", "Opinion" and "Opinion".

Since the lists are huge, solutions based on iterating over the lists are not an option and I want a lapply (or variants) based solution.

Any help is greatly appreciated!

```<code>aaa
[[1]]
character(0)

[[2]]
character(0)

[[3]]
character(0)

[[4]]
[1] "TopNews" "TopNews"

[[5]]
[1] "Opinion"

[[6]]
 [1] "TopNews" "TopNews" "TopNews" "Opinion" "TopNews" "TopNews" "Opinion"
 [8] "Opinion" "Opinion" "Opinion" "Opinion" "Opinion"

[[7]]
 [1] "N.Y./Region" "Opinion"     "Opinion"     "Opinion"     "Opinion"
 [6] "Opinion"     "TopNews"     "TopNews"     "TopNews"     "Opinion"

[[8]]
[1] "TopNews" "TopNews" "TopNews"

[[9]]
[1] "Opinion" "Opinion" "TopNews" "Opinion" "TopNews"

[[10]]
[1] "TopNews" "Opinion" "TopNews" "TopNews" "Opinion"

bIdx
[[1]]
integer(0)

[[2]]
integer(0)

[[3]]
integer(0)

[[4]]
[1] 1 2

[[5]]
[1] 1

[[6]]
[1]  1  8 10

[[7]]
[1] 3 8

[[8]]
[1] 2

[[9]]
[1] 3

[[10]]
[1] 3
</code>```

答:
This is a classic case for mapply. This function takes a function as first argument (in this case the indexing function [). It then loops over the lists in the following arguments and uses the selected elements as the 1st, 2nd, ... argument to the function specified.

An example:

```<code>aaa <- list(
  character(0),
  letters[1:4],
  letters[10:20]
)

bldx <- list(
  integer(0),
  c(2,1),
  c(7,3,2)
)

mapply(`[`,aaa,bldx)
</code>```

On a sidenote: your lists aren't really nested. A nested list would be a list with its elements being lists again (see eg. the output of lm).

Body:
I am facing some nested list blues in R.

I have two nested lists like the ones shown below, except that each is of size 200 million. I am interested in indexing aaa with bIdx i.e. pluck out the corresponding entries from aaa based on the index specified in bIdx. For example, after the operation we would pluck 1,8,10 entries from aaa[[6]] i.e. "TopNews", "Opinion" and "Opinion".

Since the lists are huge, solutions based on iterating over the lists are not an option and I want a lapply (or variants) based solution.

Any help is greatly appreciated!

aaa
[[1]]
character(0)

[[2]]
character(0)

[[3]]
character(0)

[[4]]
[1] "TopNews" "TopNews"

[[5]]
[1] "Opinion"

[[6]]
 [1] "TopNews" "TopNews" "TopNews" "Opinion" "TopNews" "TopNews" "Opinion"
 [8] "Opinion" "Opinion" "Opinion" "Opinion" "Opinion"

[[7]]
 [1] "N.Y./Region" "Opinion"     "Opinion"     "Opinion"     "Opinion"
 [6] "Opinion"     "TopNews"     "TopNews"     "TopNews"     "Opinion"

[[8]]
[1] "TopNews" "TopNews" "TopNews"

[[9]]
[1] "Opinion" "Opinion" "TopNews" "Opinion" "TopNews"

[[10]]
[1] "TopNews" "Opinion" "TopNews" "TopNews" "Opinion"

bIdx
[[1]]
integer(0)

[[2]]
integer(0)

[[3]]
integer(0)

[[4]]
[1] 1 2

[[5]]
[1] 1

[[6]]
[1]  1  8 10

[[7]]
[1] 3 8

[[8]]
[1] 2

[[9]]
[1] 3

[[10]]
[1] 3

Body:
This is a classic case for mapply. This function takes a function as first argument (in this case the indexing function [). It then loops over the lists in the following arguments and uses the selected elements as the 1st, 2nd, ... argument to the function specified.

An example:

aaa <- list(
  character(0),
  letters[1:4],
  letters[10:20]
)

bldx <- list(
  integer(0),
  c(2,1),
  c(7,3,2)
)

mapply(`[`,aaa,bldx)

On a sidenote: your lists aren't really nested. A nested list would be a list with its elements being lists again (see eg. the output of lm).


问:
How parse soap Fault.detail(lxml.etree._Element) from zeep python library
I'm trying get error detail, when I'm calling soap service with zeep.

How parse zeep.exceptions.Fault.detail? It's return lxml.etree._Element.

I'm using this code:

```<code>try:
    client = Client(wsdl=self.__wsdl)
    response = client.service.CustomerInformation(CustomerInformationService=self.service, faultStyle='wsdl')
except Fault as error:
    detail = error.detail
    # parse detail here
</code>```

Here is response XML:

```<code><?xml version="1.0" ?>
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
    <soap-env:Body >
        <soap-env:Fault  >
            <faultcode>soap-env:Client</faultcode>
            <faultstring>Client Error</faultstring>
            <detail>
                <ouaf:Fault xmlns:ouaf="urn:oracle:ouaf">
                    <ResponseStatus>F</ResponseStatus>
                    <ResponseCode>2013</ResponseCode>
                    <ResponseText>
                            Error while executing the request:
                            (Server Message)
                                Category: 90006
                                Number: 32200
                                Call Sequence:
                                Program Name: CustomerInformationService
                                Text: The personal account was not found: 9134211141
                                Description:
                                Table: null
                                Field: null
                    </ResponseText>
                    <ResponseData numParm="1"  text="The personal account was not found: 9134211141"  category="90006"  number="32200"  parm1="9134211141"  />
                </ouaf:Fault>
            </detail>
        </soap-env:Fault>
    </soap-env:Body >
</soap-env:Envelope>
</code>```

Diffinition of 'Fault' type from xml data exist in my wsdl.

答:
You can use error.code or error.message to match with the error that you want to look for.

https://github.com/mvantellingen/python-zeep/blob/master/src/zeep/exceptions.py#L53

If you can't see anything in error.detail, consider sending a PR to the python-zeep project.

Body:
I'm trying get error detail, when I'm calling soap service with zeep.

How parse zeep.exceptions.Fault.detail? It's return lxml.etree._Element.

I'm using this code:

try:
    client = Client(wsdl=self.__wsdl)
    response = client.service.CustomerInformation(CustomerInformationService=self.service, faultStyle='wsdl')
except Fault as error:
    detail = error.detail
    # parse detail here

Here is response XML:

<?xml version="1.0" ?>
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
    <soap-env:Body >
        <soap-env:Fault  >
            <faultcode>soap-env:Client</faultcode>
            <faultstring>Client Error</faultstring>
            <detail>
                <ouaf:Fault xmlns:ouaf="urn:oracle:ouaf">
                    <ResponseStatus>F</ResponseStatus>
                    <ResponseCode>2013</ResponseCode>
                    <ResponseText>
                            Error while executing the request:
                            (Server Message)
                                Category: 90006
                                Number: 32200
                                Call Sequence:
                                Program Name: CustomerInformationService
                                Text: The personal account was not found: 9134211141
                                Description:
                                Table: null
                                Field: null
                    </ResponseText>
                    <ResponseData numParm="1"  text="The personal account was not found: 9134211141"  category="90006"  number="32200"  parm1="9134211141"  />
                </ouaf:Fault>
            </detail>
        </soap-env:Fault>
    </soap-env:Body >
</soap-env:Envelope>

Diffinition of 'Fault' type from xml data exist in my wsdl.


问:
Sending commands to a device, name for idiom?
Sometimes a device has commands to be sent to another device. In simple cases, I often use strings of digits and letters like

```<code>"123X456YG"
</code>```

with the meaning

```<code> set the value of parameter X to 123, 456 to Y, and then Go.
</code>```

The interpretation algorithm is quite simple : process char by char, "push" the digit to build a number (n = 10*n + ch-'0'), execute action (and reset number) when it is a letter.

It very convenient when there are not too many different actions (and you can remember the letters), of course you may use SCPI for more complicated things.

Is there a name for this (rather obvious) way to to?

答:
This is an example of postfix notation. It's a notation that fairly naturally falls out of anything that uses a stack.

Examples include:

Reverse Polish Notation -- common on programmable calculators from the late 1960s onwards.

... in which 4 3 - 5 + results in 6 being left at the head of the stack, because the stack builds up like this:

```<code> Stack     Unconsumed input
1 [      ]  4 3 - 5 +
2 [ 4    ]  3 - 5 +
3 [ 4 3  ]  - 5 +
4 [ 1    ]  5 +
5 [ 1 5  ]  +
6 [ 6    ]
</code>```

At steps 4 and 6, the operator is executed by popping elements off the stack, then pushing the result onto the stack.

Many stack-based programming languages -- including Forth and Postscript. Postfix syntax is also fairly common in the world of esoteric programming languages.

If you're curious, I thoroughly recommend having a go at hand-writing Postscript. It's a fully-fledged programming language; for example, you can write a recursive Postscript program in a few bytes, to draw a fractal curve. Test it in Ghostscript. PDF is closely related to Postscript.

The language you have created differs from these in your approach to tokenisation, but at its core -- putting the operand(s) before the operator -- it's a postfix language.

You are unlikely to get a patent granted. :)

Body:
Sometimes a device has commands to be sent to another device. In simple cases, I often use strings of digits and letters like

"123X456YG"

with the meaning

 set the value of parameter X to 123, 456 to Y, and then Go.

The interpretation algorithm is quite simple : process char by char, "push" the digit to build a number (n = 10*n + ch-'0'), execute action (and reset number) when it is a letter.

It very convenient when there are not too many different actions (and you can remember the letters), of course you may use SCPI for more complicated things.

Is there a name for this (rather obvious) way to to?

Body:
This is an example of postfix notation. It's a notation that fairly naturally falls out of anything that uses a stack.

Examples include:

Reverse Polish Notation -- common on programmable calculators from the late 1960s onwards.

... in which 4 3 - 5 + results in 6 being left at the head of the stack, because the stack builds up like this:

 Stack     Unconsumed input
1 [      ]  4 3 - 5 +
2 [ 4    ]  3 - 5 +
3 [ 4 3  ]  - 5 +
4 [ 1    ]  5 +
5 [ 1 5  ]  +
6 [ 6    ]

At steps 4 and 6, the operator is executed by popping elements off the stack, then pushing the result onto the stack.

Many stack-based programming languages -- including Forth and Postscript. Postfix syntax is also fairly common in the world of esoteric programming languages.

If you're curious, I thoroughly recommend having a go at hand-writing Postscript. It's a fully-fledged programming language; for example, you can write a recursive Postscript program in a few bytes, to draw a fractal curve. Test it in Ghostscript. PDF is closely related to Postscript.

The language you have created differs from these in your approach to tokenisation, but at its core -- putting the operand(s) before the operator -- it's a postfix language.

You are unlikely to get a patent granted. :)


问:
Merging two json (deep nested)
I tried to merge two json both with $.extend and $.merge but no success. I also tried to attach it like this:

```<code>data: JSON.stringify({"data" : [
    {term: request.term},
    jsontag
]}),
</code>```

Here's my setup:

```<code>autocomplete: ({
    source: function (request, response) {
        var tags = $('#input-newsearch-2').val();
        var jsonfied = {
            tags: tags.replace(/,$/, "").split(",").map(function (tag) {
                return { tag: tag };
            })
        };
        var jsontag = JSON.stringify(jsonfied);
        var jsonterm = JSON.stringify({ term: request.term });
    //console.log(jsontag);
    //console.log(jsonterm);
    //var mergedObj = $.extend(jsontag, jsonterm);
    //console.log(mergedObj);
    $.ajax({
        url: "/source",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: [jsontag, jsonterm],
        success: function (data) {
            response(data);
        }
    });
},
});
</code>```

Console:

```<code>{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}
{"term":"value04"}
</code>```

I was hoping to get sth like:

```<code>[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]
</code>```

Or even better:

```<code>{"data":[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]}
</code>```

答: What about using Lodash js library for manipulating arrays, objects, ...</p>

Title: Merging two json (deep nested)

Body:
I tried to merge two json both with $.extend and $.merge but no success. I also tried to attach it like this:

data: JSON.stringify({"data" : [
    {term: request.term},
    jsontag
]}),

Here's my setup:

autocomplete: ({
    source: function (request, response) {
        var tags = $('#input-newsearch-2').val();
        var jsonfied = {
            tags: tags.replace(/,$/, "").split(",").map(function (tag) {
                return { tag: tag };
            })
        };
        var jsontag = JSON.stringify(jsonfied);
        var jsonterm = JSON.stringify({ term: request.term });
    //console.log(jsontag);
    //console.log(jsonterm);
    //var mergedObj = $.extend(jsontag, jsonterm);
    //console.log(mergedObj);
    $.ajax({
        url: "/source",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: [jsontag, jsonterm],
        success: function (data) {
            response(data);
        }
    });
},
});

Console:

{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}
{"term":"value04"}

I was hoping to get sth like:

[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]

Or even better:

{"data":[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]}


问:
BxAndroidBle cannot read device, status=22
I am having troubles with reading a Ble device and using the RxAndroidBle library.

I keep getting this error:

```<code>BleGattException{status=22, bleGattOperation=BleGattOperation{description='CONNECTION_STATE'}}
</code>```

Can anyone look at my code and see what I might be doing wrong:

```<code>subscription = rxBleDevice.establishConnection(context, true)
            .subscribe(rxBleConnection -> {
                rxBleConnection.readCharacteristic(UUID.fromString(UUID_LOG_COUNT)).doOnNext(Action1 -> Logger.d(Helper_Utils.reverseHex(HexString.bytesToHex(Action1))));
            }, throwable -> {
                Logger.d("Error", throwable.getMessage());
            });
</code>```

If you need more info, I will try to provide it.

EDIT

I have used 2 different phones:
OnePlus Two Android 6.0.1
Moto G Play Android 6.0.1

I have tried multiple times switching wifi and bluetooth on and off.
I have never been able to get a reading with this example.

答:
status = 22 is a problem related to Android OS disconnecting your peripheral. There is not much you can do from the code to prevent it.

As for not reading the characteristic value — it is because you are not subscribing to it. The best approach in RxJava programming (or reactive programming in general) is to prepare a flow with only a single subscribe because then you minimise the amount of state.

You could do like this:

```<code>Subscription s = rxBleDevice.establishConnection(true) // establish the connection
  .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString(UUID_LOG_COUNT))) // when the connection is established start reading the characteristic
  .take(1) // after the first value unsubscribe from the upstream to close the connection
  .subscribe( // subscribe to read values
    characteristicValue -> Logger.d(Helper_Utils.reverseHex(HexString.bytesToHex(characteristicValue))), // do your thing with the read value here
    throwable -> Logger.d("Error", throwable.getMessage()) // log / show possible error here
  );
</code>```

Remember that the result of .subscribe() is a Subscription which you can cancel by calling Subscription.unsubscribe() which will disconnect the peripheral.

My code is referencing the new API that was introduced by RxAndroidBle 1.2.0 which was released yesterday.

Body:
I am having troubles with reading a Ble device and using the RxAndroidBle library.

I keep getting this error:

BleGattException{status=22, bleGattOperation=BleGattOperation{description='CONNECTION_STATE'}}

Can anyone look at my code and see what I might be doing wrong:

subscription = rxBleDevice.establishConnection(context, true)
            .subscribe(rxBleConnection -> {
                rxBleConnection.readCharacteristic(UUID.fromString(UUID_LOG_COUNT)).doOnNext(Action1 -> Logger.d(Helper_Utils.reverseHex(HexString.bytesToHex(Action1))));
            }, throwable -> {
                Logger.d("Error", throwable.getMessage());
            });

If you need more info, I will try to provide it.

EDIT

I have used 2 different phones:
OnePlus Two Android 6.0.1
Moto G Play Android 6.0.1

I have tried multiple times switching wifi and bluetooth on and off.
I have never been able to get a reading with this example.

Body:
status = 22 is a problem related to Android OS disconnecting your peripheral. There is not much you can do from the code to prevent it.

As for not reading the characteristic value — it is because you are not subscribing to it. The best approach in RxJava programming (or reactive programming in general) is to prepare a flow with only a single subscribe because then you minimise the amount of state.

You could do like this:

Subscription s = rxBleDevice.establishConnection(true) // establish the connection
  .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(UUID.fromString(UUID_LOG_COUNT))) // when the connection is established start reading the characteristic
  .take(1) // after the first value unsubscribe from the upstream to close the connection
  .subscribe( // subscribe to read values
    characteristicValue -> Logger.d(Helper_Utils.reverseHex(HexString.bytesToHex(characteristicValue))), // do your thing with the read value here
    throwable -> Logger.d("Error", throwable.getMessage()) // log / show possible error here
  );

Remember that the result of .subscribe() is a Subscription which you can cancel by calling Subscription.unsubscribe() which will disconnect the peripheral.

My code is referencing the new API that was introduced by RxAndroidBle 1.2.0 which was released yesterday.


问:
how to download in python
I am writing a script which will run on my server. Its purpose is to download the document. If any person hit the particular url he/she should be able to download the document. I am using urllib.urlretrieve but it download document on the server side not on the client. How to download in python at client side?</p>

答: You might want to take a look at the SocketServer module.</p>

Title: how to download in python


问:
fadeIn doesn't work jquery
css

```<code> .wrap_result {
        background-color: #f0f2f0;
        border: 2px solid orangered;
        padding: 20px;
        position: fixed;
        left: 35%;
        top: 45%;
        width: 400px;
        height: 150px;
        text-align: center;
        display: none;
        z-index: 5005;
    }
</code>```

script

```<code> $('#removeSelected').click(function (e) {
            $('#qty').removeAttr('required');
            $('#product_id').removeAttr('required');
            var checked = $("input[type=checkbox]:checked").length;
            var cboxCount = $('input:checkbox').length;

            if (!checked) {
                $('.wrap_result')
                    .text('No selected items')
                    .fadeIn(3000).fadeOut(3000);
                e.preventDefault();
            }
        ]);
</code>```

When Im trying to remove products with 0 products selected im preventing form submit and informing user about it. Alert works just fine, but this custom window doesn't work :c

答:
I think the problem was the typo, Check this out!

$(function(){
 console.log('test')

  $('#removeSelected').click(function (e) {
            $('#qty').removeAttr('required');
            $('#product_id').removeAttr('required');
            var checked = $("input[type=checkbox]:checked").length;
            var cboxCount = $('input:checkbox').length;

            if (!checked) {
                $('.wrap_result')
                    .text('No selected items')
                    .fadeIn(3000).fadeOut(3000);
                e.preventDefault();
            }
        });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrap_result {
        background-color: #f0f2f0;
        border: 2px solid orangered;
        padding: 20px;
        position: fixed;
        left: 35%;
        top: 45%;
        width: 400px;
        height: 150px;
        text-align: center;
        display: none;
        z-index: 5005;
    }</code>```

<form method="GET" action="#">

  Water: <input type="checkbox" />

  Fire: <input type="checkbox" />

  Qty:<input type="text" id="qty"/>

  Product ID:<input type="text" id="product_id" required/>

  <button id="removeSelected">Remove</button>
</form>

```

Title: fadeIn doesn't work jquery

Body:
css

 .wrap_result {
        background-color: #f0f2f0;
        border: 2px solid orangered;
        padding: 20px;
        position: fixed;
        left: 35%;
        top: 45%;
        width: 400px;
        height: 150px;
        text-align: center;
        display: none;
        z-index: 5005;
    }

script

 $('#removeSelected').click(function (e) {
            $('#qty').removeAttr('required');
            $('#product_id').removeAttr('required');
            var checked = $("input[type=checkbox]:checked").length;
            var cboxCount = $('input:checkbox').length;

            if (!checked) {
                $('.wrap_result')
                    .text('No selected items')
                    .fadeIn(3000).fadeOut(3000);
                e.preventDefault();
            }
        ]);

When Im trying to remove products with 0 products selected im preventing form submit and informing user about it. Alert works just fine, but this custom window doesn't work :c

Body:
I think the problem was the typo, Check this out!

$(function(){
 console.log('test')

  $('#removeSelected').click(function (e) {
            $('#qty').removeAttr('required');
            $('#product_id').removeAttr('required');
            var checked = $("input[type=checkbox]:checked").length;
            var cboxCount = $('input:checkbox').length;

            if (!checked) {
                $('.wrap_result')
                    .text('No selected items')
                    .fadeIn(3000).fadeOut(3000);
                e.preventDefault();
            }
        });
})

.wrap_result {
        background-color: #f0f2f0;
        border: 2px solid orangered;
        padding: 20px;
        position: fixed;
        left: 35%;
        top: 45%;
        width: 400px;
        height: 150px;
        text-align: center;
        display: none;
        z-index: 5005;
    }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_result">

</div>
<div>
<form method="GET" action="#">

  Water: <input type="checkbox" /><br/>
  Fire: <input type="checkbox" /><br/>
  Qty:<input type="text" id="qty"/><br/>
  Product ID:<input type="text" id="product_id" required/><br/>
  <button id="removeSelected">Remove</button>
</form>
</div>


问:
Android emulator reports unknown virtual device
i am having the same problem described in the following post "Android emulator reports unknown virtual device" Why does the Android emulator report "unknown virtual device", when the device is in my user directory? and have followed all of the instructions in an attempt to resolve but still i cannot run my AVD.

I only have one drive on my Windows 7 machine (C:) and the AVD is being created in the correct location -> C:\Users\MyUser\.android

Ive also tried to setup an environment variable "ANDROID_SDK_HOME"

The actual error is:

```<code>emulator: ERROR: unknown virtual device name: 'my_AVD'
emulator: could not find virtual device named 'my_AVD'
</code>```

Can someone please help me?

答:
Please try the below steps to solve the above issue -

in task manager kill adb in process

in android sdk folder .. /tools/ run adb kill-server in command line

Check the avd folder name in " ../.adroid/avd/" - say it is "avd1"

run command "emulator -avd avd1 " under android folder "../tool/" in command line

it will start the avd1 device

Now start the eclipse and run your project with setting the "manula" option in configuration.

It will ask for choosing the avd between "avd1" and the existing list of avd's in eclipse if any. You choose "avd1" as it is already running.

Body:
i am having the same problem described in the following post "Android emulator reports unknown virtual device" Why does the Android emulator report "unknown virtual device", when the device is in my user directory? and have followed all of the instructions in an attempt to resolve but still i cannot run my AVD.

I only have one drive on my Windows 7 machine (C:) and the AVD is being created in the correct location -> C:\Users\MyUser\.android

Ive also tried to setup an environment variable "ANDROID_SDK_HOME"

The actual error is:

emulator: ERROR: unknown virtual device name: 'my_AVD'
emulator: could not find virtual device named 'my_AVD'

Can someone please help me?


问:
Hide an element when clicking anywhere outside it
I am trying to have an element be hidden when you click anywhere outside of it.

It is a drop down that appears when you click on the CART link in the top left.  The problem I seem to be facing is two fold.

1) When you click on anything in that button other then just CART, it's showing and then hiding the .cart-dropdown DIV.  I am guessing it's because I'm not targeting the correct classes in this piece of code:

```<code>$(document).click (function (e) {
  if (e.target != $('.cart-dropdown')[0] && e.target != $('.cart-nav-item')[0] && e.target != $('.cart-full')[0]) {
    $('.cart-dropdown').hide();
  }
});
</code>```

2) The .cart-dropdown DIV also closes when you click within it, which is what I want to avoid.  Again this must relate to an error in my syntax / logic in the above piece of code.

Can someone please point me in the correct direction?

Thanks.

答:
You need to change

```<code>e.target
</code>```

to

```<code>$(e.target)
</code>```

to treat it as a jquery object.

Body:
I am trying to have an element be hidden when you click anywhere outside of it.

It is a drop down that appears when you click on the CART link in the top left.  The problem I seem to be facing is two fold.

1) When you click on anything in that button other then just CART, it's showing and then hiding the .cart-dropdown DIV.  I am guessing it's because I'm not targeting the correct classes in this piece of code:

$(document).click (function (e) {
  if (e.target != $('.cart-dropdown')[0] && e.target != $('.cart-nav-item')[0] && e.target != $('.cart-full')[0]) {
    $('.cart-dropdown').hide();
  }
});

2) The .cart-dropdown DIV also closes when you click within it, which is what I want to avoid.  Again this must relate to an error in my syntax / logic in the above piece of code.

Can someone please point me in the correct direction?

Thanks.

Body:
You need to change

e.target

to

$(e.target)

to treat it as a jquery object.


问:
GridView.getChildAt(index) returns null
I'm populating a GridView wth an AsyncTask:

```<code>@Override
public void onLoad() {
    super.onLoad();
    //... set Loading view and actually get the data
    adapter = new DepartmentGridAdapter(getActivity(), R.layout.gird_department_item_layout,
            mSalesPresenter.getDepartments());
}

@Override
public void onDoneLoading() {
    super.onDoneLoading();
    gridView.setAdapter(adapter); // Populate the GridView
    onShowTutorial(); // <--- This is where I need to get the firstChild.
}
</code>```

After the AsyncTask is done, I just need to access the firstChild of the GridView:

```<code>@Override
public void onShowTutorial() {
    if (gridView.getChildAt( gridView.getFirstVisiblePosition())!= null )
        // ... doStuff
}
</code>```

But the statement is Always null. I even call getCount for the GridView and it's not 0. The problem seems that the GridView childs are not accesible right away. If i Use a button to force the execution of the method onShowTutorial() after the UI is ready then I can access the first child.

I'm running out of ideas to trigger the method after the execution of the thread.

Any solution?

答:
Try to post a runnable to be run when the gridView is done doing what it is currently doing (more info regarding View.post() here) :

```<code>@Override
public void onDoneLoading() {
    super.onDoneLoading();
    gridView.setAdapter(adapter); // Populate the GridView

    // Tells the gridView to "queue" the following runnable
    gridView.post(new Runnable() {
        @Override
        public void run() {
            onShowTutorial(); // <--- This is where I need to get the firstChild.
        }
    });
}
</code>```

Title: GridView.getChildAt(index) returns null

Body:
I'm populating a GridView wth an AsyncTask:

@Override
public void onLoad() {
    super.onLoad();
    //... set Loading view and actually get the data
    adapter = new DepartmentGridAdapter(getActivity(), R.layout.gird_department_item_layout,
            mSalesPresenter.getDepartments());
}

@Override
public void onDoneLoading() {
    super.onDoneLoading();
    gridView.setAdapter(adapter); // Populate the GridView
    onShowTutorial(); // <--- This is where I need to get the firstChild.
}

After the AsyncTask is done, I just need to access the firstChild of the GridView:

@Override
public void onShowTutorial() {
    if (gridView.getChildAt( gridView.getFirstVisiblePosition())!= null )
        // ... doStuff
}

But the statement is Always null. I even call getCount for the GridView and it's not 0. The problem seems that the GridView childs are not accesible right away. If i Use a button to force the execution of the method onShowTutorial() after the UI is ready then I can access the first child.

I'm running out of ideas to trigger the method after the execution of the thread.

Any solution?

Body:
Try to post a runnable to be run when the gridView is done doing what it is currently doing (more info regarding View.post() here) :

@Override
public void onDoneLoading() {
    super.onDoneLoading();
    gridView.setAdapter(adapter); // Populate the GridView

    // Tells the gridView to "queue" the following runnable
    gridView.post(new Runnable() {
        @Override
        public void run() {
            onShowTutorial(); // <--- This is where I need to get the firstChild.
        }
    });
}


问:
how to trigger function onchange on already selected option
I have a  dropdown which i would like to trigger a function when something is selected.

```<code><select id="myselect">
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>

$(document).on("change", "#myselect", function(event) {
alert("you selected something");
});
</code>```

The problem I have is that the function is not triggered if i choose option that has already been selected. I do understand that this is because nothing has been changed but is there a way around this?

I have tried

```<code>  <select id="myselect" onmousedown="this.value='';" >
</code>```

this was ok for the few options, but when i had many options when i needed to scroll down to select it would jump up and select the wrong option.
Any help much appreciated.

答:
UPDATE

$(document).on("change", ".myselect",function(){
    var idSelect = $(this).attr("id"); /*get the id select change*/
    $(".myselect").each(function(){
       var idSelectOther = $(this).attr("id");/*get the id of another select*/
       if(idSelect != idSelectOther){ /*if id selected != other select then check value*/
          if($("#"+idSelect).val() == $("#"+idSelectOther).val()){ /* if val same so alert the user.*/
            alert("you already select this value");
          }
       }
    });
}); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="myselect" id="sel1">
  <option val="1">1</option>
  <option val="2">2</option>
  <option val="3">3</option>
 </select>

 <select class="myselect"  id="sel2">
  <option val="1">1</option>
  <option val="2">2</option>
  <option val="3">3</option>
 </select></code>```

Body:
I have a  dropdown which i would like to trigger a function when something is selected.

<select id="myselect">
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>

$(document).on("change", "#myselect", function(event) {
alert("you selected something");
});

The problem I have is that the function is not triggered if i choose option that has already been selected. I do understand that this is because nothing has been changed but is there a way around this?

I have tried

  <select id="myselect" onmousedown="this.value='';" >

this was ok for the few options, but when i had many options when i needed to scroll down to select it would jump up and select the wrong option.
Any help much appreciated.

Body:
UPDATE

$(document).on("change", ".myselect",function(){
    var idSelect = $(this).attr("id"); /*get the id select change*/
    $(".myselect").each(function(){
       var idSelectOther = $(this).attr("id");/*get the id of another select*/
       if(idSelect != idSelectOther){ /*if id selected != other select then check value*/
          if($("#"+idSelect).val() == $("#"+idSelectOther).val()){ /* if val same so alert the user.*/
            alert("you already select this value");
          }
       }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="myselect" id="sel1">
  <option val="1">1</option>
  <option val="2">2</option>
  <option val="3">3</option>
 </select>

 <select class="myselect"  id="sel2">
  <option val="1">1</option>
  <option val="2">2</option>
  <option val="3">3</option>
 </select>


问:
Floating point inverse binary representation
I'm confused with the following pieces of code:

```<code>int main()
{
    std::cout << std::bitset<32>(10.0f) << std::endl;
    std::cout << std::bitset<32>(-10.0f) << std::endl;

    float x = 10.0f;
    std::bitset<32> bsx(x);
    float y = -10.0f;
    std::bitset<32> bsy(y);
    std::cout << bsx << std::endl;
    std::cout << bsy << std::endl;
}
</code>```

the second one just (yes, it's just a truncated first one):

```<code>int main()
{
    std::cout << std::bitset<32>(10.0f) << std::endl;
    std::cout << std::bitset<32>(-10.0f) << std::endl;
}
</code>```

I'm getting the following outputs:
the 1st one:

```<code>00000000000000000000000000001010
00000000000000000000000000000000
00000000000000000000000000001010
11111111111111111111111111110110
</code>```

the 2nd:

```<code>00000000000000000000000000001010
00000000000000010010000001101000
</code>```

The system is Clang 4.0.0 on macOS Sierra (10.12.3), floats are 32-bits here as I know.

(Compiled with g++ -pedantic -std=c++14.)

The only thing I'm aware of for floating-point numbers is the IEEE-754, which states there should be a separate sign bit. The last output of the first program seems to be using two's complement...

And the other ones are just totally confusing.. all zeros and somewhat random output, even with the same code, just truncated..

What do I misunderstand? Am I getting undefined behaviour somewhere in code? Don't understand the syntax? Or floats for some reason can't be represented as bitsets?

答:
It works this way:

```<code>#include <bitset>
#include <iostream>
inline unsigned U(float f) { return (unsigned&) f; }

int main()
{
    std::cout << std::bitset<32>(U(10.0f)) << std::endl;
    std::cout << std::bitset<32>(U(-10.0f)) << std::endl;
    return 0;
}
</code>```

I've added explicit re-reading of value in another format.
The output is

```<code>01000001001000000000000000000000
11000001001000000000000000000000
</code>```

(Of course, traditional disclaimer for platform specific details shall be placed here.)

UPDATE: there are issues with memory aliasing that causes the converter would be better written (at least for modern GCC and Clang) in the following way:

```<code>inline unsigned U(float f) {
    unsigned R;
    memcpy(&R, &f, sizeof(R));
    return R;
}
</code>```

modern compilers treat this memcpy() as "bitcast" operator and internally converts it to a proper kind of register moving. Without this, you can meet some weird issues with aliasing.
But, this approach is still worse for ICC, which prefers union of members of different types:

```<code>inline unsigned U(float f) {
    union {
        unsigned u;
        float f;
    } t;
    t.f = f;
    return t.u;
}
</code>```

There are contradictory opinions on what style of bitcasting is better for different languages and versions, I will not dive into them here.

Body:
I'm confused with the following pieces of code:

int main()
{
    std::cout << std::bitset<32>(10.0f) << std::endl;
    std::cout << std::bitset<32>(-10.0f) << std::endl;

    float x = 10.0f;
    std::bitset<32> bsx(x);
    float y = -10.0f;
    std::bitset<32> bsy(y);
    std::cout << bsx << std::endl;
    std::cout << bsy << std::endl;
}

the second one just (yes, it's just a truncated first one):

int main()
{
    std::cout << std::bitset<32>(10.0f) << std::endl;
    std::cout << std::bitset<32>(-10.0f) << std::endl;
}

I'm getting the following outputs:
the 1st one:

00000000000000000000000000001010
00000000000000000000000000000000
00000000000000000000000000001010
11111111111111111111111111110110

the 2nd:

00000000000000000000000000001010
00000000000000010010000001101000

The system is Clang 4.0.0 on macOS Sierra (10.12.3), floats are 32-bits here as I know.

(Compiled with g++ -pedantic -std=c++14.)

The only thing I'm aware of for floating-point numbers is the IEEE-754, which states there should be a separate sign bit. The last output of the first program seems to be using two's complement...

And the other ones are just totally confusing.. all zeros and somewhat random output, even with the same code, just truncated..

What do I misunderstand? Am I getting undefined behaviour somewhere in code? Don't understand the syntax? Or floats for some reason can't be represented as bitsets?

Body:
It works this way:

#include <bitset>
#include <iostream>
inline unsigned U(float f) { return (unsigned&) f; }

int main()
{
    std::cout << std::bitset<32>(U(10.0f)) << std::endl;
    std::cout << std::bitset<32>(U(-10.0f)) << std::endl;
    return 0;
}

I've added explicit re-reading of value in another format.
The output is

01000001001000000000000000000000
11000001001000000000000000000000

(Of course, traditional disclaimer for platform specific details shall be placed here.)

UPDATE: there are issues with memory aliasing that causes the converter would be better written (at least for modern GCC and Clang) in the following way:

inline unsigned U(float f) {
    unsigned R;
    memcpy(&R, &f, sizeof(R));
    return R;
}

modern compilers treat this memcpy() as "bitcast" operator and internally converts it to a proper kind of register moving. Without this, you can meet some weird issues with aliasing.
But, this approach is still worse for ICC, which prefers union of members of different types:

inline unsigned U(float f) {
    union {
        unsigned u;
        float f;
    } t;
    t.f = f;
    return t.u;
}

There are contradictory opinions on what style of bitcasting is better for different languages and versions, I will not dive into them here.


问:
Passing display value format to angular component
I would like to pass the formatting of a display value to an angular component.

For example:

```<code>format="'(utc, offset) location (tz)'" === '(UTC -04:00) New York (EDT)'
</code>```

or

```<code>format="'(tz, offset) location'" === '(EDT -04:00) New York'
</code>```

The idea is that the value will be displayed as per the format given, parentheses included.
I'm guessing the best way to acheive this would be to have an array of the format required?
So given the following string, how can I generate the following array:

```<code>'(utc, offset) location (tz)' === ['(', 'utc-code', 'offset-hours', ')', 'location', '(', 'tz-code', ')'];

'(tz, offset) location' === ['(', 'tz', 'offset', ')', 'location']
</code>```

答:
You can use component binding to pass the value. Here $doCheck will be called in each digest cycle which provides an opportunity to detect and act on changes to the bindings.

I have written a simple logic with regular expression to display the data with input format. Hope this approach would helps instead of your array approach.

angular.module('app',[])
.controller('appCtrl', function($scope){
  $scope.format = '(offset) location (tz)';
})
.component('myComponent', {
  template: '
{{$ctrl.formattedValue}}
',
  controller: myComponentCtrl,
  bindings: {
    format: '='
  }
});

function myComponentCtrl(/*your DI goes here*/){
  console.log('log from component: format->'+this.format);
  var self = this;
  this.formattedValue = '';

  this.$doCheck = function(){
    var sampleDateObject = {
      tz: 'CDT',
      offset: '-4:00',
      location: 'Chicago',
      year: 2017
    }
    self.formattedValue = self.format.replace(/([a-z]+)/gi, function(match){
      return sampleDateObject[match]?sampleDateObject[match]:match;
    });
  };
}

myComponentCtrl.$inject = [/*your DI goes here as string*/];```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.min.js"></script>
<div ng-app="app" ng-controller="appCtrl">
  <my-component format="format"></my-component>
  <my-component format="'(tz, offset) location, year'"></my-component>
</div></code>```

Body:
I would like to pass the formatting of a display value to an angular component.

For example:

format="'(utc, offset) location (tz)'" === '(UTC -04:00) New York (EDT)'

or

format="'(tz, offset) location'" === '(EDT -04:00) New York'

The idea is that the value will be displayed as per the format given, parentheses included.
I'm guessing the best way to acheive this would be to have an array of the format required?
So given the following string, how can I generate the following array:

'(utc, offset) location (tz)' === ['(', 'utc-code', 'offset-hours', ')', 'location', '(', 'tz-code', ')'];

'(tz, offset) location' === ['(', 'tz', 'offset', ')', 'location']

Body:
You can use component binding to pass the value. Here $doCheck will be called in each digest cycle which provides an opportunity to detect and act on changes to the bindings.

I have written a simple logic with regular expression to display the data with input format. Hope this approach would helps instead of your array approach.

angular.module('app',[])
.controller('appCtrl', function($scope){
  $scope.format = '(offset) location (tz)';
})
.component('myComponent', {
  template: '<div>{{$ctrl.formattedValue}}</div>',
  controller: myComponentCtrl,
  bindings: {
    format: '='
  }
});

function myComponentCtrl(/*your DI goes here*/){
  console.log('log from component: format->'+this.format);
  var self = this;
  this.formattedValue = '';

  this.$doCheck = function(){
    var sampleDateObject = {
      tz: 'CDT',
      offset: '-4:00',
      location: 'Chicago',
      year: 2017
    }
    self.formattedValue = self.format.replace(/([a-z]+)/gi, function(match){
      return sampleDateObject[match]?sampleDateObject[match]:match;
    });
  };
}

myComponentCtrl.$inject = [/*your DI goes here as string*/];

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.min.js"></script>
<div ng-app="app" ng-controller="appCtrl">
  <my-component format="format"></my-component>
  <my-component format="'(tz, offset) location, year'"></my-component>
</div>


问:
The same Google map Wont work in new domain
The following code works fine in one domain and in another the map wont show.
Why is this happening?

The content of both sites is exactly the same as the client is in the process of migrating for a new address.

In the old domain the map works fine. In the new one an error appears.

HTML

```<code><div id="canvas">
    <div id="map-canvas"></div>
</div>
</code>```

JavaScrip

```<code>    <script src="https://maps.googleapis.com/maps/api/js"></script>

    <script>
    function initialize() {

    //-----------------------------Stiles --------------------------------:

    var styles = [ { "featureType": "landscape.man_made", "elementType": "geometry.fill", "stylers": [ { "hue":

    "#66ff00" }, { "saturation": 43 }, { "visibility": "on" }, { "lightness": -46 } ] },{

    "featureType": "landscape.natural", "stylers": [ { "visibility": "on" }, { "hue": "#3bff00" },

    { "lightness": -53 }, { "saturation": 33 } ] },{ "featureType": "landscape.natural.terrain",

    "stylers": [ { "visibility": "off" } ] },{ "featureType": "water", "stylers": [ { "lightness":

    -61 }, { "saturation": -60 }, { "hue": "#1aff00" } ] },{ "featureType": "road.highway",

    "elementType": "geometry.fill", "stylers": [ { "visibility": "on" }, { "hue": "#4cff00" }, {

    "lightness": -69 } ] },{ "featureType": "road.highway", "elementType": "geometry.stroke",

    "stylers": [ { "visibility": "off" } ] },{ "featureType": "road.arterial", "elementType":

    "geometry.fill", "stylers": [ { "visibility": "on" }, { "saturation": 57 }, { "hue": "#22ff00"

    }, { "lightness": -68 } ] },{ "featureType": "road.arterial", "elementType": "geometry.stroke",

    "stylers": [ { "visibility": "off" } ] },{ "featureType": "road.local", "elementType":

    "geometry.fill", "stylers": [ { "hue": "#55ff00" }, { "lightness": -64 }, { "saturation": 58 }

    ] },{ "featureType": "road.local", "elementType": "geometry.stroke", "stylers": [ {

    "visibility": "off" } ] },{ "featureType": "road", "elementType": "labels.text.fill",

    "stylers": [ { "color": "#ffffff" }, { "visibility": "on" } ] },{ "featureType": "road",

    "elementType": "labels.text.stroke", "stylers": [ { "visibility": "off" } ] },{ "featureType":

    "road", "elementType": "labels.icon", "stylers": [ { "visibility": "on" }, { "hue": "#6eff00"

    }, { "lightness": -2 }, { "saturation": -42 } ] },{ "featureType": "poi", "elementType":

    "geometry.fill", "stylers": [ { "visibility": "on" }, { "color": "#8080ff" }, { "hue":

    "#66ff00" }, { "saturation": -30 }, { "lightness": -45 } ] },{ "featureType": "poi",

    "elementType": "labels.text.stroke", "stylers": [ { "color": "#808080" }, { "visibility": "off"

    } ] },{ "featureType": "poi", "elementType": "labels.text.fill", "stylers": [ { "visibility":

    "on" }, { "color": "#ffffff" } ] },{ "featureType": "administrative", "elementType":

    "labels.text.fill", "stylers": [ { "color": "#ffffff" }, { "visibility": "on" } ] },{

    "featureType": "administrative", "elementType": "labels.text.stroke", "stylers": [ {

    "visibility": "on" }, { "hue": "#66ff00" }, { "saturation": 31 }, { "lightness": -76 } ] },{

    "featureType": "water", "elementType": "labels.text", "stylers": [ { "color": "#ffffff" }, {

    "visibility": "on" } ] },{ "featureType": "water", "elementType": "labels.text.stroke",

    "stylers": [ { "color": "#2a6028" } ] },{ "featureType": "transit.line", "elementType":

    "geometry.fill", "stylers": [ { "visibility": "on" }, { "color": "#97f845" } ] },{

    "featureType": "transit.station", "elementType": "labels.text.fill", "stylers": [ { "color":

    "#ffffff" } ] },{ "featureType": "transit.station", "elementType": "labels.text.stroke",

    "stylers": [ { "visibility": "off" } ] } ]

    //-----------------------------------------------------------------------:

      var mapOptions = {
        zoom: 15,
        styles: styles,
        center: new google.maps.LatLng(40.115, -8.251),
        scrollwheel: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById('map-canvas'),
                                    mapOptions);

    //----------------------------- Marker --------------------------------:

      var image = 'images/logo-map-10.png';
      var myLatLng = new google.maps.LatLng(40.11218, -8.25144);
      var tipografiaMarker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          icon: image,
          animation: google.maps.Animation.BOUNCE,
      });
    }

    //-----------------------------------------------------------------------:

    google.maps.event.addDomListener(window, 'load', initialize);

    <script>
</code>```

答:
js:35 Google Maps API error: MissingKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#missing-key-map-error

Since last summer you have to use API key and restrict it for certain domain.

Body:
The following code works fine in one domain and in another the map wont show.
Why is this happening?

The content of both sites is exactly the same as the client is in the process of migrating for a new address.

In the old domain the map works fine. In the new one an error appears.

HTML

JavaScrip


问:
Generate random password string with requirements in javascript
I want to generate a random string that has to have 5 letters from a-z and 3 numbers.

How can I do this with JavaScript?

I've got the following script, but it doesn't meet my requirements.

```<code>        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        var string_length = 8;
        var randomstring = '';
        for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum,rnum+1);
        }
</code>```

答:
There is a random password string generator with selected length

let input = document.querySelector("textarea");
let button = document.querySelector("button");
let length = document.querySelector("input");

function generatePassword(n)
{
 let pwd = "";

  while(!pwd || pwd.length < n)
  {
   pwd += Math.random().toString(36).slice(-22);
  }

  return pwd.substring(0, n);
}

button.addEventListener("click", function()
{
 input.value = generatePassword(length.value);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>password:</div>
<div><textarea cols="70" rows="10"></textarea></div>
<div>length:</div>
<div><input type="number" value="200"></div>
<br>
<button>gen</button></code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to generate a random string that has to have 5 letters from a-z and 3 numbers.

How can I do this with JavaScript?

I've got the following script, but it doesn't meet my requirements.

        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        var string_length = 8;
        var randomstring = '';
        for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum,rnum+1);
        }

Body:
There is a random password string generator with selected length

let input = document.querySelector("textarea");
let button = document.querySelector("button");
let length = document.querySelector("input");

function generatePassword(n)
{
 let pwd = "";

  while(!pwd || pwd.length < n)
  {
   pwd += Math.random().toString(36).slice(-22);
  }

  return pwd.substring(0, n);
}

button.addEventListener("click", function()
{
 input.value = generatePassword(length.value);
});

<div>password:</div>
<div><textarea cols="70" rows="10"></textarea></div>
<div>length:</div>
<div><input type="number" value="200"></div>
<br>
<button>gen</button>


问:
Facebook like or share with dynamic document title
I found this problem all over the net but no answer yet, so maybe here someone solved it ...?
I built a page relying heavily on jquery.address. It's got one index page and the rest loads dynamically via Ajax following Google's /#!/ scheme for crawlable pages. Now I want to add Facebooks Like or share button but I can't get it to grab the actual page title or url.

Whatever I do, it always falls back to title and url of the index page. It tried:

(obviously) changing title an openGraph meta on load of the new parts.

"linking" the crawler page (?_escaped_fragmet_=xyx) but specifying the #! page in meta

"sharing" with a given title and url.

I never get anything but a link to the index page or a blank "share" to the right url with title and thumbnail ignored.

Has anyone got a similar setup working?

Thanks for any hints,
thomas

答: Facebook share has a BRUTAL cache, last time I checked it was impossible to change the title / description data once it was scraped :(</p>


问:
switch line class in clojurescript with if boolean variable
how can I switch the li class in a list with clojurescript, when the @switchvar is true all odd lines should be active, in the other case the even lines should be active

I tried an if statement, nothing happens.

```<code>(defn listitems [items]
  [:ul
   (for [item items]
     ^{:key item} [:li {:class
        (if (@switchvar true)
            ((odd? item) "active")
            ((even? item) "active") )
      } "Item " item ])])
</code>```

答:
thanks@all, I got a good start into clojure with your hints. switchvar is actually boolean. I changed the first "inactive" to another if clause.</p>

```<code>(defn lister-items2 [items]
  [:ul
   (for [item items ]
     ^{:key item} [:li {:class
                    (if (and (odd? item) (true? @switchvar))
                      "active"
                      (if (and (even? item) (false? @switchvar))
                        "active"
                        "inactive"))
                    } "Item " item])])
</code>```

Body:
how can I switch the li class in a list with clojurescript, when the @switchvar is true all odd lines should be active, in the other case the even lines should be active

I tried an if statement, nothing happens.

(defn listitems [items]
  [:ul
   (for [item items]
     ^{:key item} [:li {:class
        (if (@switchvar true)
            ((odd? item) "active")
            ((even? item) "active") )
      } "Item " item ])])

Body:
thanks@all, I got a good start into clojure with your hints. switchvar is actually boolean. I changed the first "inactive" to another if clause.

(defn lister-items2 [items]
  [:ul
   (for [item items ]
     ^{:key item} [:li {:class
                    (if (and (odd? item) (true? @switchvar))
                      "active"
                      (if (and (even? item) (false? @switchvar))
                        "active"
                        "inactive"))
                    } "Item " item])])


问:
SQL Update a column in a table using Trigger to a Function
I am trying to auto generate a document reference number when a new document is added to an sql table - the reference number is a concatonation of some of the other fields in that table.

Looking online i can see one method is to use the dbid function to generate a uid and then create a function to concatonate and then a trigger on the table on insert to populate the column, but ive spent numerous hours and i cant get it to work.

The table has the following columns:-

```<code>Table:-     dbo.codeallocations21322

Columns :-
Dbid
Projectcode
Type
Discipline]
Hdlreference
</code>```

So the hdlreference column would be populated with :-

```<code>[projectcode]-[type]-[discipline]-[bdid]
</code>```

With the [bdid] set to 6 characters'.

Eg 21322-rfq-mech-000001
Any help would be much appreciated / advise a better way ?

Many thanks in advance.

答:
Many thanks John - altered slightly to convert the Int dbID to a varchar and works great :-

```<code>alter table CodeAllocations21322

  add hdlreference2

    as (ProjectCode  + '-' + Type + '-' + Discipline + '-' + right('00000' + Cast (dbID AS varchar(5)), 5));
</code>```

Thanks again, look forward to talking to you in the future.

Body:
I am trying to auto generate a document reference number when a new document is added to an sql table - the reference number is a concatonation of some of the other fields in that table.

Looking online i can see one method is to use the dbid function to generate a uid and then create a function to concatonate and then a trigger on the table on insert to populate the column, but ive spent numerous hours and i cant get it to work.

The table has the following columns:-

Table:-     dbo.codeallocations21322

Columns :-
Dbid
Projectcode
Type
Discipline]
Hdlreference

So the hdlreference column would be populated with :-

[projectcode]-[type]-[discipline]-[bdid]

With the [bdid] set to 6 characters'.

Eg 21322-rfq-mech-000001
Any help would be much appreciated / advise a better way ?

Many thanks in advance.

Body:
Many thanks John - altered slightly to convert the Int dbID to a varchar and works great :-

alter table CodeAllocations21322

  add hdlreference2

    as (ProjectCode  + '-' + Type + '-' + Discipline + '-' + right('00000' + Cast (dbID AS varchar(5)), 5));

Thanks again, look forward to talking to you in the future.


问:
Do null pointer deference and uninitialized memory belong to memory corruption
In wikipedia, memory corruption is defined as follows:

Memory corruption occurs in a computer program when the contents of a
  memory location are unintentionally modified due to programming
  errors; this is termed violating memory safety.

But in the subsequent description, null pointer dereference and uninitialized memory are considered memory corruption.

I'm a little confused. Null pointer dereference and uninitialized memory do not unintentionally modify the contents of a memory location. Why are they regarded as memory corruption?

答:
Dereferencing a null pointer reference cannot corrupt memory unless the first page is mapped to the process address space.

Most operating systems do not map this page by default (although many allow the user to map it if they so choose).

Because a null pointer will reference nothing, you cannot corrupt anything by accessing it.

The pointer itself may be corrupted if it has a null (or any other invalid value).


问:
"Attribute aria-expanded not allowed on element li at this point"
I have the following code (from here):

```<code><div role="menubar">
    <ul role="menu" aria-label="functions" id="appmenu">
            <li role="menuitem" aria-haspopup="true" tabindex="0" aria-expanded="false">
                File
                <ul role="menu">
                            <li role="menuitem" tabindex="-1">New</li>
                            <li role="menuitem" tabindex="-1">Open</li>
                            <li role="menuitem" tabindex="-1">Print</li>
                    </ul>
            </li>
            <li role="menuitem" aria-haspopup="true" tabindex="-1" aria-expanded="false">
                Edit
                <ul role="menu">
                            <li role="menuitem" tabindex="-1">Undo</li>
                            <li role="menuitem" tabindex="-1">Redo</li>
                            <li role="menuitem" tabindex="-1">Cut</li>
                            <li role="menuitem" tabindex="-1">Copy</li>
                            <li role="menuitem" tabindex="-1">Paste</li>
                    </ul>
            </li>
            <li role="menuitem" aria-haspopup="true" tabindex="-1" aria-expanded="false">
                    Format
                    <ul role="menu">
                            <li role="menuitem" tabindex="-1">Font</li>
                            <li role="menuitem" tabindex="-1">Text</li>
                    </ul>
            </li>
            <li role="menuitem" aria-haspopup="true" tabindex="-1" aria-expanded="false">
                View
                <ul role="menu">
                    <li role="menuitem" tabindex="-1">100%</li>
                    <li role="menuitem" tabindex="-1">Zoom In</li>
                    <li role="menuitem" tabindex="-1">Zoom Out</li>
                </ul>
            </li>
            <li role="menuitem" tabindex="-1" aria-expanded="false">Help</li>
    </ul>
</div>
</code>```

However when I try to validate (via the W3C validator) that HTML piece it gives the error:

Attribute aria-expanded not allowed on element li at this point.

As this is an official W3C example I’m a little bit confused as their own example didn’t validate with their own validator. What’s wrong here?

答:
So according to the draft here the following should be used:

 …

  Edit

Undo

Redo

Cut

Copy

Paste

 …

```

However there is now a note which said "Application menus typically do not have links and rely on scripting to provide the functionality." so the correct menu for a website might be this here.

Body:
I have the following code (from here):

                File

New

Open

Print

                Edit

Undo

Redo

Cut

Copy

Paste

                    Format

Font

Text

                View

100%

Zoom In

Zoom Out

Help

However when I try to validate (via the W3C validator) that HTML piece it gives the error:

Attribute aria-expanded not allowed on element li at this point.

As this is an official W3C example I’m a little bit confused as their own example didn’t validate with their own validator. What’s wrong here?

Body:
So according to the draft here the following should be used:

<ul role="menubar" id="appmenu">
 …
 <li role="menuitem" aria-haspopup="true">
  Edit
  <ul role="menu">
   <li role="menuitem">Undo</li>
   <li role="menuitem">Redo</li>
   <li role="separator"></li>
   <li role="menuitem">Cut</li>
   <li role="menuitem">Copy</li>
   <li role="menuitem">Paste</li>
   </ul>
  </li>
 …
</ul>

However there is now a note which said "Application menus typically do not have links and rely on scripting to provide the functionality." so the correct menu for a website might be this here.


问:
spring-security block websocket (sockjs)
In one of my projects I configured both rest services and websockets, both go through spring security filter that check for JWT. For websockets on the client side, application uses sockjs & stomp (on Angular2) and Spring websockets on the server side (Tomcat 8). When I open connection with Spring security enabled then I get below error two seconds after it gets opened. However when I open connection without spring security enabled connection does not get dropped.

angular2 connect()/subscribe()/send() - all go with JWT token

public connect() : void {
        let sockjs = new SockJS('/rest/add?jwt=' + this.authService.getToken());
        let headers : any = this.authService.getAuthHeader();
        this.stompClient = Stomp.over(sockjs);
        this.stompClient.connect(this.token, (frame) => {
            this.log.d("frame", "My Frame: " + frame);
            this.log.d("connected()", "connected to /add");
            this.stompClient.subscribe('/topic/addMessage', this.authService.getAuthHeader(), (stompResponse) => {
                // this.stompSubject.next(JSON.parse(stompResponse.body));
                this.log.d("result of WS call: ", JSON.parse(stompResponse.body).message);
            }, (error) => {
                this.log.d(error);
            });
        });
    }

    public send(payload: string) {
        this.stompClient.send("/app/add", this.token, JSON.stringify({'message': payload}));
    }```
</div>
</div>
</p>

<p><strong>JwtAuthenticationFilter.java</strong> </p>

```public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public JwtAuthenticationFilter() {
        super("/rest/**");
    }

    @Override
    protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
        return true;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String token = null;

        String param = request.getParameter("jwt");
        if(param == null) {
            String header = request.getHeader("Authorization");
            if (header == null || !header.startsWith("Bearer ")) {
                throw new JwtAuthenticationException("No JWT token found in request headers");
            }
            token = header.substring(7);
        } else {
            token = param;
        }
        JwtAuthenticationToken authRequest = new JwtAuthenticationToken(token);

        return getAuthenticationManager().authenticate(authRequest);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authResult);

        // As this authentication is in HTTP header, after success we need to continue the request normally
        // and return the response as if the resource was not secured at all
        chain.doFilter(request, response);
    }
}
```

<p><strong>JwtAuthenticationProvider.java</strong></p>

```@Service
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    @Autowired
    private SecurityService securityService;

    @Override
    public boolean supports(Class<?> authentication) {
        return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    }

    @Override
    @Transactional(readOnly=true)
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
        String token = jwtAuthenticationToken.getToken();

        User user = securityService.parseToken(token);

        if (user == null) {
            throw new JwtAuthenticationException("JWT token is not valid");
        }

        return new AuthenticatedUser(user);
    }
}
```

<p><strong>JwtAuthenticationSuccessHandler.java</strong></p>

```@Service
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // We do not need to do anything extra on REST authentication success, because there is no page to redirect to
    }

}
```

<p><strong>RestAuthenticationEntryPoint.java</strong></p>

```@Service
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // This is invoked when user tries to access a secured REST resource without supplying any credentials
        // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}
```

<p><strong>Weboscket configuration:</strong></p>

```<websocket:message-broker
    application-destination-prefix="/app">
    <websocket:stomp-endpoint path="/add">
        <websocket:sockjs />
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic, /queue" />
</websocket:message-broker>
```

<p>and my spring security</p>

```<context:component-scan base-package="com.myapp.ws.security"/>

<sec:global-method-security pre-post-annotations="enabled" />

<sec:http pattern="/rest/login/" security="none" />

<sec:http pattern="/rest/**" entry-point-ref="restAuthenticationEntryPoint" create-session="stateless">

    <sec:csrf disabled="true" />

    <sec:custom-filter before="FORM_LOGIN_FILTER" ref="jwtAuthenticationFilter" />
</sec:http>

<bean id="jwtAuthenticationFilter" class="com.myapp.ws.security.JwtAuthenticationFilter">
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="authenticationSuccessHandler" ref="jwtAuthenticationSuccessHandler" />
</bean>

<sec:authentication-manager alias="authenticationManager">
    <sec:authentication-provider ref="jwtAuthenticationProvider" />
</sec:authentication-manager>
```

答:
Your problem doesn't related to security. You just pass wrong arguments in Stomp connect and subscribe functions.

The connect() method also accepts two other variants if you need to
  pass additional headers:

client.connect(headers, connectCallback);

    client.connect(headers, connectCallback, errorCallback);

where header is a map and connectCallback and errorCallback are
  functions.

```<code>this.stompClient.connect(this.token, (frame) => {
</code>```

should be

```<code>this.stompClient.connect({}, (frame) => {
</code>```

and

You can use the subscribe() method to subscribe to a destination. The
  method takes 2 mandatory arguments: destination, a String
  corresponding to the destination and callback, a function with one
  message argument and an optional argument headers, a JavaScript object
  for additional headers.

var subscription = client.subscribe("/queue/test", callback);

```<code>this.stompClient.subscribe('/topic/addMessage', this.authService.getAuthHeader(), (stompResponse) => {
</code>```

should be

```<code>this.stompClient.subscribe('/topic/addMessage', (stompResponse) => {
</code>```

Documentation http://jmesnil.net/stomp-websocket/doc/

Body:
In one of my projects I configured both rest services and websockets, both go through spring security filter that check for JWT. For websockets on the client side, application uses sockjs & stomp (on Angular2) and Spring websockets on the server side (Tomcat 8). When I open connection with Spring security enabled then I get below error two seconds after it gets opened. However when I open connection without spring security enabled connection does not get dropped.

angular2 connect()/subscribe()/send() - all go with JWT token

public connect() : void {
        let sockjs = new SockJS('/rest/add?jwt=' + this.authService.getToken());
        let headers : any = this.authService.getAuthHeader();
        this.stompClient = Stomp.over(sockjs);
        this.stompClient.connect(this.token, (frame) => {
            this.log.d("frame", "My Frame: " + frame);
            this.log.d("connected()", "connected to /add");
            this.stompClient.subscribe('/topic/addMessage', this.authService.getAuthHeader(), (stompResponse) => {
                // this.stompSubject.next(JSON.parse(stompResponse.body));
                this.log.d("result of WS call: ", JSON.parse(stompResponse.body).message);
            }, (error) => {
                this.log.d(error);
            });
        });
    }

    public send(payload: string) {
        this.stompClient.send("/app/add", this.token, JSON.stringify({'message': payload}));
    }

JwtAuthenticationFilter.java

public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public JwtAuthenticationFilter() {
        super("/rest/**");
    }

    @Override
    protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
        return true;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String token = null;

        String param = request.getParameter("jwt");
        if(param == null) {
            String header = request.getHeader("Authorization");
            if (header == null || !header.startsWith("Bearer ")) {
                throw new JwtAuthenticationException("No JWT token found in request headers");
            }
            token = header.substring(7);
        } else {
            token = param;
        }
        JwtAuthenticationToken authRequest = new JwtAuthenticationToken(token);

        return getAuthenticationManager().authenticate(authRequest);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authResult);

        // As this authentication is in HTTP header, after success we need to continue the request normally
        // and return the response as if the resource was not secured at all
        chain.doFilter(request, response);
    }
}

JwtAuthenticationProvider.java

@Service
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    @Autowired
    private SecurityService securityService;

    @Override
    public boolean supports(Class<?> authentication) {
        return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    }

    @Override
    @Transactional(readOnly=true)
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
        String token = jwtAuthenticationToken.getToken();

        User user = securityService.parseToken(token);

        if (user == null) {
            throw new JwtAuthenticationException("JWT token is not valid");
        }

        return new AuthenticatedUser(user);
    }
}

JwtAuthenticationSuccessHandler.java

@Service
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // We do not need to do anything extra on REST authentication success, because there is no page to redirect to
    }

}

RestAuthenticationEntryPoint.java

@Service
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // This is invoked when user tries to access a secured REST resource without supplying any credentials
        // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }
}

Weboscket configuration:

<websocket:message-broker
    application-destination-prefix="/app">
    <websocket:stomp-endpoint path="/add">
        <websocket:sockjs />
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic, /queue" />
</websocket:message-broker>

and my spring security

<context:component-scan base-package="com.myapp.ws.security"/>

<sec:global-method-security pre-post-annotations="enabled" />

<sec:http pattern="/rest/login/" security="none" />

<sec:http pattern="/rest/**" entry-point-ref="restAuthenticationEntryPoint" create-session="stateless">

    <sec:csrf disabled="true" />

    <sec:custom-filter before="FORM_LOGIN_FILTER" ref="jwtAuthenticationFilter" />
</sec:http>

<bean id="jwtAuthenticationFilter" class="com.myapp.ws.security.JwtAuthenticationFilter">
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="authenticationSuccessHandler" ref="jwtAuthenticationSuccessHandler" />
</bean>

<sec:authentication-manager alias="authenticationManager">
    <sec:authentication-provider ref="jwtAuthenticationProvider" />
</sec:authentication-manager>

Body:
Your problem doesn't related to security. You just pass wrong arguments in Stomp connect and subscribe functions.

The connect() method also accepts two other variants if you need to
  pass additional headers:

client.connect(headers, connectCallback);

    client.connect(headers, connectCallback, errorCallback);

where header is a map and connectCallback and errorCallback are
  functions.

this.stompClient.connect(this.token, (frame) => {

should be

this.stompClient.connect({}, (frame) => {

and

You can use the subscribe() method to subscribe to a destination. The
  method takes 2 mandatory arguments: destination, a String
  corresponding to the destination and callback, a function with one
  message argument and an optional argument headers, a JavaScript object
  for additional headers.

var subscription = client.subscribe("/queue/test", callback);

this.stompClient.subscribe('/topic/addMessage', this.authService.getAuthHeader(), (stompResponse) => {

should be

this.stompClient.subscribe('/topic/addMessage', (stompResponse) => {

Documentation http://jmesnil.net/stomp-websocket/doc/


问:
Insert a field with value whenever new instance of modal is created
I want to insert a field with value whenever new row is created for a modal.

Ex:  Suppose this is my user.php modal

```<code>class User extends Authenticatable
{
 protected $guarded = ['id'];
}
</code>```

What i want is in my application anywhere when i insert a row in user table, then i want to insert an extra column code with its value in user table.

Ex: If i do below in my application

```<code>User::create(['name'=>'xyz', 'password' => 'kajsndjk']);
</code>```

then it should insert an extra column code =>'Qwedf' also in my table.

In my application there are many places where i am creating the users, so i don't want to remember every time to insert code column.

Please suggest how can i achieve it.

答:
Add this mutator to your User model

```<code>public function setCodeAttribute($value)
{
    $this->attributes['code'] = "Qwedf";
}
</code>```

Anytime you are saving a record code will be assigned the Qwedf value

Body:
I want to insert a field with value whenever new row is created for a modal.

Ex:  Suppose this is my user.php modal

class User extends Authenticatable
{
 protected $guarded = ['id'];
}

What i want is in my application anywhere when i insert a row in user table, then i want to insert an extra column code with its value in user table.

Ex: If i do below in my application

User::create(['name'=>'xyz', 'password' => 'kajsndjk']);

then it should insert an extra column code =>'Qwedf' also in my table.

In my application there are many places where i am creating the users, so i don't want to remember every time to insert code column.

Please suggest how can i achieve it.

Body:
Add this mutator to your User model

public function setCodeAttribute($value)
{
    $this->attributes['code'] = "Qwedf";
}

Anytime you are saving a record code will be assigned the Qwedf value