问:
Adding class cotaining std::thread to a vector
Class declaration:

```<code>class cA{
private:
  std::thread t;
public:
  cA()=default;
};
</code>```

Somehere in another source file:

```<code>cA *a = new cA();
std::vector<cA> v;
v.push_back(*a);
</code>```

This results in the following error at compile time:

```<code>C2280: cA::cA(const cA &)': attempting to reference a deleted function
</code>```

I think it might have something to do with the fact that std::thread is missing a copy constructor and that the vector tries to make a copy of the cA object. Would anyone be willing to explain?

答:
std::thread is not copyable, so the compiler can not generate a default copy constructor because it doesn't know what to do with the uncopyable type in the class.  What would it put in the std::thread variable in the new copy?

Because it cannot generate the copy constructor, it is deleted, the same as if you had said

```<code>cA(const cA &) = delete;
</code>```

in your class definition.

Here are the rules for when it can and cannot create an implicit copy constructor:

http://en.cppreference.com/w/cpp/language/copy_constructor

The line relevant to your situation is:

T has non-static data members that cannot be copied (have deleted, inaccessible, or ambiguous copy constructors);

Also, as a comment on your question points out, your actual code, even if it did compile, isn't good.  It will leak a cA object.  The correct code here (fixed per comment):

```<code>v.emplace_back();  // since the cA constructor takes no parameters
</code>```

or

```<code>v.push_back(cA());
</code>```

Neither of these require cA to be copyable because its move constructor is used.

Body:
Class declaration:

class cA{
private:
  std::thread t;
public:
  cA()=default;
};

Somehere in another source file:

cA *a = new cA();
std::vector<cA> v;
v.push_back(*a);

This results in the following error at compile time:

C2280: cA::cA(const cA &)': attempting to reference a deleted function

I think it might have something to do with the fact that std::thread is missing a copy constructor and that the vector tries to make a copy of the cA object. Would anyone be willing to explain?

Body:
std::thread is not copyable, so the compiler can not generate a default copy constructor because it doesn't know what to do with the uncopyable type in the class.  What would it put in the std::thread variable in the new copy?

Because it cannot generate the copy constructor, it is deleted, the same as if you had said

cA(const cA &) = delete;

in your class definition.

Here are the rules for when it can and cannot create an implicit copy constructor:

http://en.cppreference.com/w/cpp/language/copy_constructor

The line relevant to your situation is:

T has non-static data members that cannot be copied (have deleted, inaccessible, or ambiguous copy constructors);

Also, as a comment on your question points out, your actual code, even if it did compile, isn't good.  It will leak a cA object.  The correct code here (fixed per comment):

v.emplace_back();  // since the cA constructor takes no parameters

or

v.push_back(cA());

Neither of these require cA to be copyable because its move constructor is used.


来源: stackexchange

问:
why im unable to get posted data using ajax in laravel
I'm getting some junk data instead of my posted data in laravel 5.4

here is my route

```<code>Route::post('capture-rating',function(Request $request){

       dd($request);
});
</code>```

my $.ajax looks like this

```<code>    var rating = 4;
     $.ajax({
        url:'capture-rating',
        type:'post',
        //dataType:'json',

        data:{rating:rating},

        success:function(data){
            console.log(data);
        }
     });
</code>```

here is network tab console image

i'm getting this junk data why i don't know?

