Q: Stopping BackgroundWorker which is searching in database i wrote a code in c# which takes search criteria from user and search in database table and i done this with the help of background worker
now while execution if i want to forcefully stop the thread.
because if user gets the result and he dont want the search to be performed anymore
btnStop_Click(object sender, EventArgs e)
{
           backgroundWorkerSearch.CancelAsync();
}

on dowork()
if (backgroundWorkerSearch.CancellationPending)
 {
     e.Cancel = true;
     return;
 }

above code doesn't work

A: Cancellation pending does only tell the DoWork method that the starting thread want's it to abort. It does not automatically stop anything. See this example of a DoWork method:
private void DoWork(object sender, DoWorkEventArgs e){
  foreach( ... )
  {
    //do some work
    if( myBackgroundWorker.CancellationPending )
    {
      return;
    }
  }
}

The other possibility (your case is like this )
private void DoWork(object sender, DoWorkEventArgs e){
  //perform a big task towards the database here
}

That last case does not give you any entry point to check for cancellation requests, so the ony option is to locate the thread and kill it without giving it the chance to shut down in a good manner, and is not a recommended pattern.
Your best bet is to divide the work inside DoWork in several batches, and check for cancellation requests between each of the sub tasks.


Q: Custom Live Agent Chat Window on an external website I want to know if it's possible to customize Live Agent Chat Window using visualforce, and it's to be deployed to an external website using the deployment code snippet.
At the current stage, I have deployed the code, and it's working fine using the default live agent chat window, but if I set it to my customized chat window, it give an error about refused to connect.

A: Update.
Problem fixed, I just needs to set the public access method of the force.com site that is hosting the chat window to same origin and external domain.


Q: Symfony user login link in chain user providers I am creating PasswordLess api for my symfony project by following this: https://symfony.com/doc/5.4/security/login_link.html
I have multiple firewalls:
firewalls:
        dev:
            pattern:                        ^/(_(profiler|wdt)|css|images|js)/
            security:                       false

        install:
            pattern:                        ^/installer
            security:                       false
            anonymous:                      true

        login:
            pattern:                        ^/user/(login|reset-request|send-email|check-email|auto-login)$
            provider:                       chain_provider
            anonymous:                      true
            #login_link:                    # ERROR HERE
            #    check_route: login_check
            #    signature_properties: ['id']

        main:
            pattern:                        ^/
            provider:                       chain_provider
            form_login:
                csrf_token_generator:       security.csrf.token_manager
                check_path:                 main_security_check
                login_path:                 main_security_login
                use_forward:                true
            logout:
                path:                       main_security_logout
            remember_me:
                secret:                     "%env(APP_SECRET)%"
                name:                       BAPRM
                lifetime:                   1209600   # stay logged for two weeks
                samesite:                   'lax'
            anonymous:                      false

But when I try to configure it I get this error:
The old authentication system is not supported with login_link.

How can I make it work, what I am missing here.
I am using Symfony 5.4
Thanks.

A: As mentionned in the documentation you have to enable the new authenticator system to use login links.

Login links are only supported by Symfony when using the authenticator system. Before using this authenticator, make sure you have enabled it with enable_authenticator_manager: true in your security.yaml file.

So modify your security.yaml to add:
enable_authenticator_manager: true
If you do not use it, for example if you use guards, you will have to replace it with the new system.


Q: how to shade the intersection of 3 lines I was trying to shade the intersection of the following 3 lines, but don't know how to do that. Apparently, the coordinates of the 3 points of the triangle area are identifiable. Could anyone please help me with that? Thank you in advance.
\documentclass{standalone}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\usetikzlibrary{intersections}
\begin{document}

\begin{tikzpicture}
\begin{axis}[
    axis lines = left,
    xlabel = $x$,
    ylabel = {$f(x)$},
    ymin=0, ymax=5
]
%Below the red parabola is defined
\addplot [name path=A][
    domain=0:4,
    samples=10,
    color=red,
]
{2-0.5*x};
\addlegendentry{A: 2-0.5*x}
%Here the blue parabloa is defined
\addplot [name path=B][
    domain=0:4,
    samples=10,
    color=blue,
    ]
    {(15-5*x)/3};
\addlegendentry{B: (15-5*x)/3}

\addplot [name path=C][
    domain=0:4,
    samples=10,
    color=yellow,
    ]
    {5*x-15};
\addlegendentry{C: 5*x-15}

\def\firstellipse{(-4,0) ellipse [x radius=8, y radius=3, rotate=45]}

\end{axis}
\end{tikzpicture}
\end{document}

A: Here is a way:
\documentclass{article}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\usetikzlibrary{intersections}
\begin{document}

\begin{tikzpicture}
\begin{axis}[
    axis lines = left,
    xlabel = $x$,
    ylabel = {$f(x)$},
    ymin=0, ymax=5
]
%Below the red parabola is defined
\addplot [name path=A][
    domain=0:4,
    samples=10,
    color=red,
]
{2-0.5*x};
\addlegendentry{A: 2-0.5*x}
%Here the blue parabloa is defined
\addplot [name path=B][
    domain=0:4,
    samples=10,
    color=blue,
    ]
    {(15-5*x)/3};
\addlegendentry{B: (15-5*x)/3}

\addplot [name path=C][
    domain=0:4,
    samples=10,
    color=yellow,
    ]
    {5*x-15};
\addplot[blue!60] fill between[of=A and B,soft clip={domain=2.6:3}];
\addplot[blue!60,draw] fill between[of=C and A,soft clip={domain=3:3.1}];
\addlegendentry{C: 5*x-15}

\def\firstellipse{(-4,0) ellipse [x radius=8, y radius=3, rotate=45]}

\end{axis}
\end{tikzpicture}
\end{document}

I didn't solved the equations to find real points, and I suggest you to do it.
Output:

PS: If the above answers to your question, your question is duplicate of : pgfplots fillbetween with multiple curves

A: With \usetikzlibrary{intersections} you could (1.) compute the intersection points a,b and c and then (2.) fill the area  between them.
intersection points:
\node[coordinate, name intersections = {of = A and B}] (a) at  (intersection-1) {};
\node[coordinate, name intersections = {of = A and C}] (b) at  (intersection-1) {};
\node[coordinate, name intersections = {of = B and C}] (c) at  (intersection-1) {};

Fill area
\fill[red](a) -- (b) -- (c);

MWE:
\documentclass{standalone}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}
\usetikzlibrary{intersections}
\begin{document}

\begin{tikzpicture}
\begin{axis}[
    axis lines = left,
    xlabel = $x$,
    ylabel = {$f(x)$},
    ymin=0, ymax=5
]
%Below the red parabola is defined
\addplot [name path=A][
    domain=0:4,
    samples=10,
    color=red,
]
{2-0.5*x};
\addlegendentry{A: 2-0.5*x}
%Here the blue parabloa is defined
\addplot [name path=B][
    domain=0:4,
    samples=10,
    color=blue,
    ]
    {(15-5*x)/3};
\addlegendentry{B: (15-5*x)/3}

\addplot [name path=C][
    domain=0:4,
    samples=10,
    color=yellow,
    ]
    {5*x-15};
\addlegendentry{C: 5*x-15}

\def\firstellipse{(-4,0) ellipse [x radius=8, y radius=3, rotate=45]}
%% NEW
\node[coordinate, name intersections = {of = A and B}] (a) at  (intersection-1) {};
\node[coordinate, name intersections = {of = A and C}] (b) at  (intersection-1) {};
\node[coordinate, name intersections = {of = B and C}] (c) at  (intersection-1) {};
\fill[red](a) -- (b) -- (c);
%%
\end{axis}
\end{tikzpicture}
\end{document}


Q: Android Custom section header views I have a listview which should contain different types of data. I want to group them in sections. Requirement is that each section header should have different layout for e.g.
listview should have following structure.
DATA A       price     quanitity    weight    color
PICTURE       123.0       10          1       Green
PICTURE       190.0       12          2       Orange

DATA B      price       purity      weight
PICTURE      133.0       100%        10
PICTURE      142.0       92%         15

DATA C      price       quanity      weight
PICTURE     103.0        10            12

How to display such data in listview. As you can see that each section might have different section headers. Does anybody knows about such listview? Currently I am using http://code.google.com/p/android-amazing-listview/ but it only allows to have fixed header view for all sections. If someone can help me modifying it or tell me anyother listview that does it then it will be real help.
Thanks

A: You can use different viewTypes that means that you can use different types of layout for different types of view in your listview. Simply ovverride getViewType(int pos) in your adapter. And you can set different layouts in you getView like this
if (getItemViewType(position) == VIEW_TYPE_LEFT) {
            convertView = inflater.inflate(R.layout.image_bubble_left, null);
            holder.drawable = (NinePatchDrawable) convertView.findViewById(R.id.bubble_left_layout).getBackground();
            holder.bubbleLayout = (RelativeLayout)convertView.findViewById(R.id.bubble_left_layout);

        } else {
            convertView = inflater.inflate(R.layout.image_bubble_right, null);
            holder.drawable = (NinePatchDrawable) convertView.findViewById(R.id.bubble_right_layout).getBackground();
            holder.bubbleLayout = (RelativeLayout)convertView.findViewById(R.id.bubble_right_layout);
        }

But have you considered using a tablelayout?

A: i think this link will help you. Here is a copy paste example. It just works. Is a listview with headers and multiple views in each row.
Give it a try.
http://w2davids.wordpress.com/android-sectioned-headers-in-listviews/


Q: Open default browser when link opens a new window I am using Android WebView and I have shouldoverrideurlloading so that it doesn't open up the default browser when navigating within the browser.
Is there a way to get it so it only opens the default browser when the link is one that opens a new page like: target="_blank"??


Q: SQL Server chooses unselective index I was testing SQL Server indexes and found very strange behavior. Here is my code:
DROP TABLE IF EXISTS  dbo._Test
DROP TABLE IF EXISTS  dbo._Newtest
GO
CREATE TABLE _Test(
ID INT NOT NULL,
UserSystemID INT NOT NULL,
Age INT
)
GO
INSERT INTO dbo._Test
        ( ID, UserSystemID, Age )

SELECT TOP 10000000 ABS(CHECKSUM(NEWID())) % 5000000, ABS(CHECKSUM(NEWID())) % 2, ABS(CHECKSUM(NEWID())) % 100
FROM sys.all_columns
CROSS JOIN sys.all_objects a
CROSS JOIN sys.all_objects b
CROSS JOIN sys.all_objects c

; WITH cte AS (
SELECT ID, UserSystemID,  age, ROW_NUMBER() OVER(PARTITION BY ID, UserSystemID ORDER BY GETDATE()) rn
FROM dbo._Test
)

SELECT cte.ID ,
       cte.UserSystemID ,
       cte.Age
INTO _newTest
FROM cte
WHERE cte.rn = 1

CREATE UNIQUE NONCLUSTERED INDEX  IX_test ON dbo._NewTest(ID, UserSystemID) INCLUDE(age)
GO
ALTER TABLE dbo._NewTest ADD CONSTRAINT PK_NewTest PRIMARY KEY CLUSTERED(UserSystemID, ID)
GO

At this point, I have two indexes on the same table and on the same columns. First one is nonclustered and the second one is clustered. The Id column is more selective (about 5000000 unique values) and UserSystemID is not (two unique values).
Then I run the following query to test which index is used:
SELECT id,  UserSystemID, age
FROM _NewTest
WHERE id = 1502945
AND UserSystemID = 1

It seeks the clustered index. You can see the plan here.
The question is why SQL Server prefers the clustered index instead of the unique nonclustered index.

My leading column of clustered index is much less selective than the other unique nonclustered index. So I expect that the performance must be worse with clustered index but in practice it is not.