```<code><script> Sfdump = window.Sfdump || (function (doc) { var refStyle = doc.createElement('style'), rxEsc = /([.*+?^${}()|\[\]\/\\])/g, idRx = /\bsf-dump-\d+-ref[012]\w+\b/, keyHint = 0 <= navigator.platform.toUpperCase().indexOf('MAC') ? 'Cmd' : 'Ctrl', addEventListener = function (e, n, cb) { e.addEventListener(n, cb, false); }; (doc.documentElement.firstElementChild || doc.documentElement.children[0]).appendChild(refStyle); if (!doc.addEventListener) { addEventListener = function (element, eventName, callback) { element.attachEvent('on' + eventName, function (e) { e.preventDefault = function () {e.returnValue = false;}; e.target = e.srcElement; callback(e); }); }; } function toggle(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className, arrow, newClass; if ('sf-dump-compact' == oldClass) { arrow = '▼'; newClass = 'sf-dump-expanded'; } else if ('sf-dump-expanded' == oldClass) { arrow = '▶'; newClass = 'sf-dump-compact'; } else { return false; } a.lastChild.innerHTML = arrow; s.className = newClass; if (recursive) { try { a = s.querySelectorAll('.'+oldClass); for (s = 0; s < a.length; ++s) { if (a[s].className !== newClass) { a[s].className = newClass; a[s].previousSibling.lastChild.innerHTML = arrow; } } } catch (e) { } } return true; }; function collapse(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if ('sf-dump-expanded' == oldClass) { toggle(a, recursive); return true; } return false; }; function expand(a, recursive) { var s = a.nextSibling || {}, oldClass = s.className; if ('sf-dump-compact' == oldClass) { toggle(a, recursive); return true; } return false; }; function collapseAll(root) { var a = root.querySelector('a.sf-dump-toggle'); if (a) { collapse(a, true); expand(a); return true; } return false; } function reveal(node) { var previous, parents = []; while ((node = node.parentNode || {}) && (previous = node.previousSibling) && 'A' === previous.tagName) { parents.push(previous); } if (0 !== parents.length) { parents.forEach(function (parent) { expand(parent); }); return true; } return false; } function highlight(root, activeNode, nodes) { resetHighlightedNodes(root); Array.from(nodes||[]).forEach(function (node) { if (!/\bsf-dump-highlight\b/.test(node.className)) { node.className = node.className + ' sf-dump-highlight'; } }); if (!/\bsf-dump-highlight-active\b/.test(activeNode.className)) { activeNode.className = activeNode.className + ' sf-dump-highlight-active'; } } function resetHighlightedNodes(root) { Array.from(root.querySelectorAll('.sf-dump-str, .sf-dump-key, .sf-dump-public, .sf-dump-protected, .sf-dump-private')).forEach(function (strNode) { strNode.className = strNode.className.replace(/\b sf-dump-highlight\b/, ''); strNode.className = strNode.className.replace(/\b sf-dump-highlight-active\b/, ''); }); } return function (root, x) { root = doc.getElementById(root); var indentRx = new RegExp('^('+(root.getAttribute('data-indent-pad') || ' ').replace(rxEsc, '\\$1')+')+', 'm'), options = {"maxDepth":1,"maxStringLength":160,"fileLinkFormat":false}, elt = root.getElementsByTagName('A'), len = elt.length, i = 0, s, h, t = []; while (i < len) t.push(elt[i++]); for (i in x) { options[i] = x[i]; } function a(e, f) { addEventListener(root, e, function (e) { if ('A' == e.target.tagName) { f(e.target, e); } else if ('A' == e.target.parentNode.tagName) { f(e.target.parentNode, e); } else if (e.target.nextElementSibling && 'A' == e.target.nextElementSibling.tagName) { f(e.target.nextElementSibling, e, true); } }); }; function isCtrlKey(e) { return e.ctrlKey || e.metaKey; } function xpathString(str) { var parts = str.match(/[^'"]+|['"]/g).map(function (part) { if ("'" == part) { return '"\'"'; } if ('"' == part) { return "'\"'"; } return "'" + part + "'"; }); return "concat(" + parts.join(",") + ", '')"; } addEventListener(root, 'mouseover', function (e) { if ('' != refStyle.innerHTML) { refStyle.innerHTML = ''; } }); a('mouseover', function (a, e, c) { if (c) { e.target.style.cursor = "pointer"; } else if (a = idRx.exec(a.className)) { try { refStyle.innerHTML = 'pre.sf-dump .'+a[0]+'{background-color: #B729D9; color: #FFF !important; border-radius: 2px}'; } catch (e) { } } }); a('click', function (a, e, c) { if (/\bsf-dump-toggle\b/.test(a.className)) { e.preventDefault(); if (!toggle(a, isCtrlKey(e))) { var r = doc.getElementById(a.getAttribute('href').substr(1)), s = r.previousSibling, f = r.parentNode, t = a.parentNode; t.replaceChild(r, a); f.replaceChild(a, s); t.insertBefore(s, r); f = f.firstChild.nodeValue.match(indentRx); t = t.firstChild.nodeValue.match(indentRx); if (f && t && f[0] !== t[0]) { r.innerHTML = r.innerHTML.replace(new RegExp('^'+f[0].replace(rxEsc, '\\$1'), 'mg'), t[0]); } if ('sf-dump-compact' == r.className) { toggle(s, isCtrlKey(e)); } } if (c) { } else if (doc.getSelection) { try { doc.getSelection().removeAllRanges(); } catch (e) { doc.getSelection().empty(); } } else { doc.selection.empty(); } } else if (/\bsf-dump-str-toggle\b/.test(a.className)) { e.preventDefault(); e = a.parentNode.parentNode; e.className = e.className.replace(/sf-dump-str-(expand|collapse)/, a.parentNode.className); } }); elt = root.getElementsByTagName('SAMP'); len = elt.length; i = 0; while (i < len) t.push(elt[i++]); len = t.length; for (i = 0; i < len; ++i) { elt = t[i]; if ('SAMP' == elt.tagName) { elt.className = 'sf-dump-expanded'; a = elt.previousSibling || {}; if ('A' != a.tagName) { a = doc.createElement('A'); a.className = 'sf-dump-ref'; elt.parentNode.insertBefore(a, elt); } else { a.innerHTML += ' '; } a.title = (a.title ? a.title+'\n[' : '[')+keyHint+'+click] Expand all children'; a.innerHTML += '<span>▼</span>'; a.className += ' sf-dump-toggle'; x = 1; if ('sf-dump' != elt.parentNode.className) { x += elt.parentNode.getAttribute('data-depth')/1; } elt.setAttribute('data-depth', x); if (x > options.maxDepth) { toggle(a); } } else if ('sf-dump-ref' == elt.className && (a = elt.getAttribute('href'))) { a = a.substr(1); elt.className += ' '+a; if (/[\[{]$/.test(elt.previousSibling.nodeValue)) { a = a != elt.nextSibling.id && doc.getElementById(a); try { s = a.nextSibling; elt.appendChild(a); s.parentNode.insertBefore(a, s); if (/^[@#]/.test(elt.innerHTML)) { elt.innerHTML += ' <span>▶</span>'; } else { elt.innerHTML = '<span>▶</span>'; elt.className = 'sf-dump-ref'; } elt.className += ' sf-dump-toggle'; } catch (e) { if ('&' == elt.innerHTML.charAt(0)) { elt.innerHTML = '…'; elt.className = 'sf-dump-ref'; } } } } } if (doc.evaluate && Array.from && root.children.length > 1) { root.setAttribute('tabindex', 0); SearchState = function () { this.nodes = []; this.idx = 0; }; SearchState.prototype = { next: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx < (this.nodes.length - 1) ? this.idx + 1 : this.idx; return this.current(); }, previous: function () { if (this.isEmpty()) { return this.current(); } this.idx = this.idx > 0 ? this.idx - 1 : this.idx; return this.current(); }, isEmpty: function () { return 0 === this.count(); }, current: function () { if (this.isEmpty()) { return null; } return this.nodes[this.idx]; }, reset: function () { this.nodes = []; this.idx = 0; }, count: function () { return this.nodes.length; }, }; function showCurrent(state) { var currentNode = state.current(); if (currentNode) { reveal(currentNode); highlight(root, currentNode, state.nodes); } counter.textContent = (state.isEmpty() ? 0 : state.idx + 1) + ' of ' + state.count(); } var search = doc.createElement('div'); search.className = 'sf-dump-search-wrapper sf-dump-search-hidden'; search.innerHTML = ' <input type="text" class="sf-dump-search-input"> <span class="sf-dump-search-count">0 of 0<\/span> <button type="button" class="sf-dump-search-input-previous" tabindex="-1"> <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"> <path d="M1683 1331l-166 165q-19 19-45 19t-45-19l-531-531-531 531q-19 19-45 19t-45-19l-166-165q-19-19-19-45.5t19-45.5l742-741q19-19 45-19t45 19l742 741q19 19 19 45.5t-19 45.5z"\/> <\/svg> <\/button> <button type="button" class="sf-dump-search-input-next" tabindex="-1"> <svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"> <path d="M1683 808l-742 741q-19 19-45 19t-45-19l-742-741q-19-19-19-45.5t19-45.5l166-165q19-19 45-19t45 19l531 531 531-531q19-19 45-19t45 19l166 165q19 19 19 45.5t-19 45.5z"\/> <\/svg> <\/button> '; root.insertBefore(search, root.firstChild); var state = new SearchState(); var searchInput = search.querySelector('.sf-dump-search-input'); var counter = search.querySelector('.sf-dump-search-count'); var searchInputTimer = 0; var previousSearchQuery = ''; addEventListener(searchInput, 'keyup', function (e) { var searchQuery = e.target.value; /* Don't perform anything if the pressed key didn't change the query */ if (searchQuery === previousSearchQuery) { return; } previousSearchQuery = searchQuery; clearTimeout(searchInputTimer); searchInputTimer = setTimeout(function () { state.reset(); collapseAll(root); resetHighlightedNodes(root); if ('' === searchQuery) { counter.textContent = '0 of 0'; return; } var xpathResult = doc.evaluate('//pre[@id="' + root.id + '"]//span[@class="sf-dump-str" or @class="sf-dump-key" or @class="sf-dump-public" or @class="sf-dump-protected" or @class="sf-dump-private"][contains(child::text(), ' + xpathString(searchQuery) + ')]', document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); while (node = xpathResult.iterateNext()) state.nodes.push(node); showCurrent(state); }, 400); }); Array.from(search.querySelectorAll('.sf-dump-search-input-next, .sf-dump-search-input-previous')).forEach(function (btn) { addEventListener(btn, 'click', function (e) { e.preventDefault(); var direction = -1 !== e.target.className.indexOf('next') ? 'next' : 'previous'; 'next' === direction ? state.next() : state.previous(); searchInput.focus(); collapseAll(root); showCurrent(state); }) }); addEventListener(root, 'keydown', function (e) { var isSearchActive = !/\bsf-dump-search-hidden\b/.test(search.className); if ((114 === e.keyCode && !isSearchActive) || (isCtrlKey(e) && 70 === e.keyCode)) { /* F3 or CMD/CTRL + F */ e.preventDefault(); search.className = search.className.replace(/\bsf-dump-search-hidden\b/, ''); searchInput.focus(); } else if (isSearchActive) { if (27 === e.keyCode) { /* ESC key */ search.className += ' sf-dump-search-hidden'; e.preventDefault(); resetHighlightedNodes(root); searchInput.value = ''; } else if ( (isCtrlKey(e) && 71 === e.keyCode) /* CMD/CTRL + G */ || 13 === e.keyCode /* Enter */ || 114 === e.keyCode /* F3 */ ) { e.preventDefault(); e.shiftKey ? state.previous() : state.next(); collapseAll(root); showCurrent(state); } } }); } if (0 >= options.maxStringLength) { return; } try { elt = root.querySelectorAll('.sf-dump-str'); len = elt.length; i = 0; t = []; while (i < len) t.push(elt[i++]); len = t.length; for (i = 0; i < len; ++i) { elt = t[i]; s = elt.innerText || elt.textContent; x = s.length - options.maxStringLength; if (0 < x) { h = elt.innerHTML; elt[elt.innerText ? 'innerText' : 'textContent'] = s.substring(0, options.maxStringLength); elt.className += ' sf-dump-str-collapse'; elt.innerHTML = '<span class=sf-dump-str-collapse>'+h+'<a class="sf-dump-ref sf-dump-str-toggle" title="Collapse"> ◀</a></span>'+ '<span class=sf-dump-str-expand>'+elt.innerHTML+'<a class="sf-dump-ref sf-dump-str-toggle" title="'+x+' remaining characters"> ▶</a></span>'; } } } catch (e) { } }; })(document); </script><style> pre.sf-dump { display: block; white-space: pre; padding: 5px; } pre.sf-dump:after { content: ""; visibility: hidden; display: block; height: 0; clear: both; } pre.sf-dump span { display: inline; } pre.sf-dump .sf-dump-compact { display: none; } pre.sf-dump abbr { text-decoration: none; border: none; cursor: help; } pre.sf-dump a { text-decoration: none; cursor: pointer; border: 0; outline: none; color: inherit; } pre.sf-dump .sf-dump-ellipsis { display: inline-block; overflow: visible; text-overflow: ellipsis; max-width: 5em; white-space: nowrap; overflow: hidden; vertical-align: top; } pre.sf-dump .sf-dump-ellipsis+.sf-dump-ellipsis { max-width: none; } pre.sf-dump code { display:inline; padding:0; background:none; } .sf-dump-str-collapse .sf-dump-str-collapse { display: none; } .sf-dump-str-expand .sf-dump-str-expand { display: none; } .sf-dump-public.sf-dump-highlight, .sf-dump-protected.sf-dump-highlight, .sf-dump-private.sf-dump-highlight, .sf-dump-str.sf-dump-highlight, .sf-dump-key.sf-dump-highlight { background: rgba(111, 172, 204, 0.3); border: 1px solid #7DA0B1; border-radius: 3px; } .sf-dump-public.sf-dump-highlight-active, .sf-dump-protected.sf-dump-highlight-active, .sf-dump-private.sf-dump-highlight-active, .sf-dump-str.sf-dump-highlight-active, .sf-dump-key.sf-dump-highlight-active { background: rgba(253, 175, 0, 0.4); border: 1px solid #ffa500; border-radius: 3px; } pre.sf-dump .sf-dump-search-hidden { display: none; } pre.sf-dump .sf-dump-search-wrapper { float: right; font-size: 0; white-space: nowrap; max-width: 100%; text-align: right; } pre.sf-dump .sf-dump-search-wrapper > * { vertical-align: top; box-sizing: border-box; height: 21px; font-weight: normal; border-radius: 0; background: #FFF; color: #757575; border: 1px solid #BBB; } pre.sf-dump .sf-dump-search-wrapper > input.sf-dump-search-input { padding: 3px; height: 21px; font-size: 12px; border-right: none; width: 140px; border-top-left-radius: 3px; border-bottom-left-radius: 3px; color: #000; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next, pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous { background: #F2F2F2; outline: none; border-left: none; font-size: 0; line-height: 0; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next { border-top-right-radius: 3px; border-bottom-right-radius: 3px; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-next > svg, pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-input-previous > svg { pointer-events: none; width: 12px; height: 12px; } pre.sf-dump .sf-dump-search-wrapper > .sf-dump-search-count { display: inline-block; padding: 0 5px; margin: 0; border-left: none; line-height: 21px; font-size: 12px; }pre.sf-dump, pre.sf-dump .sf-dump-default{background-color:#fff; color:#222; line-height:1.2em; font-weight:normal; font:12px Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:100000}pre.sf-dump .sf-dump-num{color:#a71d5d}pre.sf-dump .sf-dump-const{color:#795da3}pre.sf-dump .sf-dump-str{color:#df5000}pre.sf-dump .sf-dump-cchr{color:#222}pre.sf-dump .sf-dump-note{color:#a71d5d}pre.sf-dump .sf-dump-ref{color:#a0a0a0}pre.sf-dump .sf-dump-public{color:#795da3}pre.sf-dump .sf-dump-protected{color:#795da3}pre.sf-dump .sf-dump-private{color:#795da3}pre.sf-dump .sf-dump-meta{color:#b729d9}pre.sf-dump .sf-dump-key{color:#df5000}pre.sf-dump .sf-dump-index{color:#a71d5d}</style><pre class=sf-dump id=sf-dump-160511467 data-indent-pad="  "><abbr title="Illuminate\Support\Facades\Request" class=sf-dump-note>Request</abbr> {<a class=sf-dump-ref>#172</a>}
</code>```

still i haven't found the solution please help me

答:
You are currently in route http://http:localhost:8000/rating.
If you call ajax request to url:'capture-rating', your url target will change to http://http:localhost:8000/rating/capture-rating.

Try to give name to route.

Route::post('capture-rating',function(Request $request){
       dd($request);
})->name('capture-rating');

then change url property to :

url:'{{ route('capture-rating') }}',

ContentLicense: CC BY-SA 3.0

Body:
I'm getting some junk data instead of my posted data in laravel 5.4

here is my route

Route::post('capture-rating',function(Request $request){

       dd($request);
});

my $.ajax looks like this

    var rating = 4;
     $.ajax({
        url:'capture-rating',
        type:'post',
        //dataType:'json',

        data:{rating:rating},

        success:function(data){
            console.log(data);
        }
     });

here is network tab console image

i'm getting this junk data why i don't know?

Request {#172}

still i haven't found the solution please help me


问:
Is there a better way to block property overloading?
```<code><?php
class Item {
 public function __set($name, $value){
  throw new Exception('Overloading is forbidden.');
 }

 public function __get($name){
  throw new Exception('Overloading is forbidden.');
 }
}
</code>```

<p>I want to make sure I set all required object properties, but if I mistype a property name PHP just adds a new property and the prop I wanted to initialize remains null. </p>

答: Using http://php.net/manual/en/function.get-class-vars.php you can check for existence of the variable and for example throw exception when fails</p>

ContentLicense: CC BY-SA 2.5

Body:
<?php
class Item {
 public function __set($name, $value){
  throw new Exception('Overloading is forbidden.');
 }

 public function __get($name){
  throw new Exception('Overloading is forbidden.');
 }
}

I want to make sure I set all required object properties, but if I mistype a property name PHP just adds a new property and the prop I wanted to initialize remains null.


问:
neural network for sudoku solver
I recently started learning neural networks, and I thought that creating a sudoku solver would be a nice application for NN. I started learning them with backward propagation neural network, but later I figured that there are tens of neural networks. At this point, I find it hard to learn all of them and then pick an appropriate one for my purpose. Hence, I am asking what would be a good choice for creating this solver. Can back propagation NN work here? If not, can you explain why and tell me which one can work.
Thanks!</p>

答:
Neural networks don't really seem to be the best way to solve sudoku, as others have already pointed out. I think a better (but also not really good/efficient) way would be to use an genetic algorithm. Genetic algorithms don't directly relate to NNs but its very useful to know how they work.

Better (with better i mean more likely to be sussessful and probably better for you to learn something new) ideas would include:

If you use a library:

Play around with the networks, try to train them to different datasets, maybe random numbers and see what you get and how you have to tune the parameters to get better results.

Try to write an image generator. I wrote a few of them and they are stil my favourite projects, with one of them i used backprop to teach a NN what x/y coordinate of the image has which color, and the other aproach combines random generated images with ine another (GAN/NEAT).

Try to use create a movie (series of images) of the network learning to create a picture. It will show you very well how backprop works and what parameter tuning does to the results and how it changes how the network gets to the result.

If you are not using a library:

Try to solve easy problems, one after the other. Use backprop or a genetic algorithm for training (whatever you have implemented).

Try to improove your implementation and change some things that nobody else cares about and see how it changes the results.

List of 'tasks' for your Network:

XOR (basically the hello world of NN)

Pole balancing problem

Simple games like pong

More complex games like flappy bird, agar.io etc.

Choose more problems that you find interesting, maybe you are into image recognition, maybe text, audio, who knows. Think of something you can/would like to be able to do and find a way to make you computer do it for you.

It's not advisable to only use your own NN implemetation, since it will probably not work properly the first few times and you'll get frustratet. Experiment with librarys and your own implementation.

Good way to find almost endless resources:
Use google search and add 'filetype:pdf' in the end in order to only show pdf files. Search for neural network, genetic algorithm, evolutional neural network.

Title: neural network for sudoku solver


问:
SAML integration to Angular JS with rails back end
The current scenario I am working on requires me to integrate SAML or single sign on in an Angular application having a rails back end. To start I have been able to send a request to my IdP and have received a response in the form of XML which I parse using nokogiri and I have a few credentials with which I can create the user inside the database. The problem however is I am unable to sign user in and keep them signed in once they are created.

I have ng-token-auth implemented on the front end and devise_token_auth on back end. I have used omniauth-saml gem to send a request to the IdP which responds with a post request and I have a seperate controller inheriting ::DeviseTokenAuth::OmniauthCallbacksController and having the post route where I consume the response of the IdP.

Once I have done that and the user is created inside the database I cannot figure out how to sign the user in. I do the following and I can see the sign in count incrementing on the back end but on the client side the user stays signed out.

```<code>@resource = User.find_or_create_user(idp_response)
if @resource.persisted?
  set_token_on_resource
  create_auth_params
  sign_in(:user, @resource, store: false, bypass: false)
  yield @resource if block_given?
  render_data_or_redirect('deliverCredentials', @auth_params.as_json, @resource.as_json)
</code>```

It seems like I have reached a state of a dead end for some time now. I am not sure how I can authenticate user on the front end manually as a response from my IdP. Any help would be appreciated.

答:
In your controller where the sign in request is hit..

```<code>response = SIGN_IN_REQUEST_API
session[:api_tokens] = response.headers
</code>```

In your application_layout.html.haml,

```<code>- if (tokens = session[:api_tokens]).present?
  :javascript
    myApp.controller('cookieController', function($scope, $resource, $http, $mdDialog, $auth, ipCookie ) {
      ipCookie('auth_headers', '{"access-token": "{token["access-token"]}","token-type": "Bearer","client": "#{token["client"]}","expiry": "#{token["expiry"]}","uid": "#{token["uid"]}"}", {path: "/",expires: 9999,expirationUnit: "days",secure: false}');
      ipCookie('currentConfigName', 'default', {path: '/',expires: 9999,expirationUnit: 'days',secure: false});
    });
  - session.delete(:api_tokens)
  %div{'ng-controller'=>'cookieController'}
</code>```

Reference

Body:
The current scenario I am working on requires me to integrate SAML or single sign on in an Angular application having a rails back end. To start I have been able to send a request to my IdP and have received a response in the form of XML which I parse using nokogiri and I have a few credentials with which I can create the user inside the database. The problem however is I am unable to sign user in and keep them signed in once they are created.

I have ng-token-auth implemented on the front end and devise_token_auth on back end. I have used omniauth-saml gem to send a request to the IdP which responds with a post request and I have a seperate controller inheriting ::DeviseTokenAuth::OmniauthCallbacksController and having the post route where I consume the response of the IdP.

Once I have done that and the user is created inside the database I cannot figure out how to sign the user in. I do the following and I can see the sign in count incrementing on the back end but on the client side the user stays signed out.

@resource = User.find_or_create_user(idp_response)
if @resource.persisted?
  set_token_on_resource
  create_auth_params
  sign_in(:user, @resource, store: false, bypass: false)
  yield @resource if block_given?
  render_data_or_redirect('deliverCredentials', @auth_params.as_json, @resource.as_json)

It seems like I have reached a state of a dead end for some time now. I am not sure how I can authenticate user on the front end manually as a response from my IdP. Any help would be appreciated.

Body:
In your controller where the sign in request is hit..

response = SIGN_IN_REQUEST_API
session[:api_tokens] = response.headers

In your application_layout.html.haml,

- if (tokens = session[:api_tokens]).present?
  :javascript
    myApp.controller('cookieController', function($scope, $resource, $http, $mdDialog, $auth, ipCookie ) {
      ipCookie('auth_headers', '{"access-token": "{token["access-token"]}","token-type": "Bearer","client": "#{token["client"]}","expiry": "#{token["expiry"]}","uid": "#{token["uid"]}"}", {path: "/",expires: 9999,expirationUnit: "days",secure: false}');
      ipCookie('currentConfigName', 'default', {path: '/',expires: 9999,expirationUnit: 'days',secure: false});
    });
  - session.delete(:api_tokens)
  %div{'ng-controller'=>'cookieController'}

Reference


问:
java reason: actual and formal argument lists differ in length
I need help creating a setter method for my code. I have created two setter methods for both of my string values, but I am A) not sure if they are implemented correct, and B) not sure how to call them so that they appear on the screen. Essentially I would like to be able to just call my lion and hippo classes and have them already have a name and a size, and not have to implement them inside my main function directly by inserting something like
 Hippo h = new Hippo("Tom", "42")

```<code>package game2;

public class Game2 {

    public static void main(String[] args) {
        //I am getting the error here, what I want to do is figure out how to
        //get this to work and then declare a name and size for the animal
        Hippo h = new Hippo();
        Lion l = new Lion();
    }

}
</code>```

```<code>package game2;

public abstract class Animal {
    private String name;
    private String Size;

    public String getName() {
        return name;
    }

    public String getSize() {
        return Size;
    }

    public void setName(String name) {
        name = "Tom";
    }

    public void setSize(String name) {
        name = "42";
    }

    public Animal(String theName, String theSize) {
        name = theName;
        Size = theSize;
    }
 }
</code>```

```<code>package game2;

public class Hippo extends Animal {

    public Hippo(String name, String Size) {
        super(name, Size);
    }
}
</code>```

```<code>package game2;

public class Lion extends Animal{

    public Lion(String name, String Size) {
        super(name, Size);
    }
}
</code>```

答:
Remember when implement constructor by your own, you are overload the default constructor. So you need to pass two arguments.

You didnot pass the arguments for constructors when you instantiate:

```<code>Hippo h = new Hippo();
Lion l = new Lion();
</code>```

Because your class constructors expect two parameters.

```<code>public Hippo(String name, String Size) {
    super(name, Size);
}
</code>```

And:

```<code>public Lion(String name, String Size) {
    super(name, Size);
}
</code>```

Solutions:

Either you can pass arguments when you instantiating objects:

```<code>Hippo h = new Hippo("name", "33");
Lion l = new Lion("name", "22");
</code>```

Or you need to implement overloaded constructors for these.

Read this to learn more about constructor overloading.

Body:
I need help creating a setter method for my code. I have created two setter methods for both of my string values, but I am A) not sure if they are implemented correct, and B) not sure how to call them so that they appear on the screen. Essentially I would like to be able to just call my lion and hippo classes and have them already have a name and a size, and not have to implement them inside my main function directly by inserting something like
 Hippo h = new Hippo("Tom", "42")

package game2;

public class Game2 {

    public static void main(String[] args) {
        //I am getting the error here, what I want to do is figure out how to
        //get this to work and then declare a name and size for the animal
        Hippo h = new Hippo();
        Lion l = new Lion();
    }

}

package game2;

public abstract class Animal {
    private String name;
    private String Size;

    public String getName() {
        return name;
    }

    public String getSize() {
        return Size;
    }

    public void setName(String name) {
        name = "Tom";
    }

    public void setSize(String name) {
        name = "42";
    }

    public Animal(String theName, String theSize) {
        name = theName;
        Size = theSize;
    }
 }

package game2;

public class Hippo extends Animal {

    public Hippo(String name, String Size) {
        super(name, Size);
    }
}