A: Given the unique indexes, your query will select at most one row.
The optimizer knows it will need to descend the index b-tree just once, and will not need to scan forward or backward from that point to find more matches. This is known as a singleton seek (equality test on a unique index).
The current index matching implementation happens to always choose the clustered index when it can use a singleton seek.
The choice between clustered and nonclustered index here is generally not very important.
There might be a tiny extra cost as the upper levels of the b-tree are navigated (using binary search or linear interpolation) but this would be challenging to even measure. Remember only the ID and UserSystemID key components are present on non-leaf index pages.
One could argue that wider clustered index leaf pages are less likely to be in memory on average. There are a few other edge case consequences, but I don't see this behaviour being changed any time soon.

But my leading column of clustered index is much less selective than the other unique nonclustered index. So I expect that the performance must be worse with clustered index but in practice it is not.

The selectivity does not matter for equality seek on a compound b-tree index.
Your unique clustered compound index has keys (UserSystemID, id).
To find a row with (UserSystemID = 1 and id = 1502945), SQL Server does not find all rows where UserSystemID = 1, then find rows where id = 1502945. That would be very inefficient.
You can tell how many pages your test query touches using SET STATISTICS IO ON. Your example builds a clustered index with two non-leaf levels. In total, finding the row you want means touching three pages - one at each level of the index.
Rows are ordered in the index by UserSystemID and id. My copy of your demo table has the following layout on the root (top level) page of the clustered index:

Performing a binary search on this page is easy:

*

*Start at the middle row.

*Compare the UserSystemID with the one you are looking for.

*

*If it is not equal, continue the binary search in the usual way (choose a new midpoint in the earlier or later rows as appropriate).

*If equal on UserSystemID, Compare the id with the one you are looking for, and continue the binary search

Following that logic, we will quickly find the child (next lower level) index page the searched keys will be found on if they are present. Repeat the binary search on that page, and so on until we reach the single leaf-level page that must contain the row we are looking for, if it exists.


Q: LINQ include doesn't include related entities when parameters are passed I have the following code. When I don't give the param "current" and "version" so it only run the first line, the lstFile variable at the end contains the file with it's related jobs. If a give the "current" parameter or the "version" parameter, files are returned without the related Jobs. But since I include the Jobs in the first step, why does the related Jobs are lost in the process?
And by the way, lazy loading is Off, that's why I need to do the include.
IQueryable<File> filteredFiles = entities.Files.Include("Jobs");

if (!String.IsNullOrWhiteSpace(current))
{
    bool bActive = current == "1" ? true : false;

    filteredFiles =
        from f in filteredFiles
        join j in entities.Jobs
            on f.IDFile equals j.IDFile
        where j.Active == bActive
        select f;
}

if (!String.IsNullOrWhiteSpace(version))
{
    filteredFiles =
        from f in filteredFiles
            join j in entities.Jobs
            on f.IDFile equals j.IDFile
        where j.Version == version
        select f;
}

List<File> lstFile = filteredFiles.Distinct().ToList();

A: The Include merely means that the Jobs property isn't going to defer execution when the query is executed and that each record is going to also return all of the related Jobs records.  In your joins you're actually filtering out the files that don't have jobs that meet the given criteria.  You aren't filtering out the jobs of those files, you're filtering out all of the files that have those jobs.  The Include won't prevent those files from being filtered out.

A: After Eren Ersönmez point me out that there was an Include function for the IQueryable interface, I decided to try to upgrade my EF4 to EF6 and with this update, the function was available! This is not clear in the documentation from Microsoft.
If that can help someone else, I have followed this tutorial on how to update from EF4 to EF6.


Q: Read 2D array in C++ using boost::spirit I would like to read a simple 2D int array (whitespace separated) as here:
qi::phrase_parse(b, e, +qi::int_ % qi::eol, qi::space - qi::eol, vectors)

There are two differences, though:

*

*I want to put it into a 1D std::vector, line by line, without separating

*If two lines have a different amount of ints, this shall be recognized as a parsing error.

Is it possible to do this as a one liner, e.g. without writing my own parser? Just as simple as in the link mentioned above?

A: Assuming you meant the Spirit version ("as a one liner"), below is an adapted version that adds the check for number of elements.
Should you want more control (and on the fly input checking, instead of 'in hindsight') then I recommend you look at another answer I wrote that shows three approaches to do this:

*

*Boost::Spirit::QI parser: index of parsed element
.
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/spirit/include/karma.hpp>

namespace spirit = boost::spirit;
namespace qi     = boost::spirit::qi;
namespace karma  = boost::spirit::karma;

int main()
{
    std::cin.unsetf(std::ios::skipws);
    spirit::istream_iterator b(std::cin), e;

    std::vector<std::vector<int> > vectors;

    if (qi::phrase_parse(b, e, +qi::int_ % qi::eol >> qi::eoi, qi::blank, vectors))
    {
        std::cerr << "Parse failed at '" << std::string(b,e) << "'\n";
        return 255;
    }

    // check all rows have equal amount of elements:
    const auto number_of_elements = vectors.front().size();
    for (auto& v : vectors)
        if (v.size() != number_of_elements)
            std::cerr << "Unexpected number of elements: " << v.size() << " (expected: " << number_of_elements << ")\n";

    // print the data for verification
    std::cout
        << karma::format(karma::right_align(8)[karma::auto_] % ',' % '\n', vectors)
        << std::endl;

    return 0;
}