package game2;

public class Lion extends Animal{

    public Lion(String name, String Size) {
        super(name, Size);
    }
}

Body:
Remember when implement constructor by your own, you are overload the default constructor. So you need to pass two arguments.

You didnot pass the arguments for constructors when you instantiate:

Hippo h = new Hippo();
Lion l = new Lion();

Because your class constructors expect two parameters.

public Hippo(String name, String Size) {
    super(name, Size);
}

And:

public Lion(String name, String Size) {
    super(name, Size);
}

Solutions:

Either you can pass arguments when you instantiating objects:

Hippo h = new Hippo("name", "33");
Lion l = new Lion("name", "22");

Or you need to implement overloaded constructors for these.

Read this to learn more about constructor overloading.


问:
Unable to get material spinner working in android
I imported a custom material library Material by Rey for my Android project to use a spinner. I have made all the required changes but still, I get an error in my setAdapter function

"Cannot resolve method setPrompt"

The line of code throwing this error is:

```<code>spinner.setPrompt("Choose "+Utils.capsAllWords(names));
</code>```

Earlier I used the inbuilt Android spinner widget and the setPrompt() method worked fine. What changes can I make to get around this?

The xml for the widget is-

```<code><com.rey.material.widget.Spinner
android:id="@+id/spin1"
style="@style/MyStyle"/>
</code>```

In the activity I have imported com.rey.material.widget.Spinner and declared -

```<code>Spinner sp1;
sp1 = (Spinner) findViewById(R.id.spin1);
</code>```

答:
there is no setPrompt() option available in the library

try

```<code>spinner.setPromptText("Choose "+Utils.capsAllWords(names));
</code>```

Update
they didn't exposed the method in the library. You can customise suit your purpose

```<code><com.rey.material.widget.Spinner
android:id="@+id/spin1"
android:prompt="@string/message"
style="@style/MyStyle"/>
</code>```

Check this

Body:
I imported a custom material library Material by Rey for my Android project to use a spinner. I have made all the required changes but still, I get an error in my setAdapter function

"Cannot resolve method setPrompt"

The line of code throwing this error is:

spinner.setPrompt("Choose "+Utils.capsAllWords(names));

Earlier I used the inbuilt Android spinner widget and the setPrompt() method worked fine. What changes can I make to get around this?

The xml for the widget is-

<com.rey.material.widget.Spinner
android:id="@+id/spin1"
style="@style/MyStyle"/>

In the activity I have imported com.rey.material.widget.Spinner and declared -

Spinner sp1;
sp1 = (Spinner) findViewById(R.id.spin1);

Body:
there is no setPrompt() option available in the library

try

spinner.setPromptText("Choose "+Utils.capsAllWords(names));

Update
they didn't exposed the method in the library. You can customise suit your purpose

<com.rey.material.widget.Spinner
android:id="@+id/spin1"
android:prompt="@string/message"
style="@style/MyStyle"/>

Check this

ContentLicense: CC BY-SA 4.0


问:
how check one check box at one time in Jquery?
I want to click on check box at one time. when one check box checked other all check box unchecked.

$('.checkboxes-assign').on('change', function() {
  $('.checkboxes-assign').not(this).prop('checked', false);
});```
<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>
<table>
  <tr>
    <td class="text-center">
      <div class="checker">
        <span class=""><input type="checkbox" name="data[data_id][]" value="21" class="checkboxes-assign">
              </span></div>
    </td>
  </tr>
</table></code>```

答:
```<code>$("input:checkbox").click(function(){
    var group = "input:checkbox[name='"+$(this).attr("name")+"']";
    $(group).attr("checked",false);
    $(this).attr("checked",true);
});
</code>```

Body:
I want to click on check box at one time. when one check box checked other all check box unchecked.

$('.checkboxes-assign').on('change', function() {
  $('.checkboxes-assign').not(this).prop('checked', false);
});

        <input type="checkbox" name="data[data_id][]" value="21" class="checkboxes-assign">


问:
Angular2 - Set A Different Color to an element Depending On Value
I am new to Angular2 and was wondering how I go about setting a font color to an element depending on the value.

My scenario is: if the value of the input field is not 100 then I want it red but if it is 100 then I want it green.

I have the following code in place but cant get it working.

XXX.component.css

```<code>.red {
    color: red;
}

.green {
    color: green;
}
</code>```

XXX.component.css

```<code><input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion ">
<p>hello <span ng-class='{red : proportion!= '100', green: proportion === '100'}'>{{proportion}}</span></p>
</code>```

答:
Since you use Angular2, So you need to use [ngClass], and your input model is bind to proportion, So use it to compare,

Do it like :

```<code><input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion">
<p>hello <span [ngClass]="{'red': proportion !== '100', 'green': proportion === '100'}">{{username}}</span></p>
</code>```

Body:
I am new to Angular2 and was wondering how I go about setting a font color to an element depending on the value.

My scenario is: if the value of the input field is not 100 then I want it red but if it is 100 then I want it green.

I have the following code in place but cant get it working.

XXX.component.css

.red {
    color: red;
}

.green {
    color: green;
}

XXX.component.css

<input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion ">

hello {{proportion}}

Body:
Since you use Angular2, So you need to use [ngClass], and your input model is bind to proportion, So use it to compare,

Do it like :

<input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion">
<p>hello <span [ngClass]="{'red': proportion !== '100', 'green': proportion === '100'}">{{username}}</span></p>


答:
There are two solutions to change font color but depends on you requirement

If you requirement is change inline style then you can use angular NgStyle Directive which Update an HTML element styles for you..

NgStyle directive Ex:

```<code><span [ngStyle]="{'color': proportion === '100' ? 'green' : 'red'}"></span>

        ---------------------- OR -----------------------------------

<span [style.color]="proportion === '100' ? 'green' : 'red'"></span>
</code>```

If you requirement is change class then you can use angular NgClass Directive which Adds and removes CSS classes on an HTML element...

NgClass directive Ex:

```<code><span [ngClass]="{proportion === '100' ? 'green': 'red'}"></span>
</code>```

Title: Angular2 - Set A Different Color to an element Depending On Value

Body:
There are two solutions to change font color but depends on you requirement

If you requirement is change inline style then you can use angular NgStyle Directive which Update an HTML element styles for you..

NgStyle directive Ex:

<span [ngStyle]="{'color': proportion === '100' ? 'green' : 'red'}"></span>

        ---------------------- OR -----------------------------------

<span [style.color]="proportion === '100' ? 'green' : 'red'"></span>

If you requirement is change class then you can use angular NgClass Directive which Adds and removes CSS classes on an HTML element...

NgClass directive Ex:

<span [ngClass]="{proportion === '100' ? 'green': 'red'}"></span>


问:
Beginner Java: How to get it to display menu again after "Invalid selection"

How can I get it to display menu again after it displays "invalid selection"?

For now when a number < 1 or > 4 is entered, it just displays "Invalid selection."

Ideally I would want it to display

```<code>"Invalid selection
 /nMETER CONVERSION
1) Convert to Kilometers
2) Convert to Inches
3) Convert to Feet
4) Quit the Program
Please make a selection:"
</code>```

Here is my code

```<code>import java.util.Scanner;
import java.text.DecimalFormat;

public class Homework8bbb
{
//create main
public static void main(String[]args)
{//open main method
  int selection;
  double meters;

  Scanner keyboard = new Scanner(System.in);

  DecimalFormat format = new DecimalFormat("##.00");

   //call showMenu method
   //DISPLAY showMenu method
  do
  {
     showMenu();
   //get user [selection]
     selection = keyboard.nextInt();
  //validate selection
     do {
        if (selection < 1 || selection > 4)
        {
           System.out.print("Invalid selection\n");
           selection = keyboard.nextInt();
        }
     }while(selection < 1 || selection > 4);

   //get [meters]
     System.out.print("How many meters?\n");
     meters = keyboard.nextInt();
       //validate meters: do not allow negative meters
     while (meters < 0)
     {
        System.out.print("Invalid Selection. Please enter a positive number:\n");
        meters = keyboard.nextInt();
     }

     switch (selection)
     {
        case 1: calcKilometers(meters);
           break;
        case 2: calcInches(meters);
           break;
        case 3: calcFeet(meters);
           break;
        case 4:
           break; }
  }while(selection != 4);

 }

 public static void showMenu()
 {

  System.out.print("\n"
     + "METER CONVERSION\n"
     + " 1) Convert to Kilometers\n"
     + " 2) Convert to Inches\n"
     + " 3) Convert to Feet\n"
     + " 4) Quit the Program\n"
     + " Please make a selection:\n");
}

//calcKilometers method
public static double calcKilometers(double meters)
{

  double kilometers;
  kilometers = meters * 0.001;

  System.out.println(meters + " meters is " +
     kilometers + " kilometers.");
  return kilometers;
}

//calcInches method
public static double calcInches(double meters)
{
  double inches;
  inches = meters * 39.37;

  System.out.println(meters + " meters is " +
     inches + " inches.");
  return inches;
}

//calcFeet method
public static double calcFeet(double meters)
{
  double feet;
  feet = meters * 3.281;
  System.out.println(meters + " meters is " +
     feet + " feet.");

  return feet;
}

}//close class
</code>```

答:
You dont need this loop

```<code>   do {
            if (selection < 1 || selection > 4)
            {
                System.out.print("Invalid selection\n");
                continue;
            }
        }while(selection < 1 || selection > 4);
</code>```

replace it with this

```<code>  if (selection < 1 || selection > 4) {
            System.out.print("Invalid selection\n");
            continue;
     }
</code>```

if you enter if statment continue will take you to the start of the loop

Body:
How can I get it to display menu again after it displays "invalid selection"?

For now when a number < 1 or > 4 is entered, it just displays "Invalid selection."

Ideally I would want it to display

"Invalid selection
 /nMETER CONVERSION
1) Convert to Kilometers
2) Convert to Inches
3) Convert to Feet
4) Quit the Program
Please make a selection:"

Here is my code

import java.util.Scanner;
import java.text.DecimalFormat;

public class Homework8bbb
{
//create main
public static void main(String[]args)
{//open main method
  int selection;
  double meters;

  Scanner keyboard = new Scanner(System.in);

  DecimalFormat format = new DecimalFormat("##.00");

   //call showMenu method
   //DISPLAY showMenu method
  do
  {
     showMenu();
   //get user [selection]
     selection = keyboard.nextInt();
  //validate selection
     do {
        if (selection < 1 || selection > 4)
        {
           System.out.print("Invalid selection\n");
           selection = keyboard.nextInt();
        }
     }while(selection < 1 || selection > 4);

   //get [meters]
     System.out.print("How many meters?\n");
     meters = keyboard.nextInt();
       //validate meters: do not allow negative meters
     while (meters < 0)
     {
        System.out.print("Invalid Selection. Please enter a positive number:\n");
        meters = keyboard.nextInt();
     }

     switch (selection)
     {
        case 1: calcKilometers(meters);
           break;
        case 2: calcInches(meters);
           break;
        case 3: calcFeet(meters);
           break;
        case 4:
           break; }
  }while(selection != 4);

 }

 public static void showMenu()
 {

  System.out.print("\n"
     + "METER CONVERSION\n"
     + " 1) Convert to Kilometers\n"
     + " 2) Convert to Inches\n"
     + " 3) Convert to Feet\n"
     + " 4) Quit the Program\n"
     + " Please make a selection:\n");
}

//calcKilometers method
public static double calcKilometers(double meters)
{

  double kilometers;
  kilometers = meters * 0.001;

  System.out.println(meters + " meters is " +
     kilometers + " kilometers.");
  return kilometers;
}

//calcInches method
public static double calcInches(double meters)
{
  double inches;
  inches = meters * 39.37;

  System.out.println(meters + " meters is " +
     inches + " inches.");
  return inches;
}

//calcFeet method
public static double calcFeet(double meters)
{
  double feet;
  feet = meters * 3.281;
  System.out.println(meters + " meters is " +
     feet + " feet.");

  return feet;
}

}//close class

Body:
You dont need this loop

   do {
            if (selection < 1 || selection > 4)
            {
                System.out.print("Invalid selection\n");
                continue;
            }
        }while(selection < 1 || selection > 4);

replace it with this

  if (selection < 1 || selection > 4) {
            System.out.print("Invalid selection\n");
            continue;
     }

if you enter if statment continue will take you to the start of the loop


问:
Python dbus can't find org.(gnome|freedesktop).ScreenSaver
I'm trying to get python to interact with dbus and screensaver however it flatly refuses to do so no matter what. Perl seems to do alright with it but I write python, not perl (yet)

```<code>Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dbus
>>> bus = dbus.SystemBus()
>>> ofn = 'org.freedesktop.ScreenSaver'
>>> bus.get_object(ofn, "/org/freedesktop/ScreenSaver")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/dbus/bus.py", line 244, in get_object
    follow_name_owner_changes=follow_name_owner_changes)
  File "/usr/lib/pymodules/python2.6/dbus/proxies.py", line 241, in __init__
    self._named_service = conn.activate_name_owner(bus_name)
  File "/usr/lib/pymodules/python2.6/dbus/bus.py", line 183, in activate_name_owner
    self.start_service_by_name(bus_name)
  File "/usr/lib/pymodules/python2.6/dbus/bus.py", line 281, in start_service_by_name
    'su', (bus_name, flags)))
  File "/usr/lib/pymodules/python2.6/dbus/connection.py", line 620, in call_blocking
    message, timeout)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.ScreenSaver was not provided by any .service files
>>>
</code>```

Here's what I've seen in other places in perl:

```<code>my $cmd = "dbus-monitor --session \"type='signal',interface='org.gnome.ScreenSaver',member='SessionIdleChanged'\"";

open (IN, "$cmd |");

while (<IN>) {
if (m/^\s+boolean true/) {
  #print something
} elsif (m/^\s+boolean false/) {
  #print something else
}
}
</code>```

答:
```<code>In [36]: import dbus

In [37]: bus = dbus.SessionBus()

In [38]: bus.get_object('org.gnome.ScreenSaver','/org/gnome/ScreenSaver')
Out[38]: <ProxyObject wrapping <dbus._dbus.SessionBus (session) at 0xa41e38c> :1.24 /org/gnome/ScreenSaver at 0xa4a3b0c>
</code>```

Body:
I'm trying to get python to interact with dbus and screensaver however it flatly refuses to do so no matter what. Perl seems to do alright with it but I write python, not perl (yet)

Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dbus
>>> bus = dbus.SystemBus()
>>> ofn = 'org.freedesktop.ScreenSaver'
>>> bus.get_object(ofn, "/org/freedesktop/ScreenSaver")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/dbus/bus.py", line 244, in get_object
    follow_name_owner_changes=follow_name_owner_changes)
  File "/usr/lib/pymodules/python2.6/dbus/proxies.py", line 241, in __init__
    self._named_service = conn.activate_name_owner(bus_name)
  File "/usr/lib/pymodules/python2.6/dbus/bus.py", line 183, in activate_name_owner
    self.start_service_by_name(bus_name)
  File "/usr/lib/pymodules/python2.6/dbus/bus.py", line 281, in start_service_by_name
    'su', (bus_name, flags)))
  File "/usr/lib/pymodules/python2.6/dbus/connection.py", line 620, in call_blocking
    message, timeout)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.ScreenSaver was not provided by any .service files
>>>

Here's what I've seen in other places in perl:

my $cmd = "dbus-monitor --session \"type='signal',interface='org.gnome.ScreenSaver',member='SessionIdleChanged'\"";

open (IN, "$cmd |");

while (<IN>) {
if (m/^\s+boolean true/) {
  #print something
} elsif (m/^\s+boolean false/) {
  #print something else
}
}


问:
java.io.InvalidClassException: org.apache.spark.rpc.netty.RequestMessage
From my application, I am unable to connect to spark master because of the below error

Caused by: java.lang.RuntimeException: java.io.InvalidClassException:
  org.apache.spark.rpc.netty.RequestMessage; local class incompatible:
  stream classdesc serialVersionUID = -2221986757032131007, local class
  serialVersionUID = -5447855329526097695

I understand that there is a version compatibility issue, but unable to resolve it as it seems fine to me. Below is my version info

Application(Tomcat)  Java 7

Spark Installation   2.1.0

```<code>./spark-shell --version

Welcome to
         ____              __
        / __/__  ___ _____/ /__    _\ \/ _ \/ _ `/ __/  '_/   /___/ .__/\_,_/_/ /_/\_\   version 2.1.0
         /_/

Using Scala version 2.11.8, Java HotSpot(TM) 64-Bit Server VM, 1.8.0_91
</code>```

Maven Dependency

```<code>    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.10</artifactId>
    <version>2.1.0</version>
</code>```

Is it because my application is on Java 7 and Spark 2.1 runs on Java 8 ?

答:
This is related to class compatibility issue. For Spark 2.1.0, check version of Scala,Hadoop libraries(under jar folder). You need to keep same version with your app. If running via IDE(e.g. eclipse) then ctrl+shift+T and check if multiple version of spark-core are there.

This worked for me.

Body:
From my application, I am unable to connect to spark master because of the below error

Caused by: java.lang.RuntimeException: java.io.InvalidClassException:
  org.apache.spark.rpc.netty.RequestMessage; local class incompatible:
  stream classdesc serialVersionUID = -2221986757032131007, local class
  serialVersionUID = -5447855329526097695

I understand that there is a version compatibility issue, but unable to resolve it as it seems fine to me. Below is my version info

Application(Tomcat)  Java 7

Spark Installation   2.1.0

./spark-shell --version

Welcome to
         ____              __
        / __/__  ___ _____/ /__    _\ \/ _ \/ _ `/ __/  '_/   /___/ .__/\_,_/_/ /_/\_\   version 2.1.0
         /_/

Using Scala version 2.11.8, Java HotSpot(TM) 64-Bit Server VM, 1.8.0_91

Maven Dependency

    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.10</artifactId>
    <version>2.1.0</version>

Is it because my application is on Java 7 and Spark 2.1 runs on Java 8 ?


问:
Spring boot not logging CQL queries
I am using Spring Boot Data Cassandra in my spring boot project, I am trying to log CQL queries but setting spring.jpa.show-sql to true is not working.
here is my application.properties

```<code>spring.data.cassandra.keyspace-name=sample
spring.data.cassandra.contact-points=127.0.0.1
spring.data.cassandra.port=9042
spring.data.cassandra.schema-action=CREATE_IF_NOT_EXISTS
spring.jpa.show-sql=true
</code>```

答:
It's possible using a LatencyTracker</p>

```<code>@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    public Application(Cluster cluster) {
        this.cluster = cluster;
    }

    @Override
    public void run(String... strings) throws Exception {

    cluster.register(new LatencyTracker() {
                @Override
                public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
                    System.out.println(statement);
                }

                @Override
                public void onRegister(Cluster cluster) {

                }

                @Override
                public void onUnregister(Cluster cluster) {

                }
            });
    }

}
</code>```

Title: Spring boot not logging CQL queries

Body:
I am using Spring Boot Data Cassandra in my spring boot project, I am trying to log CQL queries but setting spring.jpa.show-sql to true is not working.
here is my application.properties

spring.data.cassandra.keyspace-name=sample
spring.data.cassandra.contact-points=127.0.0.1
spring.data.cassandra.port=9042
spring.data.cassandra.schema-action=CREATE_IF_NOT_EXISTS
spring.jpa.show-sql=true

Body:
It's possible using a LatencyTracker

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    public Application(Cluster cluster) {
        this.cluster = cluster;
    }

    @Override
    public void run(String... strings) throws Exception {

    cluster.register(new LatencyTracker() {
                @Override
                public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
                    System.out.println(statement);
                }

                @Override
                public void onRegister(Cluster cluster) {

                }

                @Override
                public void onUnregister(Cluster cluster) {

                }
            });
    }

}


问:
How to convert comma separated string values into a List<string> using asp.net mvc5
want to convert comma separated string values into a List

have tried

```<code>public List<string> GetColumnNamesByReportname(string Reportname)
{
    using (var Context = new MCPEntities())
    {
        var ColumnNames = Context.Reports.Where(c => c.ReportName == Reportname).Select(c => c.ColumnNames).ToList();
        return ColumnNames;
    }
}
</code>```

答:
Try this...    </p>

```<code> public static void Main(string[] args)
            {
                //Your code goes here
                string a="a,b,c,d";

              List<string> abc=a.Split(',').ToList();
                foreach(var item in abc){
                    Console.WriteLine(item);}
            }
</code>```

Body:
want to convert comma separated string values into a List

have tried