The karma bits are not necessary (they're just there to output the whole thing for demonstration).
UPDATE
To build in more active error checking, you could do:
int num_elements = 0;
bool ok = qi::phrase_parse(b, e,
        (+qi::int_) [ phx::ref(num_elements) = phx::size(qi::_1) ]
     >> *(qi::eol >> qi::repeat(phx::ref(num_elements)) [ qi::int_ ])
     >> *qi::eol,
     qi::blank, vectors);

Which uses qi::repeat to expect the num_elements number of elements on subsequent lines. You can just store that into a 1-dimensional array:
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/spirit/include/karma.hpp>

namespace qi     = boost::spirit::qi;
namespace phx    = boost::phoenix;
namespace karma  = boost::spirit::karma;

int main()
{
    std::cin.unsetf(std::ios::skipws);
    boost::spirit::istream_iterator b(std::cin), e;

    //std::vector<std::vector<int> > vectors;
    std::vector<int> vectors;

    int num_elements = 0;
    bool ok = qi::phrase_parse(b, e,
            (+qi::int_) [ phx::ref(num_elements) = phx::size(qi::_1) ]
         >> *(qi::eol >> qi::repeat(phx::ref(num_elements)) [ qi::int_ ])
         >> *qi::eol,
         qi::blank, vectors);

    std::cout << "Detected num_elements: " << num_elements << "\n";

    if (!ok)
    {
        std::cerr << "Parse failed at '" << std::string(b,e) << "'\n";
        return 255;
    }

    if (b!=e)
        std::cout << "Trailing unparsed: '" << std::string(b,e) << "'\n";

    // print the data for verification
    std::cout
        << karma::format_delimited(karma::columns(num_elements)[+karma::int_], ' ', vectors)
        << std::endl;

    return 0;
}

Note the use of karma::columns(num_elements) to split the output into the correct number of columns per row.


Q: JavaScript Refactoring / Avoid Repitition I need to refactor this to avoid code repetition.
$('#showmore-towns').toggle(
    function() {
        $('.popularTownsAdditional').show();
        console.log(this);
        $('#showmore-town .showless').show();
        $('#showmore-town .showmore').hide();
        $('#showmore-town').removeClass('sd-dark28').addClass('sd-dark28down');
        return false;
    },
    function() {
        $('.popularTownsAdditional').hide();
        $('.showless').hide();
        $('.showmore').show();
        $('#showmore-towns').addClass('sd-dark28').removeClass('sd-dark28down');
    });

$('#showmore-cities').toggle(
    function() {
        $('.popularCitiesAdditional').show();
        $('#showmore-cities .showless').show();
        $('#showmore-cities .showmore').hide();
        $('#showmore-cities').removeClass('sd-dark28').addClass('sd-dark28down');
        return false;
    },
    function() {
        $('.popularCitiesAdditional').hide();
        $('#showmore-cities .showless').hide();
        $('#showmore-cities .showmore').show();
        $('#showmore-cities').addClass('sd-dark28').removeClass('sd-dark28down');
    });

basically, it shows the same functionality but only on different divs with different IDs.

A: Probably just need to reference a named function or two instead of the anon ones.
function showStuff(typeToShow) {
    $('.popular' + typeToShow + 'Additional').show();
    $('#showmore-' + typeToShow + .showless').show();
    $('#showmore-' + typeToShow + .showmore').hide();
    $('#showmore-' + typeToShow).removeClass('sd-dark28').addClass('sd-dark28down');
    return false;
}

function hideStuff(typeToHide) {
    $('.popular' + typeToHide + 'Additional').hide();
    $('#showmore-' + typeToHide + .showless').hide();
    $('#showmore-' + typeToHide + .showmore').show();
    $('#showmore-' + typeToHide ).addClass('sd-dark28').removeClass('sd-dark28down');
}

NOTE: a) You could probably make these methods a bit slicker, but you get the idea!
NOTE: b) You'd need to rename '#showmore-town' to '#showmore-towns' (with an S) if you want to use the substitution suggested.
Then in your toggle you could reference these functions:
$('#showmore-towns').toggle(showStuff(towns),
hideStuff(towns));

$('#showmore-cities').toggle(showStuff(cities),
hideStuff(cities));

A: I mean...if it's always going to start with #showmore-...we can work it down
$('[id^=showmore-]').toggle(
function() {
    var id = $(this).prop('id');
    id = id.split('-')[1];
    var upperID = id.charAt(0).toUpperCase() + id.slice(1);
    $('.popular'+upperID+'Additional').show();
    $('#showmore-'+id+' .showless').show();
    $('#showmore-'+id+'.showmore').hide();
    $('#showmore-'+id).removeClass('sd-dark28').addClass('sd-dark28down');
    return false;
},
function() {
    var id = $(this).prop('id');
    id = id.split('-')[1];
    var upperID = id.charAt(0).toUpperCase() + id.slice(1);
    $('.popular'+upperID+'Additional').hide();
    $('#showmore-'+id+' .showless').hide();
    $('#showmore-'+id+' .showmore').show();
    $('#showmore-'+id).addClass('sd-dark28').removeClass('sd-dark28down');
});

A: you could do:
(function() {

    $('#showmore-towns').toggle(
        function() { showmorelessOn('#showmore-town'); },
        function() { showmorelessOff('#showmore-town'); }
    );
    $('#showmore-cities').toggle(
        function() { showmorelessOn('#showmore-town'); },
        function() { showmorelessOff('#showmore-town'); }
    );

    var showmorelessOn = function(context) {
        $('.popularCitiesAdditional').show();
        $('.showless', context).show();
        $('.showmore', context).hide();
        $(context).removeClass('sd-dark28').addClass('sd-dark28down');
        return false;
    };
    var showmorelessOff = function(context) {
        $('.popularCitiesAdditional').hide();
        $('.showless', context).hide();
        $('.showmore', context).show();
        $(context).addClass('sd-dark28').removeClass('sd-dark28down');
    };

})();

though I agree, could perhaps be better served on codereview.stackexchange.com

A: I would do this almost entirely in the CSS.  Only use .toggleClass() and determine what is shown and what is hidden in the CSS.

A: (function() {

    $('#showmore-towns').toggle(
        function() { showmorelessOn.call($('#showmore-town')); },
        function() { showmorelessOff.call($('#showmore-town')); }
    );
    $('#showmore-cities').toggle(
        function() { showmorelessOn.call($('#showmore-town')); },
        function() { showmorelessOff.call($('#showmore-town')); }
    );

    var showmorelessOn = function() {
        $('.popularCitiesAdditional').show();
        $('.showless', this).show();
        $('.showmore', this).hide();
        $(this).removeClass('sd-dark28').addClass('sd-dark28down');
        return false;
    };
    var showmorelessOff = function() {
        $('.popularCitiesAdditional').hide();
        $('.showless', this).hide();
        $('.showmore', this).show();
        $(this).addClass('sd-dark28').removeClass('sd-dark28down');
    };

})();

(function() {

    $('#showmore-towns').toggle(
        function() { showmoreless(); }
    );
    $('#showmore-cities').toggle(
        function() { showmoreless(); }
    );

    var showmoreless = function() {
           if(this.hasClass('sd-dark28'){
            $('.popularCitiesAdditional').show();
            $('.showless', this).show();
            $('.showmore', this).hide();
            $(this).removeClass('sd-dark28').addClass('sd-dark28down');
       }
     else
       {
      $('.popularCitiesAdditional').hide();
            $('.showless', this).hide();
            $('.showmore', this).show();
            $(this).addClass('sd-dark28').removeClass('sd-dark28down');
      }
}.bind($('#showmore-town'));
})();


Q: creating a 2D array in javascript please i am new to javascript and i want to create a two dimensional array. this is the code i have:
var locations = new Array(track);

for(var j = 0; j < track; j++){
    locations[j] = new Array();
    locations[j] = ['test', 'test', 'test', 'test']
}

when i try to output locations, i have only one row of tests. please what could be the problem, because i am expecting track rows of test.
thanks.

A: If you want something to print all the rows you have to keep you what you have already printed so you have to do something like this :
for(var j = 0; j < 10; j++) {

         document.getElementById("myResults").innerHTML =
         document.getElementById("myResults").innerHTML + locations[j] + "<br>";
}

You can see it there:
http://jsfiddle.net/Ba8TU/


Q: What type of function is this? const xhr = new XMLHttpRequest(),
    method = "GET",
    url = "https://developer.mozilla.org/";

xhr.open(method, url, true);
xhr.onreadystatechange = function () {
  // In local files, status is 0 upon success in Mozilla Firefox
  if(xhr.readyState === XMLHttpRequest.DONE) {
    var status = xhr.status;
    if (status === 0 || (status >= 200 && status < 400)) {
      // The request has been completed successfully
      console.log(xhr.responseText);
    } else {
      // Oh no! There has been an error with the request!
    }
  }
};
xhr.send();

This code represent an XHR request and response. I was watching a tutorial on AJAX and xhr.onreadystatechange was described as an object property. I know that function expressions are anonymous functions assigned to variables but what about anonymous functions assigned to object properties. What is the name of this kind of function that is called when an object property updates? This hasn’t really been taught in basic javascript or ES6 from what I can see.

A: The function that you are assigning to xhr.onreadystatechange is called an event handler. This event handler function gets executed when the actual event 'readystatechange' gets fired in your case.

A: That is a event handler which differs a little bit from a callback.


Q: Wordpress filtering custom post type taxonomy I've been following this guide: https://rudrastyh.com/wordpress/ajax-post-filters.html#comment-908. I've got a custom post type called "project" and a taxonomy called "producten". What i'm trying to achieve is that the filters categories under the taxonomies get called and the user can filter the posts by using those taxonomies. I did get it working with a dropdown, but what i want are filters. I've created these by using checkboxes which do work, it's just that when i actually try to filter, all posts get shown, no matter which filter i select. The code is used on a random template called test.php.
I feel like there's some really obvious mistake i'm making but i can't seem to figure it out.
The code in test.php:

        <form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
            <?php
                if( $terms = get_terms( array( 'taxonomy' => 'producten' ) ) ) :
                    echo '
';
                    foreach( $terms as $term ) :
                        echo 'term_id . '"><input type="checkbox" id="product_' . $term->term_id . '" name="product_' . $term->term_id . '" />' . $term->name . '';
                    endforeach;
                    echo '
';
                endif;
            ?>
            <button>Pas filters toe</button>
            <input type="hidden" name="action" value="myfilter">
        </form>

The code in functions.php:
add_action('wp_ajax_myfilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');

function misha_filter_function(){

$args = array(
    'post_type' => 'project',
    'orderby' => 'date', // we will sort posts by date
    'order' => $_POST['date'], // ASC or DESC
    'posts_per_page' => '-1'
);

    if( $terms = get_terms( array( 'taxonomy' => 'producten' ) ) ) :
$all_terms = array();

foreach( $terms as $term ) {
    if( isset( $_GET['product_' . $term->term_id ] ) && $_GET['product_' . $term->term_id] == 'on' )
         $all_terms[] = $term->slug;
}

if( count( $all_terms ) > 0 ) {
    $args['tax_query'] = array(
        array(
            'taxonomy' => 'producten',
            'field' => 'slug',
            'terms'=> $all_terms
        )
    );
}

endif;

$query = new WP_Query( $args );

if( $query->have_posts() ) :
    echo '
';
    while( $query->have_posts() ): $query->the_post();
    echo '
';
    echo '

';
    echo '
';
    echo the_title();
    echo '

';
    echo  the_excerpt();
    echo  '

                <svg xmlns="http://www.w3.org/2000/svg" width="15.528" height="27.359" viewBox="0 0 15.528 27.359">
                    <g id="Group_5" data-name="Group 5" transform="translate(2568.865 -660.337) rotate(90)">
                        <g id="Group_2" data-name="Group 2" transform="translate(660.337 2553.337)">
                            <rect id="Rectangle_11" data-name="Rectangle 11" width="19.346" height="2.614" rx="1.307" transform="translate(0 13.679) rotate(-45)" fill="#fff"/>
                            <rect id="Rectangle_12" data-name="Rectangle 12" width="19.346" height="2.614" rx="1.307" transform="translate(25.51 15.528) rotate(-135)" fill="#fff"/>
                        </g>
                    </g>
                </svg>

';

    if( has_post_thumbnail() ):
            echo get_the_post_thumbnail();
    endif;
    echo    '

';
            endwhile;
    echo    '
';

            wp_reset_postdata();
        else :
            echo 'No posts found';
        endif;

        die();

    }

And the jQuery function:
jQuery(function($){
$('#filter').submit(function(){
    var filter = $('#filter');
    $.ajax({
        url:filter.attr('action'),
        data:filter.serialize(), // form data
        type:filter.attr('method'), // POST
        beforeSend:function(xhr){
            filter.find('button').text('Processing...'); // changing the button label
        },
        success:function(data){
            filter.find('button').text('Apply filter'); // changing the button label back
            $('#response').html(data); // insert data
        }
    });
    return false;
});
});

A: Actually found the solution after hours of trying. Changing $_GET to $_POST did the trick.
if( isset( $_GET['product_' . $term->term_id ] ) && $_GET['product_' . $term->term_id]

Changed to:
if( isset( $_POST['product_' . $term->term_id ] ) && $_POST['product_' . $term->term_id]


Q: ASP.NET How to access multiple form labels text property with foreach loop I have a form runat= "server" with id = "myform" . It is a profile page with lots of labels. I am getting their input text from SQL database. But if the SQL data base have null value, then i wish their text get changed to "Not Specified". For such reason i am using following code, but it is not working.
foreach (Control item in myform.Controls)
{
    Label lbl = null;
    bool labelIsEmpty = false;
    try
    {
        lbl = (Label)item;
        labelIsEmpty = (lbl.Text == string.Empty && lbl != null);
    }
    catch
    {
    }

    if (labelIsEmpty)
    {
        lbl.Text = "Not Specified";
    }
}

A: myform.Controls will gives you a collection that contains all controls withing the container( not only labels). So you have to check for the type for control while iterating the collection in order to avoid throwing exception. In the additional comment you ware specify that label has default text "Label" so you need to include this also in the condition. The whole scenario can be implemented like the following:
      foreach (Control  item in myform.Controls)
        {
            if (item is Label)
            {
              var  lbl = (Label)item;
              bool labelIsEmpty = false;
              try
              {
                  lbl = (Label)item;
                  labelIsEmpty = (lbl != null && lbl.Text == string.Empty && lbll.Text!="Label");
              }
              catch
              {
              //Throw error message
              }
              if (labelIsEmpty)
              {
                  lbl.Text = "Not Specified";
              }
            }
        }

Note :-

You need to reorder the conditions to avoid exception. Check for
  string.Empty should be comes after check for control is  null.
  Because AND  will not check for second condition if first one is
  false, lbl.Text will throw NullReferenceException if lbl is null

A: foreach (Control item in myform.Controls)
        {
            if (item is Label)
            {
                var lbl = (Label)item;
                bool labelIsEmpty = false;
                try
                {
                    lbl = (Label)item;
                    labelIsEmpty = (lbl != null && (lbl.Text == string.Empty || lbl.Text == "Label"));
                }
                catch
                {
                    //Throw error message
                }
                if (labelIsEmpty)
                {
                    lbl.Text = "Not Specified";
                }
            }
        }


Q: Accessing / processing ArrayBuffer @ http client (websocket connection, JavaScript) I have a websocket connection between
•   Nodejs server (+ socket.io)
•   Browser
A message is emitted from the server to the browser (Udp message from an Arduino)
udpSocket.on("message", function (msg, rinfo) {
    for (i = 0; i < msg.length; i++) {
        console.log(msg.readInt8(i));
}
    console.log("");
    io.sockets.emit('message', msg);
});

Code in the browser (index.html):
A)
I started with:
socket.on('message', function(message) {
    document.getElementById("ko1").innerHTML = message;
})

 Arduino sends:

Result in browser : [object ArrayBuffer]
My conclusion : message is coming in, but must be handled in another way.
B)
Research learned that I have to use a DataView on the Array Buffer (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays). My code:
socket.on('message', function(message) {
    var uint8 = new Uint8Array(message);
    document.getElementById("ko1").innerHTML = uint8[0];
})

Result : no data printed to the browser
Question: what am I doing wrong? I also tried other Data Views, but no success. It’ s driving me mad. Please help.


Q: Best way to get data from database I have a doubt. I need to get the data from the sever twice every time when I load a page, one to render the HTML and another one to get the data for client side (javascript).
So I don't know exactly what it's the best way and fastest. I was trying to implement a session object and store the data once using joinedload loading technique. When the data is in the client side, to kill the session object.
Another one it's to call the database twice.
I don't know which one is faster and better because I don't know if the database or server stores the first call in memory. If so it's not like to call the database twice, right?
And if the second choice is better which loading technique (joinedload, eagerload or subqueryload) is better to use.
Every call could be a bunch of data.
Any help could be really useful.
Thanks in advance!

A: I'm not really sure about all this stuff you asked, so I'll try 2 different scenarios.

*

*If the data you need to display the html and data needed for the javascript is the same - you're doing it very wrong. All you need to do is to query the db only for the html, then structure the data needed for javascript in hidden fields, then, on client side, query the html's hidden fields with javascript and use the data onward.

*If the data sets are different than you'll probably need an ajax request from the client side after the html is displayed. That is, an additional http request. I say you close the db connection after the first call, and then reopen again with the next http request. Every http request is on its own, you'll need to take care with opening/closing connections inside a single request. [That is, if you don't use pooling, but that is another issue]


Q: Setting user programmatically in ASP.NET MVC5 I want to log user programatically in ASP.NET MVC5. I'm setting auth cookies like this:
FormsAuthentication.SetAuthCookie(username, true);

I thouth it will be enough. But then I want to check value of Request.IsAuthenticated and it is always false. Also when I'm checking value of User.Identity.Name I'm getting empty string, not the username I passed earlier.
What should I do to make this work and set this values correctly?
EDIT:
One more thing. I'm not using any login form, I'm passing user data (login and token) from different application.

A: Make sure form Athentication is enabled in your web.config file.
<system.web>
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
...
</system.web>

A: MVC5 comes with Identity instead of the older SimpleMembership and ASP.NET Membership. Identity doesn't use forms auth, hence why what you're doing has no effect.
To log a user in via Identity, first, you need an actual user instance, which you can get by doing something like:
var userManager = new UserManager<ApplicationUser>(context);
var user = userManager.FindByName(username);

Then if you have a valid user (user != null), you need to generate a claims identity for that user via:
var identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

Finally, you can use that identity to sign the user in:
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);

(If you want a persistent login, change that to true)


Q: Expanding a variable containing an equals sign and curly braces I'm writing a script that uses rsync and excludes files based on certain settings. I end up with an exclude flag that has a format of --exclude={foo, bar, baz}.
However, upon trying to expand it within the rsync command, I noticed the flag is escaped. From the bash debugger, I can see my command of rsync $excludes becomes rsync '--exclude={foo,bar,baz}', rather than the expected rsync --exclude={foo,bar,baz}. Doing some testing, I found that any string containing =, {, or } will get wrapped in single quotes when expanded. Short of using eval on a constructed string, is there a way around this?

A: Brace expansion won't occur when quoted.  You should also store arguments in an array rather than a variable (when possible).
I think the following should work for you:
excludes=( $(--exclude={foo,bar,baz}) )
rsync "${excludes[@]}"

A:
From the bash debugger, ... any string containing =, {, or } will get wrapped in single quotes when expanded.

If you mean the xtrace output (set -x), it does indeed like to display arguments in single quotes when they contain special characters. The output is in a format that would be usable as input to the shell.
That doesn't mean the quotes are part of the string, though.
Compare:
$ echo abc def\ ghi
+ echo abc 'def ghi'
abc def ghi

$ echo abc \'def\ ghi\'
+ echo abc ''\''def ghi'\'''
abc 'def ghi'

Though as far as I can see, it doesn't bother to quote strings containing the equal sign.


Q: How to carry data of a variable to the rest of the same page? It really is easy for me to do it in the following way:
if(mysqli_num_rows($result) > 0){
    while ($row = mysqli_fetch_array($result)) {
        $id_product = $row['id_courses'];
        $product = $row['product'];
        $title = $row['title'];
        $subtitle = $row['subtitle'];
        $price = $row['price'];
    }
}

Then later only print the value of the variable on any part of the page as follows:
echo $product;

How can I do the same with an object-oriented query?

like the previous query, this query also works, I perform the same procedure and print the value correctly:

echo $product;

but it is correct that this code while ($stmt->fetch()) {} is left empty in the following query
$stmt->bind_param("i",$active);
$stmt->execute();
$stmt->bind_result( $id_product,$product,$subtitle,$price);

      while ($stmt->fetch()) {

      }

A: Just get rid of while.
It was useless with your old approach and become harmful with second one.
You have to understand that this while thing is not some obligatory part of the database interaction but the way to get multiple rows. But since you are fetching only one row, you shouldn't use while at all.
Your first code block should be
$result = mysqli_query(...);
$row = mysqli_fetch_array($result);
$id_product = $row['id_courses'];
...

and the second one as well
$stmt->bind_param("i",$active);
$stmt->execute();
$stmt->bind_result( $id_product,$product,$subtitle,$price);
$stmt->fetch();

in the first block you saved variables manually inside while, and thet's why they were available outside the loop. But in the second they are populated directly by fetch() method and therefore it makes them all empty on the last iteration when no more data left.


Q: AC_FL_Runcontent is not defined , Exadel Fiji I am using Exadel-Fiji 1.0, Richfaces 3.3.3, Jboss 4.3 -EAP, Seam 2.1.0, JSF-1.2_09
When I try to render a exadel fiji line chart , the page just throws up a blank screen and
the firefox error console says
AC_FL_Runcontent is not defined

A: I found the solution.
I had the following code in my web.xml. I had to comment it out to get it working
<context-param>
  <param-name>org.richfaces.LoadScriptStrategy</param-name>
  <param-value>NONE</param-value>
</context-param>

A: This script error is because one of the fiji related js file is missing in your jsf page. Please add the following script in your xhtml/jsf page to resolve this issue:
<script type="text/javascript" src="/[your-application-context-name]/a4j/g/3_3_1.CR1com/exadel/fiji/renderkit/html/AC_OETags.js.jsf" />

Before testing this in your application, please check that you are able to view Javascript with your browser using the following URL:
http://[url]:8080/[your-application-context-name]/a4j/g/3_3_1.CR1com/exadel/fiji/renderkit/html/AC_OETags.js.jsf

or
http://[url]:8080/your-application-context-name/a4j/g/3_3_1.CR1com/exadel/fiji/renderkit/html/AC_OETags.js

If you are able to see the script content in your browser, your problem has been resolved, and there will be no need to comment the web.xml changes.


Q: Excel VBA Macro MsgBox auto converts number to Scientific notation, how do I stop this? I am trying to get the current date into milliseconds so I can compare it to the AD "LastLogon" time stamp. The problem is that the current date automatically becomes scientific notation instead of the 18 digit number I am in need of. How do I force it to display all digits?
Dim currentDate
currentDate = Now * (8.64 * 10 ^ 11) + 109205
'MsgBox (DateAdd("d", -90, Now))
MsgBox (currentDate)

A:  MsgBox( Format(currentDate, "#0"))

or other format you prefer

A: Dim currentDate
currentDate = Now * (8.64 * 10 ^ 11) + 109205
'MsgBox (DateAdd("d", -90, Now))
MsgBox (Format(currentDate(), "MM dd, yyy"))
MsgBox (Format(Now(), "MM dd, yyy"))

Now() displays a date
currentDate is an over flow.
How to format date in VBA?


Q: Can an equation of two ratios with an unknown in the numerator and an unknown in the denominator be constrained enough to solve? E.g. Looking back at some of previous work, I can't understand how I solved this question in the way that I did:

I would now solve this using the fact that $m_{radius}  = \frac{1}{3}$ and the centre $=(5, -3)$ with $y-y_1 = m(x-x_1)$ to find the equation of the radius and diameter to such tangents. I would then solve this equation along with the equation of the circle as a system of equation to find the points where l intersects with C. Finally, I would then sub into $y-y_1 = m(x-x_1)$ to obtain the possible equations for l.
However, that's not how I actually solved this problem. Instead, I solved this using $m_{radius} = \frac{1}{3}$, centre $=(5, -3)$, and that $m = \frac{y_2-y_1}{x_2-x_1}$ for a straight line. Picking the centre as $(x_1, y_1)$, I solved $\frac{1}{3}= \frac{y_2+3}{x_2-5}$ as if the numerator and denominator were each individual equations:
$ y_2 + 3 = 1$
$y_2 = -2$
$ x_2 - 5 = 3$
$x_2 = 8$
I then repeated this process for the other point by picking the centre as $(x_2, y_2)$ and solving  for $(x_1, y_1)$. Thus, I ended up with $(8, -2)$ and $(2, -4)$. I subbed this into $y-y_1 = m(x-x_1)$ to obtain the correct possible equations for l, $y = -3x + 22$ and $y = -3x + 2$.
What I don't understand is why solving $\frac{1}{3}= \frac{y_2+3}{x_2-5}$ as if the numerator and denominator were individual equations worked to find the points I needed. Surely $\frac{1}{3}= \frac{y_2+3}{x_2-5}$ is underdetermined as there are two unknowns? Is there some property of it being ratio with one unknown in the numerator and one unknown in denominator that means this is not an issue? Are there are other instances where this is the case? Moreover, I believe $\frac{1}{3}= \frac{y_2+3}{x_2-5}$ has to be underdetermined. Surely, if the centre is $(x_2, y_2)$, then $(x_1, y_1)$ could be any point before $(5, -3)$  along the line with the gradient $m = \frac{1}{3} $? Likewise, $(x_2, y_2)$ could be any point after $(5, -3)$ along this line.
With the 'correct' method, it's only with the additional constraint $(x-5)^2 + (y+3)^2 = 10$ that the points we are trying to find are narrowed down to $(8, -2)$ and $(2, -4)$. So, I can't understand how I could solve this problem without that constraint.

A: This is a fluke. If you have an equation that looks like
$$\frac ab = \frac xy$$
and you are able to solve it by solving $a=x$ and $b=y$ separately, then you are a very lucky person. If you define $c=2x$ and $d=2y$, then it's still true that
$$\frac ab = \frac cd$$
Then we do not have $a=c$ (unless $a=0$) and we definitely do not have $b=d$.
The problem was designed to have "nice" numbers, as is usual for problems that do not arise naturally, and it turned out that the ratios worked out just right for you to be able to solve it this way. But there's no reason for it to work, because you can multiply both the top and the bottom by any constant factor to get a wrong equation in the same way.


Q: Red arrows on line numbers codelite Just downloaded codelite, when I try to include iostream I get a red arrow on that line when hovered over it says file not found. It doesn't cause any warnings or errors however. I have tried reinstalling. If I include the string library I don't get the red arrows on it . Any help is appreciated they are very annoying.

A: Select 'Plugins'->'Language Server'->'Settings' and uncheck the box that says 'Display Diagnostics' at the bottom of the page then click OK.


Q: Failing to run Rake-Task in Textmate I'm starting to write Ruby code for Chef using Textmate 1.5.11, and need some help with an error i'm getting when attempting to run tasks from a RakeFile.
When I try to run Bundles->Ruby->rake->run rake task, I'm expecting to be prompted for which task i'd like to run from my rakefile. Instead, I'm getting the following error:
/opt/chef/embedded/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in require': cannot load such file -- run_rake_task (LoadError) from /opt/chef/embedded/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:inrequire' from /Applications/TextMate.app/Contents/SharedSupport/Bundles/Ruby.tmbundle/Support/RakeMate/rake_mate.rb:7:in `'
Any help greatly appreciated.
Thank you

A: See Textmate + RVM + Rake = Rake not using expected gem environment for some answers about this particular problem, and some advice on how to diagnose your own situation.


Q: How do I create a where condition on a sub table in LINQ This is in response to this question in the answers section of another question.
I have a collection of Orders, each Order a collection of OrderItems, and each OrderItem has a PartId. Using LINQ how do I implement the following SQL statements:
1) Select all the orders that have a specific part ID
SELECT *
FROM Order
WHERE Id in (SELECT OrderId FROM OrderItems WHERE PartId = 100)

2) Select the Order.OrderNumber and OrderItem.PartName
SELECT Order.OrderNumber, OrderItem.PartName
FROM Order INNER JOIN OrderItem ON Order.Id = OrderItem.OrderId
WHERE OrderItem.partId = 100

3) SELECT the Order.OrderNumber and the whole OrderItem detail:
SELECT Order.OrderNumber, OrderItem.*
FROM Order INNER JOIN OrderItem ON Order.Id = OrderItem.OrderId
WHERE OrderItem.partId = 100

A: Actual code should be
1)
var orders = from o in Orders
             where o.OrderItems.Any(i => i.PartId == 100)
             select o;

The Any() method returns a bool and is like the SQL "in" clause. This would get all the order where there are Any OrderItems what have a PartId of 100.
2a)
// This will create a new type with the 2 details required
var orderItemDetail = from o in Orders
                      from i in Orders.OrderItems
                      where i.PartId == 100
                      select new()
                      {
                          o.OrderNumber,
                          i.PartName
                      }

The two from clauses are like an inner join.
2b)
// This  will populate the OrderItemSummary type
var orderItemDetail = from o in Orders
                      from i in Orders.OrderItems
                      where i.PartId == 100
                      select new OrderItemSummary()
                      {
                          OriginalOrderNumber = o.OrderNumber,
                          PartName = i.PartName
                      }

3)
// This will create a new type with two properties, one being the
// whole OrderItem object.
var orderItemDetail = from o in Orders
                      from i in Orders.OrderItems
                      where i.PartId == 100
                      select new()
                      {
                          OrderNumber = o.OrderNumber,
                          Item = i
                       }

Since "i" is an object of Type OrderItem, Item is create as an OrderItem.


Q: A "Hermitian" operator with imaginary eigenvalues Let $${\bf H}=\hat{x}^3\hat{p}+\hat{p}\hat{x}^3$$ where $\hat{p}=-id/dx$.
Clearly ${\bf H}^{\dagger}={\bf H}$, because ${\bf H}={\bf T} + {\bf T}^{\dagger}$, where ${\bf T}=\hat{x}^3\hat{p}$. In this sense ${\bf H}$ is "formally" self-adjoint.
It turns out that
$$ \psi_{\lambda}(x)=\frac{1}{|x|^{3/2}}e^{-\lambda/4x^2} \in L^2[-\infty,\infty]$$
is an eigenfunction of ${\bf H}$. In fact
$${\bf H}\psi_{\lambda}(x)=-i\lambda\psi_{\lambda}(x).$$
If we go through the usual proof that Hermitian operators have real eigenvalues, we see that something has to go wrong in the following steps:
$$ \langle\psi_{\lambda}(x)|{\bf H}\psi_{\lambda}(x)\rangle= \langle{\bf H}^{\dagger}\psi_{\lambda}(x)|\psi_{\lambda}(x)\rangle=\langle{\bf H}\psi_{\lambda}(x)|\psi_{\lambda}(x)\rangle=\langle\psi_{\lambda}(x)|{\bf H}\psi_{\lambda}(x)\rangle^{*}.$$
Clearly ${\bf H}\psi_{\lambda}(x) = -i\lambda\psi_{\lambda}(x)\in L^{2}.$ So all these operations seem to be well-defined.
Our book suggests that we look at ${\bf T}\psi_{\lambda}(x)$. It turns out that ${\bf T}\psi_{\lambda}(x),{\bf T}^{\dagger}\psi_{\lambda}(x) \notin L^{2}$. So when we are writing $$\langle\psi_{\lambda}(x)|{\bf H}\psi_{\lambda}(x)\rangle$$
we are really writing
$$\langle\psi_{\lambda}(x)|({\bf T} + {\bf T}^{\dagger})\psi_{\lambda}(x)\rangle=\langle\psi_{\lambda}(x)|{\bf T}\psi_{\lambda}(x)\rangle+\langle\psi_{\lambda}(x)|{\bf T}^{\dagger}\psi_{\lambda}(x)\rangle$$
where these inner products are no longer defined. Does the fact that these two inner products are undefined lead to this seemingly (and "formally") self-adjoint operator having imaginary eigenvalues? And how?

A: This problem is posed and solved by: François Gieres his article: Mathematical surprises and Dirac’s formalism in quantum mechanics .
It is given in example 3 page 6 and its solution is given in: (3a) page 39 and continued on pages 45 and 46 where the  von Neumann’s criterion for self adjontiness is formulated and applied to the problem.
As explained in the article, the basic reason that the function $\psi_{\lambda}$ is not an eigenfunction of $\mathbf{H}$ is that it does not belong to the Schwartz space $\mathcal{S}(\mathbf{R})$ (of rapidly decreasing  functions) which the mutual domain of definition of both $\hat{x}$ and $\hat{p}$.
In the second part it is shown that $\psi_{\lambda}$ is an eigenfunction of $\mathbf{H^{\dagger}}$ and there is no way to extend the domain of $\mathbf{H}$ to make it self adjoint.

A: The problem with this hamiltonian is that there is a difference between symmetric/Hermitian operators and self-adjoint operators. It looks like a nit-picky mathematician's poking holes into everything, but it is in fact important:

In general, the domains of $\hat{A}$ and $\hat{A}^\dagger$ do not coincide. If $\hat{A}=\hat{A}^\dagger$ on $D(\hat{A})$, then $D(\hat{A})\subseteq D(\hat{A}^\dagger)$ holds and $\hat{A}$ is called symmetric or Hermitian. If, in addition, $D(\hat{A}^\dagger)=D(\hat{A})$, then $\hat{A}$ is called self-adjoint.

The important existence and reality theorems for eigenvalues and eigenvectors are usually only for self-adjoint operators. This is made clear in page 13 of your textbook. While your operator is indeed symmetric, it is unlikely to be self-adjoint.
More specifically, $H$ is densely defined and therefore has an adjoint $H^\dagger$, which is an operator on some domain $D(H^\dagger)$ which satisfies $\langle\phi|H\psi\rangle=\langle H^\dagger\phi|\psi\rangle$ for all $\psi\in D(H)$ and $\phi\in D(H^\dagger)$. Your real job is characterizing the domains of both operators and seeing if they coincide, or figuring out whether $H$ can be extended to a larger domain such that the adjoint's domain will coincide with the original domain. None of that is particularly easy.

The thing is, though, that these mathematical troubles very rarely come on their own and are usually accompanied by trouble in the corresponding classical problem. This is beautifully made clear, together with a clear exposition of the necessary mathematical facts, in the paper

Classical symptoms of quantum illnesses. Chengjun Zhu and John R. Klauder. Am. J. Phys. 61 no. 7, 605 (1993).

The main point is that unless the classical problem has well-defined solutions for all time and for all initial conditions, you really have no business complaining about unexpected behaviour in the quantum counterpart.
For your model, the classical hamiltonian $H=\frac12(q^3p+pq^3)=q^3 p$ produces the Hamilton equations
$$
\left\{
\begin{array}{}
\dot p=-\frac{\partial H}{\partial q}=&3q^2 p,\\
\dot q=\phantom{-}\frac{\partial H}{\partial p}=&q^3.
\end{array}
\right.
$$
These are fairly easy to solve, and the solutions are not well behaved:
$$
\left\{
\begin{array}{}
\frac{1}{2q^2}&=t_0-t,\\
\frac{p_0^2}{p^2}&=(t_0-t)^3,
\end{array}
\right.
$$
where $t_0$ and $p_0$ are constants of integration. Note, in particular, that there are no (real) solutions after a certain time $t_0=t_\text{in}+\frac{1}{2q(t_\text{in})^2}$. How, then, are you expecting reasonable physics out of the quantized version of this?

Finally, as a coda, let me address Qmechanic's very interesting comment. It is true that for a given physical system, you will have a single hamiltonian and many other physical observables. How, then is one to make sense of this construction for an arbitrary observable? I would counter that any arbitrary observable can be considered as a hamiltonian, and that things like the spectrum do follow from properties like the corresponding time evolution.
Take some arbitrary self-adjoint, as-nice-as-necessary physical observable $\hat A$ in a physical system with state space $\mathcal H$. Even if it does not make physical sense, you can definitely postulate the flow associated with that observable, i.e. the curve $t\to|\psi(t)\rangle$ in $\mathcal H$ that obeys the Schrödinger-like equation
$$i\partial_t|\psi(t)\rangle=\hat A|\psi(t)\rangle.$$
If you want to bring the spectrum into play, you can solve this equation by decomposing the flow into the observable's eigenbasis, so
$|\psi(t)\rangle=\sum_n\psi_n e^{-ia_n t}|n\rangle$,
where $\hat A|n\rangle=a_n|n\rangle$ and $\psi_n=\langle n|\psi(0)\rangle$. (Here one needs to assume that $|\psi(0)\rangle$ is "general" or "random" enough that all the $\psi_n$ are nonzero.
The question, though, is how can you extract the spectrum from the time evolution? The answer to that is to Fourier transform into the frequency domain: define
$$|\tilde\psi(\omega)\rangle=\int_{-\infty}^\infty\text dt \, e^{i\omega t}|\psi(t)\rangle$$
and see what the eigenvector decomposition does to it:
$$|\tilde\psi(\omega)\rangle
=\int_{-\infty}^\infty\text dt \, e^{i\omega t}\sum_n\psi_n e^{-ia_n t}|n\rangle
=\sum_n\psi_n|n\rangle \int_{-\infty}^\infty\text dt \, e^{i(\omega -a_n) t}
=\sum_n\delta(\omega -a_n)\psi_n|n\rangle .
$$
That is: the Fourier transform of the $\hat A$-induced flow is equal to a number of spikes at the eigenvalues of $\hat A$, and the eigenvectors are the coefficients.
To put it another way, this offers a means of obtaining the spectrum from the time evolution: solve it in some way, Fourier transform the solution, and then read the eigenvalues from the support of the transform and the eigenvectors from the value at those points. In fact, this is a useful technique and it has quite wide deployment in numerical solutions of certain classes of problems. (For more information, see David Tannor's excellent textbook Introduction to Quantum Mechanics: A Time-Dependent Perspective (Ebookee).)
... and, of course, if you tried to diagonalize in this way an operator with the kind of problems described above, you'd be heading straight for trouble. Surely it is unreasonable to ask the quantum flow to be well-behaved when the classical flow isn't!

A: Although Emilio's answer is insightful, I don't think it directly answers your question.  I'll attempt to do that here.  This answer proceeds in two parts:

*

*We'll show that the operator you try to write down is hermitian with appropriate domain, but that it is not self-adjoint and has no self-adjoint extensions.

*We'll show that your formal manipulations have errors.
Part 1.
We set $\hbar=1$ for convenience throughout, and let $S(\mathbb R)$ denote Schwartz space.  Recall that the $L^2(\mathbb R)$ inner product is defined as follows:
\begin{align}
  \langle \psi, \phi\rangle = \int_{-\infty}^{\infty} dx\, \psi^*(x) \phi(x)
\end{align}
We are going to use the following definition which appears on page 138 of Reed and Simon's Methods of Modern Mathematical Physics Volume II (Fourier analysis, self-adjointness):
Definition. For a symmetric operator $A$, we define its deficiency indices by
\begin{align}
  n_+(A) &= \dim\mathrm{ker}(iI-A^\dagger) \\
  n_-(A) &= \dim\mathrm{ker}(iI+A^\dagger) \\
\end{align}
We are also going to need the following result which is part of a corollary on page 141 of Reed and Simon:
Lemma. Let $A$ be a closed hermitian operator with deficiency indices $n_+(A)$ and $n_-(A)$, then $A$ is self-adjoint if and only if $n_+(A) = 0 = n_-(A)$, and $A$ has at least one self-adjoint extension if and only of $n_+(A) = n_-(A)$.
With this lemma, we can prove the following claim.  What we are going to prove here tells us that there is no way to define $H$ self-adjoint operator on some domain in $L^2(\mathbb R)$.
Claim. The operator $H$ with domain $D(A) = S(\mathbb R)$ defined by
\begin{align}
  H\psi(x) = -ix^3\frac{d\psi}{dx}(x) -i \frac{d}{dx} (x^3\psi(x))
\end{align}
is closed and hermitian but not self-adjoint.  Furthermore, $H$ has no self-adjoint extensions on $L^2(\mathbb R)$.
Proof. We will show that $A$ is hermitian and closed but that $n_-(H) = 1$ while $n_+(H) = 0$.  The desired result then follows immediately from the lemma.  To show that $H$ is hermitian, it suffices to show that $\langle \psi, H\phi\rangle = \langle H\psi, \phi\rangle$ for all $\phi,\psi\in D(H) = S(\mathbb R)$.  We have
\begin{align}
  \langle \psi, H\phi\rangle
  &= \int_{-\infty}^\infty dx\, \psi^*\left(-ix^3\frac{d\phi}{dx} -i \frac{d}{dx} (x^3\phi)\right) \\
  &= -2i\psi^*x^3\phi\Big|_{-\infty}^\infty +i\int_{-\infty}^\infty dx\left(\frac{d}{dx}(\psi^*x^3)+\frac{d\psi^*}{dx}(x)x^3\right)\phi \\
  &= \int_{-\infty}^\infty dx\left(-i\frac{d}{dx}(\psi(x)x^3)-i\frac{d\psi}{dx}x^3\right)^*\phi \\
  &= \langle H\psi, \phi\rangle.
\end{align}
The boundary term in the second equality vanished because $\phi$ is rapidly decreasing.  This operator is closed (admittedly this is actually something I haven't been able to prove).  Because $H$ is hermitian, its adjoint $H^\dagger$ has the same action on elements of its domain as $H$ itself.  Moreover, let $D'$ the set of all $\psi\in L^2(\mathbb R)$ for which $H\psi$ is well-defined and also an element of $L^2(\mathbb R)$.  Then the computation be performed above to demonstrate hermiticity shows that if $\phi\in D'$, then $\langle\phi, H\psi\rangle = \langle H\phi, \psi\rangle$ for all $\psi\in D(H)$, so $D(H^\dagger) = D'$.  In particular, this domain is larger than that of $H$ which is therefore not self-adjoint.
Now if $\psi\in \mathrm{ker}(iI - A^\dagger)$, then $\psi$ obeys the following differential equation:
\begin{align}
  i\psi - \left(-ix^3\frac{d\psi}{dx} -i \frac{d}{dx} (x^3\psi)\right)=0
\end{align}
This differential equation can be simplified to give
\begin{align}
  (1+3x^2)\psi + 2x^3\frac{d\psi}{dx} =0
\end{align}
for $x> 0$ and $x<0$, we can separate variables and integrate to solve this differential equation.  The result is (I used mathematica for this)
\begin{align}
  \psi_>(x) &= \frac{e^{1/(4x^2)}}{x^{3/2}} + c_> \\
  \psi_<(x) &= \frac{e^{1/(4x^2)}}{(-x)^{3/2}} + c_<
\end{align}
These solutions both diverge at the origin, so our differential equation does not yield an $L^2(\mathbb R)$ solution.  This gives $\mathrm{ker}(iI - A^\dagger) = \{0\}$ so $n_+(H) = 0$.  On the other hand, if $\psi\in \mathrm{ker}(iI + A^\dagger)$ then
\begin{align}
  i\psi + \left(-ix^3\frac{d\psi}{dx} -i \frac{d}{dx} (x^3\psi)\right)=0
\end{align}
This differential equation can be simplified to give
\begin{align}
  (1-3x^2)\psi - 2x^3\frac{d\psi}{dx} =0
\end{align}
which admits the normalized solution
\begin{align}
  \psi(x) =\left\{ \begin{array}{cc}
                \frac{1}{\sqrt{2}}\frac{1}{|x|^{3/2}}e^{-1/(4x^2)}   &, x\neq 0 \\
                0 &, x=0
              \end{array}\right.
\end{align}
In fact, this is (up to normalization) exactly the function you wrote down in the original question statement.  This function is in $D(H^\dagger)$.  It follows that $\mathrm{ker}(iI + A^\dagger) = \mathrm{span}\{\psi_1\}$ so that $n_-(H) = 1$, as desired $\blacksquare$.
Part 2.
As for you manipulations, even if you were to enlarge the domain of $H$ to include $\psi_\lambda$, they would be wrong.  Notice, for example, that you got a nonzero boundary term in the following computation:
\begin{align}
  \langle \psi_\lambda, H\psi_\lambda\rangle
  &= \int_{-\infty}^\infty dx\, \psi_\lambda^*\left(-ix^3\frac{d\psi_\lambda}{dx} -i \frac{d}{dx} (x^3\psi_\lambda)\right) \\
  &= -2i\psi_\lambda^*x^3\psi_\lambda\Big|_{-\infty}^\infty +i\int_{-\infty}^\infty dx\left(\frac{d}{dx}(\psi_\lambda^*x^3)+\frac{d\psi_\lambda^*}{dx}(x)x^3\right)\psi_\lambda \\
  &= -2i\,\mathrm{sgn}(x)e^{-\lambda/(2x^2)}\Big|_{-\infty}^\infty +i\int_{-\infty}^\infty dx\left(\frac{d}{dx}(\psi_\lambda^*x^3)+\frac{d\psi_\lambda^*}{dx}(x)x^3\right)\psi_\lambda \\
  &= -4i +\int_{-\infty}^\infty dx\left(-i\frac{d}{dx}(\psi(x)x^3)-i\frac{d\psi}{dx}x^3\right)^*\psi_\lambda \\
  &= -4i+\langle H\psi_\lambda, \psi_\lambda\rangle
\end{align}
which we could have seen more easily by simply noting that
\begin{align}
  \langle\psi_\lambda, \psi_\lambda\rangle = \frac{2}{\lambda}
\end{align}
which gives
\begin{align}
  \langle \psi_\lambda, H\psi_\lambda\rangle &= -i\lambda \langle\psi_\lambda, \psi_\lambda\rangle = -2i \\
  \langle H\psi_\lambda, \psi_\lambda\rangle &= (-i\lambda)^* \langle\psi_\lambda, \psi_\lambda\rangle = 2i
\end{align}
In particular, both of these computations show that
\begin{align}
  \langle \psi_\lambda, H\psi_\lambda\rangle \neq \langle H\psi_\lambda, \psi_\lambda\rangle
\end{align}
in contradiction with what you claim.


Q: A pack of 10 electronic components is known to include 3 defectives.
A pack of 10 electronic components is known to include 3 defectives.
  If 4 components are randomly chosen and tested , what is the
  probability of finding among them not more than one defective ?

I tried using binomial distribution.
$$ P(x=0) + P(x=1) $$
Now , $ P(x=0) = ^4C_0 * p^0 * q^4  $ , where $ p = (\frac{3}{10})$ and $q= (\frac{7}{10}) $
Similarly , $ P(x=1) = ^4C_1 * p^1 * q^3  $ , where $ p = (\frac{3}{10})$ and $q= (\frac{7}{10}) $
Am I doing it wrong ?

A: You have to use  the hypergeometric distribution, because it is without replacement.
$P(X=0)+P(X=1)=\frac{{7\choose 4}\cdot {3\choose 0}}{10\choose 4}+\frac{{7\choose 3}\cdot {3\choose 1}}{10\choose 4}$

A: The binomial distribution would be applicable if you were sampling with replacement, which is not the case here.
Let $N_0$ be the number of ways of selecting $0$ defective components, $N_1$ be the number of ways of selecting $1$ defective component.
$$N_0=\binom{3}{0}\binom{7}{4}=35$$
and
$$N_1=\binom{3}{1}\binom{7}{3}=105$$
while there are $\binom{10}{4}=210$ ways of choosing $4$ components from $10$.
Hence
$$\Pr[\le1\text{ defective}]=\frac{35+105}{210}=\frac{2}{3}$$


Q: Use MySQL Flask connection in different python file i have a app.py with:
from flask import FlasK
from flask_mysqldb import MySQL

# Objeto Flask
app = Flask(__name__)

# Secret key
app.secret_key = "appLogin"

# BD config
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'xxx'
app.config['MYSQL_PASSWORD'] = 'xxxx'
app.config['MYSQL_DB'] = 'feedlotdb'

# Obj MySQL
mysql = MySQL(app)

@app.route('/register', methods=["GET", "POST"])
def register():
   # USE BD
       sQuery = "INSERT INTO user (mail, password, name) VALUES (%s, %s, %s)"
       cur = mysql.connection.cursor()
       cur.execute(sQuery, (mail, password, name))
       mysql.connection.commit()

QUESTION:
I put part of the code above
How can I take "/Register" and encapsulate the user code there in a file like user.py and use the same sql.connection?
thx

A: you can create user.py and import mysql and app
users.py
from app import mysql
import app

from flask import Blueprint, render_template, abort

users_bp = Blueprint('users_bp', __name__)

@users_bp.route('/register', methods=["GET", "POST"])
def register():
       # USE BD
       sQuery = "INSERT INTO user (mail, password, name) VALUES (%s, %s, %s)"
       cur = mysql.connection.cursor()
       cur.execute(sQuery, (mail, password, name))
       mysql.connection.commit()

register blueprint in main app :-
from users import users_bp
app.register_blueprint(users_bp, url_prefix='/users')


Q: Moving average that takes into account NAs in value and gaps in available dates I'm working with a time series that spans 2008 to 2015, but am restricting attention to the months of March to August in each year. To further complicate the matter, some values have been marked NA.
Here's what a subset (not sorted by date) of the df looks like:
  Date       Value   Site
1 2008-08-20     NA  Kenya
2 2008-08-29 12.954  Kenya
3 2008-08-18 29.972  Kenya
4 2008-08-16  5.080  Kenya
5 2009-04-21  3.048  Kenya
6 2009-04-22 12.954  Kenya

Probably an unimportant detail since subsetting is pretty straightforward, but in the interest of clarifying the purpose of the Site column, I'll mention there are five sites in all with time series data over the same span.
I want to add a column Value10 that gives a 10-day moving average. I've found this can be easily accomplished using one of several packages such as zoo or TTR, but I want the moving average to be sensitive to the date and site so that it

*

*generates an NA for the day if any one of the previous 10 values produces an NA

*generates an NA for the day when the previous 10 values include a jump in the Date, e.g. going from August of 2008 to March of 2009.

*is sensitive to which Site's data it's acting on

A: The data in the question was replicated for Congo and we use a width of 2 instead of 10 so we can run this without having a trivial result of all NA:
# data for DF

Lines <- "  Date       Value   Site
2008-08-20     NA  Kenya
2008-08-29 12.954  Kenya
2008-08-18 29.972  Kenya
2008-08-16  5.080  Kenya
2009-04-21  3.048  Kenya
2009-04-22 12.954  Kenya
2008-08-20     NA  Congo
2008-08-29 12.954  Congo
2008-08-18 29.972  Congo
2008-08-16  5.080  Congo
2009-04-21  3.048  Congo
2009-04-22 12.954  Congo"

# set up DF, convert Date column to "Date" class

DF <- read.table(text = Lines, header = TRUE)
DF$Date <- as.Date(DF$Date)

Sort the rows and use ave to perform the rolling mean by Site and year/month:
# sort rows
o <- order(DF$Site, DF$Date)
DF <- DF[o, ]

# perform rolling mean
library(zoo)
# w <- 10
w <- 2
roll <- function(x) rollapplyr(c(rep(NA, w-1), x), w, mean)
DF$mean <- ave(DF$Value, DF$Site, as.yearmon(DF$Date), FUN = roll)

This gives:
> DF
         Date  Value  Site   mean
10 2008-08-16  5.080 Congo     NA
9  2008-08-18 29.972 Congo 17.526
7  2008-08-20     NA Congo     NA
8  2008-08-29 12.954 Congo     NA
11 2009-04-21  3.048 Congo     NA
12 2009-04-22 12.954 Congo  8.001
4  2008-08-16  5.080 Kenya     NA
3  2008-08-18 29.972 Kenya 17.526
1  2008-08-20     NA Kenya     NA
2  2008-08-29 12.954 Kenya     NA
5  2009-04-21  3.048 Kenya     NA
6  2009-04-22 12.954 Kenya  8.001

UPDATES  Rearranged presentation and added changed ave line to use yearmon.


Q: Add prefix to img src with Javascript/JQuery how can I add a prefix to every img src?

 Title 1

 Lorem Ipsum

 Title 2

 Lorem Ipsum

 Title 3

 Lorem Ipsum

Every img src should look like  this:

A: jQuery:
Using jQuery to change all images on page http://jsfiddle.net/aamir/FnPd5/
$('img').each(function(){ this.src='prefix/'+this.src })

jQuery way to find images on in divs starting with div_: http://jsfiddle.net/aamir/FnPd5/2/
jQuery("[id^='div_']").each(function(){
    var img = $(this).find('img')[0];
    img.src='prefix/'+img.src
})

Vanilla Javascript
Vanilla Javascript: http://jsfiddle.net/aamir/FnPd5/1/
var items = document.getElementsByTagName("img");
for (var i = items.length; i--;) {
    var img = items[i];
    img.src='prefix/'+img.src;
}

Vanilla Javascript to find images on in divs starting with div_: http://jsfiddle.net/aamir/FnPd5/3/
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++) {
    if(divs[i].id.indexOf('div_') == 0) {
        var img = divs[i].getElementsByTagName("img")[0];
        img.src='prefix/'+img.src;
    }
}

A: DEMO HERE
$("[id^='div_'] img").each(function(){
  var src = $(this).attr("src");
  var newSrc="prefix/"+src;
  $(this).attr("src",newSrc)
})

A: $(function(){
  $('img').each(function(i,e){
     $(e).attr('src','prefix/'+$(e).attr('src'));
  });
});

A: My solution based on your code:
$(document).ready(function(){
$('div div img').each(function(){
   var imagen = $(this).attr('src') ;
   $(this).attr("src","prefix/"+imagen);
});
});

Working fiddle: http://jsfiddle.net/robertrozas/kR5ZW/

A: Try this solution.
$('img').each(function(){
    var imgSrc = $(this).attr('src')
    $(this).attr('src','prefix/'+imgSrc);
})

Fiddle Demo

A: Another option:
$('img').attr('src', function(ii, oldSrc) {
    return 'prefix/' + oldSrc;
});

A: function addPrefixToImg(prefix) {
    $( "img" ).each(function( index ) {
        this.src = prefix + this.src;
    });
}

addPrefixToImg('prefix/');

you can test on http://jsfiddle.net/f32MQ/


Q: "OleDbException was unhandled...Syntax error in From clause" I am getting this error saying

OleDbException was unhandled...Syntax error in From clause

My code for login is given below.
Imports System.Data.OleDb

Public Class Login

Dim con As New OleDbConnection
Dim dt As New DataTable
Dim ds As New DataSet

Private Sub Login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Project work\anshu\fitness_0.1\Fitness.accdb"
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncancel.Click
    Me.Close()

End Sub

Private Sub btnlogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnlogin.Click

    If check() = True Then
        Main.Show()
        Me.Hide()
    Else
        MsgBox("Enter vailid Username and Password", MsgBoxStyle.Information, "Login Validation Information")
    End If

End Sub

Public Function check()
    ds.Tables.Add(dt)
    con.Open()
    Dim da As New OleDbDataAdapter("select * from User", con)
    da.Fill(dt) ---->here is the error!

    For Each DataRow In dt.Rows
        If txtname.Text = DataRow(1) And txtpass.Text = DataRow(2) Then
            con.Close()
            Return True

        End If
    Next
    con.Close()
    Return False

End Function

End Class

A: User is a reserved word and must be bracketed:
"select * from [User]"


Q: PHPEXCEL formula calculation issue The problem started in a very complex worksheet but I reduce it to a very simple but still having the same problem.
PHPExcel is not calculating the formula, but if I change to a simple one (=B3) it works.
The formula returned by getvalue() is
=IF(B3="","",IF(C8="N",IF(ISERR(VALUE(B3)),0,VALUE(B3)),T(B3)))

My code.
require_once dirname(__FILE__) . '/../phpxl/Classes/PHPExcel.php';
set_include_path(get_include_path() . PATH_SEPARATOR . '/../phpxl/Classes/');
$template = "test.xlsx";
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($template);
$objPHPExcel->getActiveSheet()->getCell('B3')->setValue(8);
$result = $objPHPExcel->getActiveSheet()->getCell('B8')->getCalculatedValue();
$result1 = $objPHPExcel->getActiveSheet()->getCell('B8')->getValue();
echo $result.'
';
echo $result1.'
';

I'm setting a value of 8 at the B3 cell, doing this in excel calculates the same value at B8.
C8 has an 'N'.
But with phpexcel I always get the value it was saved with (2.1)
Response:
2.1
=IF(B3="","",IF(C8="N",IF(ISERR(VALUE(B3)),0,VALUE(B3)),T(B3)))
Replacing in the excel file the formula at B8 to '=B3' it works perfectly showing the result '8'.
Response:
8
=B3
So I must think that is a problem with the formula.
The functions are quite simple IF, T, VALUE, ISERR.
Change all double quotation and the issue persists.
=IF(ISBLANK(B3),NA(),IF(C8="N",IF(ISERR(VALUE(B3)),0,VALUE(B3)),T(B3)))

Any idea to get a workaround to this will be welcome.
Tks

A: That's because (as listed in the documentation) the VALUE() function has not yet been implemented in the PHPExcel calculation engine


Q: Data file handling modify function error c++     class flight //main class flight which the user uses to book tickets
{

    int booking_id;
    int pnr,p_age;
    char p_name[25],d_a_name[25],a_a_name[25],gender,departing_date[10],arrival_date[10],b_id;
    long double price;
public:
    flight()
    {
        static int id=0;
        booking_id=id++;
    }

    void modfunction(int n);
};
void flight::modfunction(int n) //function for entering new values when the user has chosen to modify
{
    getchar();
    cout<<"Enter the passenger's name :";
    gets(p_name);
    cout<<"Enter the passenger age :";
    cin>>p_age;
    getchar();
    cout<<"Enter the passenger's gender :";
    cin>>gender;
    getchar();
    cout<<"Enter the departing date(dd-mm-yyyy) :";
    gets(departing_date);
    cout<<"Do you want to book return ticket with a 10% discount?(y/n) :";
    cin>>return_ticket_input;
    if(return_ticket_input=='y')
    {
        cout<<"Enter the arrival date :";
        gets(arrival_date);
    }
    cout<<"Choose the airline.\n\n";
    flights(departing_date,return_ticket_input,arrival_date);
    cout<<"\n\nEnter the desired flight number :";
    cin>>selected_fno;

}
void modify_ticket()//function for modifying a ticket
{
    int n;
    system("clear");
    cout<<"Enter the booking id for modification ";
    cin>>n;
    flight f;
    fstream fp("flight.dat",ios::binary);
    ifstream ifile("flight.dat",ios::binary);
    int found=0;
    int count_variable = 0;
    while(ifile.read((char*)&f,sizeof(f)))
    {
        if(n==f.retbid())
        {
            f.output();
            f.modfunction(n);
//            int s=sizeof(f) * (count_variable + 1);
            fp.seekp(ifile.tellg());
            fp.write((char*)&f,sizeof(f));
            found = 1;
            f.output();
            getchar();
        }
        count_variable++;
    }
    ifile.close();
    fp.close();

    if(found==0)
    {
        cout<<"Passenger not founed!";

    }
    cout<<"Press any key to continue.";
    getch();

}

So this is the minimal version of my problem.
The class named flight. a function called modfuction which is used to input data from the user. and another function called modify ticket used by the user to modify the record details.
The problem is even though the user enters the booking id(n) and it outputs the record, when the user tries to update it(modify) it stays the same!
please help me as this is a part of my school project!
thanks in advance!

A: Instead of fstream fp("flight.dat",ios::binary); write:
fstream fp("flight.dat",ios::binary|ios::in|ios::out);

P.S.: Encountered Same Problem A minute ago..


Q: Get access to result sets from one stored procedure inside another stored procedure I have stored procedure that have 5 Select statements and as I understand when I run it I get 5 result sets.
I'm also using Sql server reporting services to generate some reports.
I would like to run that stored procedure from ssrs and put there 3 of 5 result sets. I read that it is currently impossible because only one (top first) result set is taken by ssrs.
So my idea was to create second stored procedure that would execute first one and union 3 out of 5 result sets and return only one newly created result set. But I have no idea how to iterate/or get access to result sets in stored procedure from executed stored procedure.
Also when I execute stored procedure from stored procedure I can see that result sets from first one are also printed in sql server management studio so I believe that problem will be the same when moving to SSRS.
Do you have any hints on how can I access results sets from one stored procedure in another, manipulate them and make sure that only newly created result set will be returned so that I can use it in SSRS?
thanks!

A: You can declare a table variable or temp table to save your results. Then execute the other stored procedures and insert the results into that table. Then return the results of that table variable.
Example below.
CREATE OR ALTER PROC StoredProc1
AS
BEGIN

   SELECT
      1,
      'ValueColumn1SP1',
      'ValueColumn2';

END;
GO

CREATE OR ALTER PROC StoredProc2
AS
BEGIN

   SELECT
      1,
      'ValueColumn1SP2',
      'ValueColumn2';

END;
GO

CREATE OR ALTER PROC CombinedSP
AS
BEGIN

   /*create a table to store results, can also be an temp table*/
   DECLARE @CombinedResults TABLE
   (
      Id INT,
      Column1 VARCHAR(50),
      Column2 VARCHAR(50)
   );

   /*Execute first Stored Proc and enter results into table*/
   INSERT INTO @CombinedResults
   (
      Id,
      Column1,
      Column2
   )
   EXEC dbo.StoredProc1;

   /*Execute second Stored Proc and enter results into table*/
   INSERT INTO @CombinedResults
   (
      Id,
      Column1,
      Column2
   )
   EXEC dbo.StoredProc2;
   /*etc*/

   /*retrieve data*/
   SELECT *
   FROM   @CombinedResults AS cr;

END;
GO

/*execute combined SP*/
EXEC CombinedSP;


Q: How to sort this core data multithreading issue I have an app where I am using core data to store messages and contacts, the app was randomly crashing with error

Could not save. Error Domain=NSCocoaErrorDomain Code=132001 "(null)"
  UserInfo={message=attempt to recursively call -save: on the context
  aborted, stack trace=(    0   CoreData
  0x00000001920eb02c  + 164   1   Pop
  0x0000000100144528
  TFC3Pop23PopMainScreenController10savePersonfCSo9CNContactT + 5808    2
  Pop                                 0x0000000100142af8
  TFFC3Pop23PopMainScreenController27pullContactsFromAdreessBookFT8purgeOldSb_T_U_FTCSo9CNContactGSpV10ObjectiveC8ObjCBool__T
  + 88  3   Pop                                 0x0000000100142b60 TTRXFo_oCSo9CNContactdGSpV10ObjectiveC8ObjCBool___XFdCb_dS_dGSpS1___ +
  76    4   Contacts                            0x000000019886a898
   + 144  5   Contacts
  0x0000000198885588  + 96    6   CoreFoundation
  0x000000018fce1e24  + 132   7   CoreFoundation
  0x000000018fce1cb8  + 208   8   Contacts
  0x000000019888545c  + 420   9   Contacts
  0x000000019886a7fc  + 72    10  Pop
  0x00000001001426f4
  TFC3Pop23PopMainScreenController27pullContactsFromAdreessBookfT8purgeOldSb_T
  + 1732    11  Pop                                 0x0000000100134790 TFFC3Pop23PopMainScreenController17reloadAddressBookFT_T_U_FT_T + 60
    12  Pop                                 0x0000000100087f30
  TTRXFo___XFdCb__ + 44     13  libdispatch.dylib
  0x0000000101bb1a50 _dispatch_call_block_and_release + 24  14
  libdispatch.dylib                   0x0000000101bb1a10
  _dispatch_client_callout + 16     15  libdispatch.dylib                   0x0000000101bc17dc _dispatch_root_queue_drain + 980     16
  libdispatch.dylib                   0x0000000101bc139c
  _dispatch_worker_thread3 + 140    17  libsystem_pthread.dylib             0x000000018eeb31d0 _pthread_wqthread + 1096     18
  libsystem_pthread.dylib             0x000000018eeb2d7c start_wqthread
  + 4 )}, [AnyHashable("stack trace"): <_NSCallStackArray 0x17464f2d0>( 0   CoreData                            0x00000001920eb02c
  + 164, 1   Pop                                 0x0000000100144528 TFC3Pop23PopMainScreenController10savePersonfCSo9CNContactT + 5808, 2
  Pop                                 0x0000000100142af8
  TFFC3Pop23PopMainScreenController27pullContactsFromAdreessBookFT8purgeOldSb_T_U_FTCSo9CNContactGSpV10ObjectiveC8ObjCBool__T
  + 88, 3   Pop                                 0x0000000100142b60 TTRXFo_oCSo9CNContactdGSpV10ObjectiveC8ObjCBool___XFdCb_dS_dGSpS1___ +
  76, 4   Contacts                            0x000000019886a898
   + 144, 5   Contacts
  0x0000000198885588  + 96, 6   CoreFoundation
  0x000000018fce1e24  + 132, 7   CoreFoundation
  0x000000018fce1cb8  + 208, 8   Contacts
  0x000000019888545c  + 420, 9   Contacts
  0x000000019886a7fc  + 72, 10  Pop
  0x00000001001426f4
  TFC3Pop23PopMainScreenController27pullContactsFromAdreessBookfT8purgeOldSb_T
  + 1732, 11  Pop                                 0x0000000100134790 TFFC3Pop23PopMainScreenController17reloadAddressBookFT_T_U_FT_T + 60,
  12  Pop                                 0x0000000100087f30
  TTRXFo___XFdCb__ + 44, 13  libdispatch.dylib
  0x0000000101bb1a50 _dispatch_call_block_and_release + 24, 14
  libdispatch.dylib                   0x0000000101bb1a10
  _dispatch_client_callout + 16, 15  libdispatch.dylib                   0x0000000101bc17dc _dispatch_root_queue_drain + 980, 16
  libdispatch.dylib                   0x0000000101bc139c
  _dispatch_worker_thread3 + 140, 17  libsystem_pthread.dylib             0x000000018eeb31d0 _pthread_wqthread + 1096, 18
  libsystem_pthread.dylib             0x000000018eeb2d7c start_wqthread
  + 4 ) , AnyHashable("message"): attempt to recursively call -save: on the context aborted]
2017-07-02 22:43:09.192263-0700 Pop[4552:2232120] [error] error:
  Serious application error.  Exception was caught during Core Data
  change processing.  This is usually a bug within an observer of
  NSManagedObjectContextObjectsDidChangeNotification.  -[__NSCFSet
  addObject:]: attempt to insert nil with userInfo (null) CoreData:
  error: Serious application error.  Exception was caught during Core
  Data change processing.  This is usually a bug within an observer of
  NSManagedObjectContextObjectsDidChangeNotification.  -[__NSCFSet
  addObject:]: attempt to insert nil with userInfo (null) 2017-07-02
  22:43:09.192412-0700 Pop[4552:2232120] * Terminating app due to
  uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet
  addObject:]: attempt to insert nil'
  * First throw call stack: (0x18fdf2fd8 0x18e854538 0x18fdf2f20 0x18fd0f14c 0x1920ed268 0x1920ec230 0x1920e4f24 0x18fda09a0
  0x18fd9e628 0x18fd9ea74 0x18fcced94 0x191738074 0x195f87130
  0x1001031a0 0x18ecdd59c) libc++abi.dylib: terminating with uncaught
  exception of type NSException

So I enabled assertion to detect access to core data from wrong thread using com.apple.CoreData.ConcurrencyDebug 1
Now its showing assertion to every core data related operation.
Most of them I have resolved using newBackgroundContext and performBlockWait block.
But my question is why its assessing for every core data related operation ?


Q: Why is Corvo's mask Piero's greatest creation? In the series "Tales from Dunwall" there's an episode about Piero.
It states that Piero's greatest creation would be Corvo's mask. This is the guy that cured the rat plague and made a giant arc pylon and his greatest creation was a visually impressive mask with a couple of lenses in it?
It could be argued that it's the creation that had the most impact, but versus a cure for the rat plague? Seriously?

A: I know this isn't optimal, but lacking a copy of the game at the moment, I am forced to use Wikia as the source of my information.
Now, according to Wikia, the Arc Pylons are the brainchild of Anton Sokolov. Piero perfected their schematics, true, but he didn't invent them in the strictest sense.
Same goes for the plague elixir: Anton Sokolov had devised his own version. While Piero accuses Sokolov of stealing his research, in one ending of the game they work together to develop an actual cure for the plague.
The mask is different: it was devised by Piero alone, after being inspired by the Outsider. This is somewhat similar to how Mendeleev develop the periodic table after allegedly dreaming about it.
The mask is not just a couple of lenses: it has a telescopic-like feature, that doesn't only magnify the image, but also magnifies the sound - making it a perfect spying tool. I'm sure you will agree that the mask required much more skillful craftsmanship - fitting multiple magnifying glasses with movable parts in an apparently armored casing is no easy task, even now.
As an out-of-universe note, both the plague cure and the arc pylon have some real-world prototypes (see vaccines and Tesla coils). The mask does not.


Q: remove first text with shell script Please someone help me with this bash script,
lets say I have lots of files with url like below:
https://example.com/x/c-ark4TxjU8/mybook.zip
https://example.com/x/y9kZvVp1k_Q/myfilename.zip

My question is, how to remove all other text and leave only the file name?
I've tried to use the command described in this url How to delete first two lines and last four lines from a text file with bash?
But since the text is random which means it doesn't have exact numbers the code is not working.

A: You can use the sed utility to parse out just the filenames
sed 's_.*\/__'

A: You can use awk:
The easiest way that I find:
awk -F/ '{print $NF}' file.txt

or
awk -F/ '{print $6}' file.txt

You can also use sed:
sed 's;.*/;;' file.txt

You can use cut:
cut -d'/' -f6 file.txt


Q: Specify end of token with cin How can you specify the characters that end the reading of a token with cin?
Defaults to / t, / n, '' ...
But I want to specify some specifics in a similar way to what the std::skipws and std::noskipws or std::ws functions do that allow you to specify whether or not the spaces are ignored, I would like to know if there is something more general for allow read up to some specific character, reads until it finds a string that matches the data type of the variable in which it is to be stored with the >> operator, in order to read and cut the token up to ' '
So that when entering the string A,B,C,D E,F   G H,I, J
Each letter is a different string something similar to specifying with scanf ("% s,"...) to say that it expects a string followed by a comma that cuts the string but using cin.
Could someone help me?
Pd: It occurs to me to read the line and to replace ',' by ' ' in such a way that with stringstream I can do the extraction that I want, but this represents crossing the string twice and I look for something clean and efficient that provides the language or it is possible make it simple without much code.

A: No you cannot do that. Parse the input and depending on the input, implement your logic with if statements for example.


Q: How to pick out exactly the right string in my list of utterances? So I am working on a python script using NumPy and Pandas and NLTK to take utterances from the CHILDES Database's Providence Corpus.
For reference, the idea of my script is to populate a dataframe for each child in the corpus with their name, utterance containing a linguistic feature I'm looking for (negation types), their age when they said it, and their MLU when they said it.
Great.
Now the user will be able to go in after the dataframes have been filled with this information and tag each utterance as being of a particular category, and the console will print out the utterance they will tag with a line of context on either side (if they just see that the child said 'no' it's hard to tell what they meant by it without seeing what Mom said right before that or what someone said afterward).
So my trick is getting the lines of context. I have it set up with other methods in the program to make this all happen, but I'd like you to look at one segment of one of the methods for populating the dataframes initially, as the line which says:
"if line == line_context:", is providing about 91 false positives for me!
I know why, because I'm making a temporary copy line by line of each file so that for each utterance that ends up having a negation, that utterance's index in the child's dataframe will be used as the key in a HashMap (or dict in Python) to a list of three Strings (well, lists of strings, since that's how the CHILDESCorpusReader gives me the sentences), the utterance, the utterance before it, and the utterance after it...
So I have that buggy line "if line == line_context" to check that as it's iterating through the list of lists of strings (a copy of the file's utterances by line, or 'line_context'), that it lines up with 'line', or the line of the kid's utterance that's being iterated through, so that later I can get the indexes to match up.
The problem is that there are many of these 'sentences' that are the same sequence of characters, (['no'] by itself shows up a lot!) so my program will see it as being the same, see it has a negation, and save it to the dataframe, but it'll save it each time it finds an instance of ['no'] in my copy of the file's utterances that's the same as one of the line's of only the child's speech in that file, so I'm getting about 91 extra instances of the same thing!
Phew! Anyway, is there any way that I can get something like "if line == line_context" to pick out a single instance of ['no'] in the file, so that I know I'm at the same point in the file on both sides??? I'm using the NLTK CHILDESCorpusReader, which doesn't seem to have resources for this kind of stuff (otherwise I wouldn't have to use this ridiculously roundabout way to get the lines of context!)
Maybe there's a way that as I iterate through the utterance_list I'm making for each file, after an utterance has been matched up with the child's utterances I'm also iterating through, I can change and/or delete that item in the utterance_list so as to prevent it from giving me a false positive c. 91 more times?!
Thanks.
Here is le code (I added some extra comments to hopefully help you understand exactly what each line is supposed to do):
for file in value_corpus.fileids(): #iterates through the .xml files in the corpus_map
    for line_total in value_corpus.sents(fileids=file, speaker='ALL'): #creates a copy of the utterances by all speakers
        utterance_list.append(line_total) #adds each line from the file to the list
    for line_context in utterance_list: #iterates through the newly created list
        for line in value_corpus.sents(fileids=file, speaker='CHI'): #checks through the original file's list of children's utterances
            if line == line_context: #tries to make sure that for each child's utterance, I'm at the point in the embedded for loop where the utterance in my utterance_list and the utterance in the file of child's sentences is the same exact sentence BUGGY(many lines are the same --> false positives)
                for type in syntax_types: #iterates through the negation syntactic types
                    if type in line: #if the line contains a negation
                        value_df.iat[i,5] = type #populates the "Syntactic Type" column
                        value_df.iat[i,3] = line #populates the "Utterance" column
                        MLU = str(value_corpus.MLU(fileids=file, speaker='CHI'))
                        MLU = "".join(MLU)
                        value_df.iat[i,2] =  MLU #populates the "MLU" column
                        value_df.iat[i,1] = value_corpus.age(fileids=file, speaker='CHI',month=True) #populates the "Ages" column
                        utterance_index = utterance_list.index(line_context)
                        try:
                            before_line = utterance_list[utterance_index - 1]
                        except IndexError: #if no line before, doesn't look for context
                            before_line = utterance_list[utterance_index]
                        try:
                            after_line = utterance_list[utterance_index + 1]
                        except IndexError: #if no line after, doesn't look for context
                            after_line = utterance_list[utterance_index]
                            value_dict[i] = [before_line, line, after_line]
                            i = i + 1 #iterates to next row in "Utterance" column of df


Q: Can I run UnitTests on all devices and UITests only on iOS 9.x devices in Xcode Server? So I spent some time on implementing the first UITests in Xcode 7 to automatically test the main workflows in our app. And everything went fine locally.
However, when I pushed the UITests to the C.I. (Xcode Server) the build broke with the following log message:

xcodebuild: error: Failed to build workspace mycoolapp with scheme
  mycoolapp.
Reason: UI Testing is not supported on “iPad 2” because it
  is running iOS Simulator 8.1 and UI Testing requires iOS Simulator 9.0
  or later.
4.684 (4.687) seconds Test Suite 'mycoolappUITests.xctest' failed at 2015-10-14 11:21:45.242.
  Executed 2 tests, with 2 failures (0 unexpected) in 12.217 (12.229) seconds

So what I understand is that UITests are only supported by iOS 9.x devices (which is reasonable).
What I don't understand is that I can't seem to configure the Xcode Bot to only run UITests on certain devices and UnitTests on all devices.
Am I right about this or is there a configuration option I'm missing? Did anybody run into the same problem?

A: I reckon you should be able to create a new scheme to run your UI Tests and uncheck unit tests from the Test action in Edit Scheme.

Later you can configure your new bot settings be specifying the UI Test scheme, selecting the "Perform test action" and select the iOS9 devices connected to your server.
You can continue to run unit tests with existing bot on all iOS devices and simulators.


Q: Erroneous element error with mapstruct and OpenAPI While trying to convert the java model generated by openapi-generator with MapStruct getting the following exception

error: No implementation was created for EmployeeMapper due to having
a problem in the erroneous element
org.openapitools.jackson.nullable.JsonNullable. Hint: this often means
that some other annotation processor was supposed to process the
erroneous element. You can also enable MapStruct verbose mode by
setting -Amapstruct.verbose=true as a compilation argument.

A: The problem was the generated java files having the unused import
org.openapitools.jackson.nullable.JsonNullable

So while generating the code using openapi-generator passed the following config to ignore the JsonNullable import.
"openApiNullable": false


Q: Is scalebase nosql database or not? I have read about scalebase but did not understand is it NoSQL database or not? Or they just well horizontal scaled SQL database?

A: Per wikipedia (https://en.wikipedia.org/wiki/ScaleBase) it is a distributed MySQL implementation. It supports SQL. So, by definition, it doesn't qualify as "NoSQL"