public List<string> GetColumnNamesByReportname(string Reportname)
{
    using (var Context = new MCPEntities())
    {
        var ColumnNames = Context.Reports.Where(c => c.ReportName == Reportname).Select(c => c.ColumnNames).ToList();
        return ColumnNames;
    }
}

Body:
Try this...

 public static void Main(string[] args)
            {
                //Your code goes here
                string a="a,b,c,d";

              List<string> abc=a.Split(',').ToList();
                foreach(var item in abc){
                    Console.WriteLine(item);}
            }


问:
Starting word of the sentence not printed using c programming language
when I am trying to concatenate a word and a sentence the first word of the sentence automatically deleted, what improvement should I use.. my code is: enter code here`     </p>

```<code>char word[]="AddMe";
char adder[150];
// reading string from stdin
scanf("%[^\n]*c",%sentence);
strcat(adder,word);
strcat(adder,sentence);
puts(adder);
</code>```

答:
First, use:</p>

```<code>strcpy(adder,word);
</code>```

Body:
when I am trying to concatenate a word and a sentence the first word of the sentence automatically deleted, what improvement should I use.. my code is: enter code here`

char word[]="AddMe";
char adder[150];
// reading string from stdin
scanf("%[^\n]*c",%sentence);
strcat(adder,word);
strcat(adder,sentence);
puts(adder);

Body:
First, use:

strcpy(adder,word);


问:
How can I measure the duration of a package execution?
I have an SSIS job that I would like to run from a procedure, and then, using the job start and job end date execute a select statement.

Getting the job start time is easy- just save the current time from just before you call the job.

How can I get the end tim? Can I use @endTime = GETDATE()? Does starting the job wait for it to end ?

Is it true in general about calls inside SQL procedures?

EDIT:
As people asked, I wanted to call an SSIS job using this code, which I found here:

```<code> declare @execution_id bigint
 exec ssisdb.catalog.create_execution
 @folder_name = 'mssqltips'
 ,@project_name = 'exec-ssis-stored-proc-ssis-sample'
 ,@package_name = 'Sample.dtsx'
 ,@execution_id = @execution_id output
 exec ssisdb.catalog.start_execution @execution_id
</code>```

答:
SSIS already logs package execution durations and events, including step durations. You don't need to use GETDATE().

You can query the catalog.executions view of the SSISDB database to retrieve the execution status, start time and end time, eg:

```<code>select status, start_time, end_time,datediff(s,start_time,end_time) as duration
from catalog.executions
where execution_id = @execution_id
</code>```

Or

```<code>select status, start_time, end_time, datediff(s,start_time,end_time) duration
from catalog.executions
where project_name = 'exec-ssis-stored-proc-ssis-sample'
      and  package_name = 'Sample.dtsx'
order by execution_id
</code>```

for historical data

Body:
I have an SSIS job that I would like to run from a procedure, and then, using the job start and job end date execute a select statement.

Getting the job start time is easy- just save the current time from just before you call the job.

How can I get the end tim? Can I use @endTime = GETDATE()? Does starting the job wait for it to end ?

Is it true in general about calls inside SQL procedures?

EDIT:
As people asked, I wanted to call an SSIS job using this code, which I found here:

 declare @execution_id bigint
 exec ssisdb.catalog.create_execution
 @folder_name = 'mssqltips'
 ,@project_name = 'exec-ssis-stored-proc-ssis-sample'
 ,@package_name = 'Sample.dtsx'
 ,@execution_id = @execution_id output
 exec ssisdb.catalog.start_execution @execution_id

Body:
SSIS already logs package execution durations and events, including step durations. You don't need to use GETDATE().

You can query the catalog.executions view of the SSISDB database to retrieve the execution status, start time and end time, eg:

select status, start_time, end_time,datediff(s,start_time,end_time) as duration
from catalog.executions
where execution_id = @execution_id

Or

select status, start_time, end_time, datediff(s,start_time,end_time) duration
from catalog.executions
where project_name = 'exec-ssis-stored-proc-ssis-sample'
      and  package_name = 'Sample.dtsx'
order by execution_id

for historical data


问:
Post XML "Root Element Is Missing"
I keep getting the infamous 'Root element is missing' error when Posting XML data.  It sometimes works, but most times throws the error.

C# Code:

```<code> public string postXMLData(string destinationUrl, string requestXml)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
            byte[] bytes;
            bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
            request.ContentType = "text/xml; encoding='utf-8'";
            request.ContentLength = bytes.Length;
            request.Method = "POST";
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream responseStream = response.GetResponseStream();
                string responseStr = new StreamReader(responseStream).ReadToEnd();
                return responseStr;
            }
            return "";
        }
</code>```

XML Data:

```<code><Person>
    <idPeople>0</idPeople>
    <AccountNumber>TEST02H</AccountNumber>
    <cFirstName>TEST 2</cFirstName>
    <cLastName>TEST 2</cLastName>
    <cTelWork/>
    <cTelMobile>0713473835</cTelMobile>
    <cEmail>myemail@mydomain.com</cEmail>
    <ubPPLIsActive>true</ubPPLIsActive>
    <ubPPLSMSOptIn>true</ubPPLSMSOptIn>
    <udPPLSMSOptInActivateDate>30/05/2017</udPPLSMSOptInActivateDate>
    <ulPPLAccessType>Administrator</ulPPLAccessType>
    <ubPPLNewsletterSignUp>true</ubPPLNewsletterSignUp>
    <ubPPLIncludeBuyerEmails>true</ubPPLIncludeBuyerEmails>
</Person>
</code>```

答:
The issue for me was in 2 places.

The application I am posting to had an error, which I resolved. I found this error by pasting the destination URL into my browser to see what happens.

I needed to System.Web.HttpUtility.UrlEncode the XML.

I used this method for posting in the end.

```<code>WebClient client = new WebClient();
string xmlResult = client.DownloadString(_workContext.AccountingWebServiceLink + "?action=updatesecondary&xml=" + System.Web.HttpUtility.UrlEncode(strXML));
</code>```

Title: Post XML "Root Element Is Missing"

Body:
I keep getting the infamous 'Root element is missing' error when Posting XML data.  It sometimes works, but most times throws the error.

C# Code:

 public string postXMLData(string destinationUrl, string requestXml)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
            byte[] bytes;
            bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
            request.ContentType = "text/xml; encoding='utf-8'";
            request.ContentLength = bytes.Length;
            request.Method = "POST";
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream responseStream = response.GetResponseStream();
                string responseStr = new StreamReader(responseStream).ReadToEnd();
                return responseStr;
            }
            return "";
        }

XML Data:

<Person>
    <idPeople>0</idPeople>
    <AccountNumber>TEST02H</AccountNumber>
    <cFirstName>TEST 2</cFirstName>
    <cLastName>TEST 2</cLastName>
    <cTelWork/>
    <cTelMobile>0713473835</cTelMobile>
    <cEmail>myemail@mydomain.com</cEmail>
    <ubPPLIsActive>true</ubPPLIsActive>
    <ubPPLSMSOptIn>true</ubPPLSMSOptIn>
    <udPPLSMSOptInActivateDate>30/05/2017</udPPLSMSOptInActivateDate>
    <ulPPLAccessType>Administrator</ulPPLAccessType>
    <ubPPLNewsletterSignUp>true</ubPPLNewsletterSignUp>
    <ubPPLIncludeBuyerEmails>true</ubPPLIncludeBuyerEmails>
</Person>

Body:
The issue for me was in 2 places.

The application I am posting to had an error, which I resolved. I found this error by pasting the destination URL into my browser to see what happens.

I needed to System.Web.HttpUtility.UrlEncode the XML.

I used this method for posting in the end.

WebClient client = new WebClient();
string xmlResult = client.DownloadString(_workContext.AccountingWebServiceLink + "?action=updatesecondary&xml=" + System.Web.HttpUtility.UrlEncode(strXML));


问:
Need to lookup 2 columns in VBA Function
I need to use to lookup columns in from another sheet and return in a single cell VBA. My Data in Sheet1 is,

```<code>P.No.  REV   Qty
2918   01    50
2918   02    44
2919   01    72
</code>```

In Sheet2, It should return the Qty, by looking both the P.No. and REV columns. Kindly help me on this.

My code to lookup one column is below. In this I need to lookup two columns.

```<code>Function SingleCellExtractInward(lookupvalue As String, lookuprange As Range, ColumnNumber As Integer)
    Dim i As Double
    Dim Result1 As String
    Dim Result2 As String

    If Result2 = Empty Then
        Result2 = "no recent inward"
        SingleCellExtractInward = Result2
    End If

    For i = 1 To lookuprange.Columns(1).Cells.Count
        If lookuprange.Cells(i, 1) = lookupvalue Then
            Result1 = Result1 & " " & lookuprange.Cells(i, ColumnNumber) & ","
            SingleCellExtractInward = Left(Result1, Len(Result1) - 1)
        End If
    Next i
End Function
</code>```

答:
Therefore you just need to extend your function by a second lookupvalue, so we have lookupValueA and lookupValueB:

```<code>Function SingleCellExtractInward(lookupValueA As String, lookupValueB As String, _
                                 lookupRange As Range, ColumnNumber As Long)
</code>```

Note that I changed Integer to Long. Always use Long instead of Integer unless you need to communicate with old APIs (see explanation here).

You need to check if both criteria are met:

```<code>If lookupRange.Cells(i, 1).Value = lookupValueA And _
   lookupRange.Cells(i, 2).Value = lookupValueB Then
</code>```

Alternative: If you want to be able to additionally look only for one criteria A or B if the other one is empty then instead use:

```<code>If (lookupRange.Cells(i, 1).Value = lookupValueA Or lookupValueA = vbNullString) And _
   (lookupRange.Cells(i, 2).Value = lookupValueB Or lookupValueB = vbNullString) Then
</code>```

In this case you can leave one of the lookupValue a vbNullString (same as "") and it only looks up one criteria (like your original function).

The following is just improvement and removing unnecessary code that I recommend:

i should be Long not Double:

```<code>Dim i As Long
</code>```

If Result2 = Empty Then is always true at this point. So we don't even need Result2.

The following …

```<code>Dim Result2 As String

If Result2 = Empty Then
    Result2 = "no recent inward"
    SingleCellExtractInward = Result2
End If
</code>```

Can be reduced to one line …

```<code>SingleCellExtractInward = "no recent inward"   'Default return value if nothing matches.
</code>```

So we would end up with something like that:

```<code>Option Explicit

Function SingleCellExtractInward(lookupValueA As String, lookupValueB As String, _
                                 lookupRange As Range, ColumnNumber As Long)
    Dim i As Long
    Dim Result As String

    SingleCellExtractInward = "no recent inward"

    For i = 1 To lookupRange.Columns(1).Cells.Count
        If (lookupRange.Cells(i, 1).Value = lookupValueA Or lookupValueA = vbNullString) And _
           (lookupRange.Cells(i, 2).Value = lookupValueB Or lookupValueB = vbNullString) Then
            Result = Result & " " & lookupRange.Cells(i, ColumnNumber) & ","
            SingleCellExtractInward = Left(Result, Len(Result) - 1)
        End If
    Next i
End Function
</code>```

Body:
I need to use to lookup columns in from another sheet and return in a single cell VBA. My Data in Sheet1 is,

P.No.  REV   Qty
2918   01    50
2918   02    44
2919   01    72

In Sheet2, It should return the Qty, by looking both the P.No. and REV columns. Kindly help me on this.

My code to lookup one column is below. In this I need to lookup two columns.

Function SingleCellExtractInward(lookupvalue As String, lookuprange As Range, ColumnNumber As Integer)
    Dim i As Double
    Dim Result1 As String
    Dim Result2 As String

    If Result2 = Empty Then
        Result2 = "no recent inward"
        SingleCellExtractInward = Result2
    End If

    For i = 1 To lookuprange.Columns(1).Cells.Count
        If lookuprange.Cells(i, 1) = lookupvalue Then
            Result1 = Result1 & " " & lookuprange.Cells(i, ColumnNumber) & ","
            SingleCellExtractInward = Left(Result1, Len(Result1) - 1)
        End If
    Next i
End Function

Body:
Therefore you just need to extend your function by a second lookupvalue, so we have lookupValueA and lookupValueB:

Function SingleCellExtractInward(lookupValueA As String, lookupValueB As String, _
                                 lookupRange As Range, ColumnNumber As Long)

Note that I changed Integer to Long. Always use Long instead of Integer unless you need to communicate with old APIs (see explanation here).

You need to check if both criteria are met:

If lookupRange.Cells(i, 1).Value = lookupValueA And _
   lookupRange.Cells(i, 2).Value = lookupValueB Then

Alternative: If you want to be able to additionally look only for one criteria A or B if the other one is empty then instead use:

If (lookupRange.Cells(i, 1).Value = lookupValueA Or lookupValueA = vbNullString) And _
   (lookupRange.Cells(i, 2).Value = lookupValueB Or lookupValueB = vbNullString) Then

In this case you can leave one of the lookupValue a vbNullString (same as "") and it only looks up one criteria (like your original function).

The following is just improvement and removing unnecessary code that I recommend:

i should be Long not Double:

Dim i As Long

If Result2 = Empty Then is always true at this point. So we don't even need Result2.

The following …

Dim Result2 As String

If Result2 = Empty Then
    Result2 = "no recent inward"
    SingleCellExtractInward = Result2
End If

Can be reduced to one line …

SingleCellExtractInward = "no recent inward"   'Default return value if nothing matches.

So we would end up with something like that:

Option Explicit

Function SingleCellExtractInward(lookupValueA As String, lookupValueB As String, _
                                 lookupRange As Range, ColumnNumber As Long)
    Dim i As Long
    Dim Result As String

    SingleCellExtractInward = "no recent inward"

    For i = 1 To lookupRange.Columns(1).Cells.Count
        If (lookupRange.Cells(i, 1).Value = lookupValueA Or lookupValueA = vbNullString) And _
           (lookupRange.Cells(i, 2).Value = lookupValueB Or lookupValueB = vbNullString) Then
            Result = Result & " " & lookupRange.Cells(i, ColumnNumber) & ","
            SingleCellExtractInward = Left(Result, Len(Result) - 1)
        End If
    Next i
End Function


问:
Unity3d, Focus Cam in a rect using project matrix.
So i'm working on this project, that require my camera to view and only view a rect area. So no matter how the camera moves, user can never see outside of the box. I attached this image below to explain my words.

I went through the Unity Camera API but didn't find anything useful, any suggestions would be appreciated.

Edit:
Turns out focus camera in a rect using projection matrix is a physically more accurate way of doing so, but i can't figure out how.

答:
Thanks to Samy Bencherif for providing the Resource.

The code here have a similar feature that should do the job, I will do more digging into it and post a more complete solution once I got time.

http://wiki.unity3d.com/index.php/MirrorReflection4

Edit

I found my solution here. By hpJohn in Unity Forum:

```<code>public Transform[] Corners;
public Transform lookTarget;
public bool drawNearCone, drawFrustum;

Camera theCam;

void Start () {
    theCam = camera;
}

void Update () {
    Vector3 pa, pb, pc, pd;
    pa = Corners[0].position; //Bottom-Left
    pb = Corners[1].position; //Bottom-Right
    pc = Corners[2].position; //Top-Left
    pd = Corners[3].position; //Top-Right

    Vector3 pe = theCam.transform.position;// eye position

    Vector3 vr = ( pb - pa ).normalized; // right axis of screen
    Vector3 vu = ( pc - pa ).normalized; // up axis of screen
    Vector3 vn = Vector3.Cross( vr, vu ).normalized; // normal vector of screen

    Vector3 va = pa - pe; // from pe to pa
    Vector3 vb = pb - pe; // from pe to pb
    Vector3 vc = pc - pe; // from pe to pc
    Vector3 vd = pd - pe; // from pe to pd

    float n = -lookTarget.InverseTransformPoint( theCam.transform.position ).z; // distance to the near clip plane (screen)
    float f = theCam.farClipPlane; // distance of far clipping plane
    float d = Vector3.Dot( va, vn ); // distance from eye to screen
    float l = Vector3.Dot( vr, va ) * n / d; // distance to left screen edge from the 'center'
    float r = Vector3.Dot( vr, vb ) * n / d; // distance to right screen edge from 'center'
    float b = Vector3.Dot( vu, va ) * n / d; // distance to bottom screen edge from 'center'
    float t = Vector3.Dot( vu, vc ) * n / d; // distance to top screen edge from 'center'

    Matrix4x4 p = new Matrix4x4(); // Projection matrix
    p[0, 0] = 2.0f * n / ( r - l );
    p[0, 2] = ( r + l ) / ( r - l );
    p[1, 1] = 2.0f * n / ( t - b );
    p[1, 2] = ( t + b ) / ( t - b );
    p[2, 2] = ( f + n ) / ( n - f );
    p[2, 3] = 2.0f * f * n / ( n - f );
    p[3, 2] = -1.0f;

    theCam.projectionMatrix = p; // Assign matrix to camera

    if ( drawNearCone ) { //Draw lines from the camera to the corners f the screen
        Debug.DrawRay( theCam.transform.position, va, Color.blue );
        Debug.DrawRay( theCam.transform.position, vb, Color.blue );
        Debug.DrawRay( theCam.transform.position, vc, Color.blue );
        Debug.DrawRay( theCam.transform.position, vd, Color.blue );
    }

    if ( drawFrustum ) DrawFrustum( theCam ); //Draw actual camera frustum

}

Vector3 ThreePlaneIntersection ( Plane p1, Plane p2, Plane p3 ) { //get the intersection point of 3 planes
    return ( ( -p1.distance * Vector3.Cross( p2.normal, p3.normal ) ) +
            ( -p2.distance * Vector3.Cross( p3.normal, p1.normal ) ) +
            ( -p3.distance * Vector3.Cross( p1.normal, p2.normal ) ) ) /
        ( Vector3.Dot( p1.normal, Vector3.Cross( p2.normal, p3.normal ) ) );
}

void DrawFrustum ( Camera cam ) {
    Vector3[] nearCorners = new Vector3[4]; //Approx'd nearplane corners
    Vector3[] farCorners = new Vector3[4]; //Approx'd farplane corners
    Plane[] camPlanes = GeometryUtility.CalculateFrustumPlanes( cam ); //get planes from matrix
    Plane temp = camPlanes[1]; camPlanes[1] = camPlanes[2]; camPlanes[2] = temp; //swap [1] and [2] so the order is better for the loop

    for ( int i = 0; i < 4; i++ ) {
        nearCorners[i] = ThreePlaneIntersection( camPlanes[4], camPlanes[i], camPlanes[( i + 1 ) % 4] ); //near corners on the created projection matrix
        farCorners[i] = ThreePlaneIntersection( camPlanes[5], camPlanes[i], camPlanes[( i + 1 ) % 4] ); //far corners on the created projection matrix
    }

    for ( int i = 0; i < 4; i++ ) {
        Debug.DrawLine( nearCorners[i], nearCorners[( i + 1 ) % 4], Color.red, Time.deltaTime, false ); //near corners on the created projection matrix
        Debug.DrawLine( farCorners[i], farCorners[( i + 1 ) % 4], Color.red, Time.deltaTime, false ); //far corners on the created projection matrix
        Debug.DrawLine( nearCorners[i], farCorners[i], Color.red, Time.deltaTime, false ); //sides of the created projection matrix
    }
}
</code>```

Body:
Thanks to Samy Bencherif for providing the Resource.

The code here have a similar feature that should do the job, I will do more digging into it and post a more complete solution once I got time.

http://wiki.unity3d.com/index.php/MirrorReflection4

Edit

I found my solution here. By hpJohn in Unity Forum:

public Transform[] Corners;
public Transform lookTarget;
public bool drawNearCone, drawFrustum;

Camera theCam;

void Start () {
    theCam = camera;
}

void Update () {
    Vector3 pa, pb, pc, pd;
    pa = Corners[0].position; //Bottom-Left
    pb = Corners[1].position; //Bottom-Right
    pc = Corners[2].position; //Top-Left
    pd = Corners[3].position; //Top-Right

    Vector3 pe = theCam.transform.position;// eye position

    Vector3 vr = ( pb - pa ).normalized; // right axis of screen
    Vector3 vu = ( pc - pa ).normalized; // up axis of screen
    Vector3 vn = Vector3.Cross( vr, vu ).normalized; // normal vector of screen

    Vector3 va = pa - pe; // from pe to pa
    Vector3 vb = pb - pe; // from pe to pb
    Vector3 vc = pc - pe; // from pe to pc
    Vector3 vd = pd - pe; // from pe to pd

    float n = -lookTarget.InverseTransformPoint( theCam.transform.position ).z; // distance to the near clip plane (screen)
    float f = theCam.farClipPlane; // distance of far clipping plane
    float d = Vector3.Dot( va, vn ); // distance from eye to screen
    float l = Vector3.Dot( vr, va ) * n / d; // distance to left screen edge from the 'center'
    float r = Vector3.Dot( vr, vb ) * n / d; // distance to right screen edge from 'center'
    float b = Vector3.Dot( vu, va ) * n / d; // distance to bottom screen edge from 'center'
    float t = Vector3.Dot( vu, vc ) * n / d; // distance to top screen edge from 'center'

    Matrix4x4 p = new Matrix4x4(); // Projection matrix
    p[0, 0] = 2.0f * n / ( r - l );
    p[0, 2] = ( r + l ) / ( r - l );
    p[1, 1] = 2.0f * n / ( t - b );
    p[1, 2] = ( t + b ) / ( t - b );
    p[2, 2] = ( f + n ) / ( n - f );
    p[2, 3] = 2.0f * f * n / ( n - f );
    p[3, 2] = -1.0f;

    theCam.projectionMatrix = p; // Assign matrix to camera

    if ( drawNearCone ) { //Draw lines from the camera to the corners f the screen
        Debug.DrawRay( theCam.transform.position, va, Color.blue );
        Debug.DrawRay( theCam.transform.position, vb, Color.blue );
        Debug.DrawRay( theCam.transform.position, vc, Color.blue );
        Debug.DrawRay( theCam.transform.position, vd, Color.blue );
    }

    if ( drawFrustum ) DrawFrustum( theCam ); //Draw actual camera frustum

}

Vector3 ThreePlaneIntersection ( Plane p1, Plane p2, Plane p3 ) { //get the intersection point of 3 planes
    return ( ( -p1.distance * Vector3.Cross( p2.normal, p3.normal ) ) +
            ( -p2.distance * Vector3.Cross( p3.normal, p1.normal ) ) +
            ( -p3.distance * Vector3.Cross( p1.normal, p2.normal ) ) ) /
        ( Vector3.Dot( p1.normal, Vector3.Cross( p2.normal, p3.normal ) ) );
}

void DrawFrustum ( Camera cam ) {
    Vector3[] nearCorners = new Vector3[4]; //Approx'd nearplane corners
    Vector3[] farCorners = new Vector3[4]; //Approx'd farplane corners
    Plane[] camPlanes = GeometryUtility.CalculateFrustumPlanes( cam ); //get planes from matrix
    Plane temp = camPlanes[1]; camPlanes[1] = camPlanes[2]; camPlanes[2] = temp; //swap [1] and [2] so the order is better for the loop

    for ( int i = 0; i < 4; i++ ) {
        nearCorners[i] = ThreePlaneIntersection( camPlanes[4], camPlanes[i], camPlanes[( i + 1 ) % 4] ); //near corners on the created projection matrix
        farCorners[i] = ThreePlaneIntersection( camPlanes[5], camPlanes[i], camPlanes[( i + 1 ) % 4] ); //far corners on the created projection matrix
    }

    for ( int i = 0; i < 4; i++ ) {
        Debug.DrawLine( nearCorners[i], nearCorners[( i + 1 ) % 4], Color.red, Time.deltaTime, false ); //near corners on the created projection matrix
        Debug.DrawLine( farCorners[i], farCorners[( i + 1 ) % 4], Color.red, Time.deltaTime, false ); //far corners on the created projection matrix
        Debug.DrawLine( nearCorners[i], farCorners[i], Color.red, Time.deltaTime, false ); //sides of the created projection matrix
    }
}


问:
General suggestions for debugging in R
I get an error when using an R function that I wrote:

```<code>Warning messages:
1: glm.fit: algorithm did not converge
2: glm.fit: algorithm did not converge
</code>```

What I have done:

Step through the function

Adding print to find out at what line the error occurs suggests two functions that should not use glm.fit.  They are window() and save().

My general approaches include adding print and stop commands, and stepping through a function line by line until I can locate the exception.

However, it is not clear to me using those techniques where this error comes from in the code. I am not even certain which functions within the code depend on glm.fit.  How do I go about diagnosing this problem?

答:
My general strategy looks like:

Run traceback() to see look for obvious issues

Set options(warn=2) to treat warnings like errors

Set options(error=recover) to step into the call stack on error

Title: General suggestions for debugging in R

Body:
I get an error when using an R function that I wrote:

Warning messages:
1: glm.fit: algorithm did not converge
2: glm.fit: algorithm did not converge

What I have done:

Step through the function

Adding print to find out at what line the error occurs suggests two functions that should not use glm.fit.  They are window() and save().

My general approaches include adding print and stop commands, and stepping through a function line by line until I can locate the exception.

However, it is not clear to me using those techniques where this error comes from in the code. I am not even certain which functions within the code depend on glm.fit.  How do I go about diagnosing this problem?


问:
AJAX Contact form doesn't work correctly
I have a form:

```<code><form id="main-contact-form" name="contact-form" action="sendemail.php" method="post">
    <div class="form-group">
        <input type="text" name="name" class="form-control" required="required" placeholder="Name">
    </div>
    <div class="form-group">
        <input type="email" name="email" class="form-control" required="required" placeholder="Email">
    </div>
    <div class="form-group">
        <textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>
    </div>
    <div class="form-group">
        <input type="submit" name="submit" class="btn btn-submit" value="Send">
    </div>
</form>
</code>```

sendememail.php is:

```<code><?php

$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);

$to = "email@email.com";
$sub = "New message from site";

$message = "New message\n
Name: $name
Email: $email";

$from  = "From: $name <$name> \r\n";

mail($to, $sub, $message, $from);
return;

?>
</code>```

javascript is:

```<code>var form = $('#main-contact-form');
form.submit(function(event){
    event.preventDefault();
    var form_status = $('<div class="form_status"></div>');
    $.ajax({
        url: $(this).attr('action'),
        beforeSend: function(){
            form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Sending...</p>').fadeIn() );
        }
    }).done(function(data){
        form_status.html('<p class="text-success">Thanks for you message!</p>').delay(3000).fadeOut();
    });
});
</code>```

The problem: it sends a message to email, but without input fields. Their value are empty. I tried to do that without JS, and it's sending every field correctly.

答:
You can use another type of form submit using jQuery ajax</p>

```<code><script>
    $('#main-contact-form').submit(function(event){
    event.preventDefault();
    $.ajax({
        type:'post',
        url:'sendememail.php',
        data:$(this).serialize(),
        success:function(response){
            if(response==1)
            {

                setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-success">Review Successfully Submitted......</div></center></h5>');},5);

            }
            else
            {

                setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-danger">Sorry Your Review Was Not Submitted......</div></center></h5>');},5);

            }
        }

    });
});
</script>
</code>```

Body:
I have a form:

<form id="main-contact-form" name="contact-form" action="sendemail.php" method="post">

        <input type="text" name="name" class="form-control" required="required" placeholder="Name">

        <input type="email" name="email" class="form-control" required="required" placeholder="Email">

        <textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>

        <input type="submit" name="submit" class="btn btn-submit" value="Send">

</form>

sendememail.php is:

<?php

$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);

$to = "email@email.com";
$sub = "New message from site";

$message = "New message\n
Name: $name
Email: $email";

$from  = "From: $name <$name> \r\n";

mail($to, $sub, $message, $from);
return;

?>

javascript is:

var form = $('#main-contact-form');
form.submit(function(event){
    event.preventDefault();
    var form_status = $('

');
    $.ajax({
        url: $(this).attr('action'),
        beforeSend: function(){
            form.prepend( form_status.html('
 Sending...
').fadeIn() );
        }
    }).done(function(data){
        form_status.html('
Thanks for you message!
').delay(3000).fadeOut();
    });
});

The problem: it sends a message to email, but without input fields. Their value are empty. I tried to do that without JS, and it's sending every field correctly.

Body:
You can use another type of form submit using jQuery ajax

<script>
    $('#main-contact-form').submit(function(event){
    event.preventDefault();
    $.ajax({
        type:'post',
        url:'sendememail.php',
        data:$(this).serialize(),
        success:function(response){
            if(response==1)
            {

                setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-success">Review Successfully Submitted......</div></center></h5>');},5);

            }
            else
            {

                setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-danger">Sorry Your Review Was Not Submitted......</div></center></h5>');},5);

            }
        }

    });
});
</script>


问:
LinearLayout only show first item
I got problem with LinearLayout, it only shows the first child. I found a solution but i not work.

Here my xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.hoangdang.diemdanh.QRCode.QRCodeActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/qrcode_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/primary_darker"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:orientation="horizontal">

        <android.support.v7.widget.AppCompatImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/qrCode_imageView"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/generate_code_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/generate_code"
            android:layout_marginRight="@dimen/de_btn_padding"
            android:layout_marginLeft="@dimen/de_btn_padding"/>

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

here is the result when i change position of Button and ImageView

and

答:
I think you have to set orientation vertical to linear layout like below</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.hoangdang.diemdanh.QRCode.QRCodeActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/qrcode_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/primary_darker"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:orientation="vertical">

        <android.support.v7.widget.AppCompatImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/qrCode_imageView"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/generate_code_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/generate_code"
            android:layout_marginRight="@dimen/de_btn_padding"
            android:layout_marginLeft="@dimen/de_btn_padding"/>

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

Title: LinearLayout only show first item

Body:
I got problem with LinearLayout, it only shows the first child. I found a solution but i not work.

Here my xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.hoangdang.diemdanh.QRCode.QRCodeActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/qrcode_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/primary_darker"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:orientation="horizontal">

        <android.support.v7.widget.AppCompatImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/qrCode_imageView"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/generate_code_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/generate_code"
            android:layout_marginRight="@dimen/de_btn_padding"
            android:layout_marginLeft="@dimen/de_btn_padding"/>

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

here is the result when i change position of Button and ImageView

and

Body:
I think you have to set orientation vertical to linear layout like below

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.hoangdang.diemdanh.QRCode.QRCodeActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/qrcode_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/primary_darker"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:orientation="vertical">

        <android.support.v7.widget.AppCompatImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/qrCode_imageView"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/generate_code_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/generate_code"
            android:layout_marginRight="@dimen/de_btn_padding"
            android:layout_marginLeft="@dimen/de_btn_padding"/>

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>