问:
Why Is my implementation of io_service::run_one() causing an indefinite block and triggering error #125?
I am using BOOST for asynchronous communication with a serial port. I can't pinpoint the cause of the error I am facing and would appreciate some guidance.

```<code>std::string myclass::readStringUntil(const std::string& delim)
{
    setupParameters=ReadSetupParameters(delim);
    performReadSetup(setupParameters);

if(timeout!=posix_time::seconds(0)) timer.expires_from_now(timeout);
else timer.expires_from_now(posix_time::hours(100000));

timer.async_wait(boost::bind(&myclass::timeoutExpired,this,
            asio::placeholders::error));

result=resultInProgress;
bytesTransferred=0;
for(;;)
{
    io.run_one();
    switch(result)
    {
        case resultSuccess:
            {
                timer.cancel();
                bytesTransferred-=delim.size();//Don't count delim
                istream is(&readData);
                string result(bytesTransferred,'\0');//Alloc string
                is.read(&result[0],bytesTransferred);//Fill values
                is.ignore(delim.size());//Remove delimiter from stream
                return result;
            }
        case resultTimeoutExpired:
            port.cancel();
            throw(timeout_exception("Timeout expired"));
            cout<<"timeout on readuntill"<<endl;
        case resultError:
            timer.cancel();
            port.cancel();
            throw(boost::system::system_error(boost::system::error_code(),
                    "Error while reading"));
    }
}

/////////////////////////////////////////////////////////////////////////////

void myclass::performReadSetup(const ReadSetupParameters& param)
{
if(param.fixedSize)
{
    asio::async_read(port,asio::buffer(param.data,param.size),boost::bind(
            &myclass::readCompleted,this,asio::placeholders::error,
            asio::placeholders::bytes_transferred));
} else {
    asio::async_read_until(port,readData,param.delim,boost::bind(
            &myclass::readCompleted,this,asio::placeholders::error,
            asio::placeholders::bytes_transferred));
}
}

/////////////////////////////////////////////////////////////////////////////

void myclass::timeoutExpired(const boost::system::error_code& error)
{
 if(!error && result==resultInProgress) result=resultTimeoutExpired;
}

/////////////////////////////////////////////////////////////////////////////

void myclass::readCompleted(const boost::system::error_code& error,
    const size_t bytesTransferred)
{
if(!error)
{
    result=resultSuccess;
    this->bytesTransferred=bytesTransferred;
    return;
}

#ifdef _WIN32
if(error.value()==995) return; //Windows spits out error 995
#elif defined(__APPLE__)
if(error.value()==45)
{
    //Bug on OS X, it might be necessary to repeat the setup
    //http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
    performReadSetup(setupParameters);
    return;
}
#else //Linux
if(error.value()==125) return; //Linux outputs error 125
#endif

result=resultError;
}
</code>```

Without io.run_one(), I go into an infinite loop and not entering the switch case.

How could I fixed my code so that it gets out of the indefinite block? I can't confirm, but I think the run_one() is causing an error#125

答:
First off, error 125 is operation aborted: so that would mean (probably) a cancel() call (or the destructor of the io object causing cancellation).

That's just normal.

I've painstakenly completed your incomplete code¹ and don't readily see your problem:

Live On Coliru

```<code>#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>

struct myclass {
    struct timeout_exception : std::runtime_error {
        timeout_exception(std::string const &msg) : std::runtime_error(msg) {}
    };

    enum {
        resultInProgress,
        resultTimeoutExpired,
        resultSuccess,
        resultError,
    } result = resultInProgress;

    std::string readStringUntil(std::string const &);
    struct ReadSetupParameters {
        ReadSetupParameters(std::string const &d = "") : delim{ d } {}
        std::string delim;
        bool fixedSize = false;
        char mutable data[1024];
        size_t size = sizeof(data);
    };

    void performReadSetup(const ReadSetupParameters &param);

    ReadSetupParameters setupParameters;
    boost::posix_time::time_duration timeout{ boost::posix_time::seconds(3) };
    boost::asio::io_service io;
    boost::asio::deadline_timer timer{ io };

    // more likely a serial port, but I'm not gonna bother mocking that:
    boost::asio::ip::tcp::socket port{ io };
    boost::asio::streambuf readData;
    size_t bytesTransferred;

    myclass() { port.connect({ {}, 6767 }); }

    void timeoutExpired(boost::system::error_code const &ec);
    void readCompleted(boost::system::error_code const &ec, size_t bytesTransferred);
};

std::string myclass::readStringUntil(const std::string &delim) {
    using namespace boost;

    setupParameters = ReadSetupParameters(delim);
    performReadSetup(setupParameters);

    if (timeout != posix_time::seconds(0))
        timer.expires_from_now(timeout);
    else
        timer.expires_from_now(posix_time::hours(100000));

    timer.async_wait(boost::bind(&myclass::timeoutExpired, this, asio::placeholders::error));

    result = resultInProgress;
    for (;;) {
        io.run_one();
        switch (result) {
        case resultSuccess: {
            timer.cancel();
            bytesTransferred -= delim.size(); // Don't count delim
            std::istream is(&readData);
            std::string result(bytesTransferred, '\0'); // Alloc string
            is.read(&result[0], bytesTransferred);      // Fill values
            is.ignore(delim.size());                    // Remove delimiter from stream
            return result;
        } break;
        case resultTimeoutExpired:
            port.cancel();
            std::cout << "timeout on readuntill" << std::endl;
            throw(timeout_exception("Timeout expired"));
            break;
        case resultError:
            timer.cancel();
            port.cancel();
            throw(boost::system::system_error(boost::system::error_code(), "Error while reading"));
        }
    }
}

/////////////////////////////////////////////////////////////////////////////

void myclass::performReadSetup(const ReadSetupParameters &param) {
    using namespace boost;
    if (param.fixedSize) {
        asio::async_read(port, asio::buffer(param.data, param.size),
                         boost::bind(&myclass::readCompleted, this, asio::placeholders::error,
                                     asio::placeholders::bytes_transferred));
    } else {
        asio::async_read_until(port, readData, param.delim,
                               boost::bind(&myclass::readCompleted, this, asio::placeholders::error,
                                           asio::placeholders::bytes_transferred));
    }
}

/////////////////////////////////////////////////////////////////////////////

void myclass::timeoutExpired(const boost::system::error_code &error) {
    if (!error && result == resultInProgress)
        result = resultTimeoutExpired;
}

/////////////////////////////////////////////////////////////////////////////

void myclass::readCompleted(const boost::system::error_code &error, const size_t bytesTransferred) {
    if (!error) {
        result = resultSuccess;
        this->bytesTransferred = bytesTransferred;
        return;
    }

#ifdef _WIN32
    if (error.value() == 995)
        return; // Windows spits out error 995
#elif defined(__APPLE__)
    if (error.value() == 45) {
        // Bug on OS X, it might be necessary to repeat the setup
        // http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
        performReadSetup(setupParameters);
        return;
    }
#else // Linux
    if (error.value() == 125)
        return; // Linux outputs error 125
#endif

    result = resultError;
}

int main() {
    myclass absent;
    std::cout << "Ok: '" << absent.readStringUntil("Transferred") << "'\n";
}
</code>```

Notes:

it looks as if you're basically trying really hard to avoid asynch calls at all. This is making things clumsy. If all you need is the timeout, see Boost::Asio synchronous client with timeout and boost::asio + std::future - Access violation after closing socket

you seem unaware that *read_until can read beyond the delimiter (it will read at least up to and including the first time it sees the delimiter). You should really account for it

You never check the return value for run_one(). If it returns 0 the loop should exit. Running it again without performing a reset() will never do anything.

¹ why?

Body:
I am using BOOST for asynchronous communication with a serial port. I can't pinpoint the cause of the error I am facing and would appreciate some guidance.

std::string myclass::readStringUntil(const std::string& delim)
{
    setupParameters=ReadSetupParameters(delim);
    performReadSetup(setupParameters);

if(timeout!=posix_time::seconds(0)) timer.expires_from_now(timeout);
else timer.expires_from_now(posix_time::hours(100000));

timer.async_wait(boost::bind(&myclass::timeoutExpired,this,
            asio::placeholders::error));

result=resultInProgress;
bytesTransferred=0;
for(;;)
{
    io.run_one();
    switch(result)
    {
        case resultSuccess:
            {
                timer.cancel();
                bytesTransferred-=delim.size();//Don't count delim
                istream is(&readData);
                string result(bytesTransferred,'\0');//Alloc string
                is.read(&result[0],bytesTransferred);//Fill values
                is.ignore(delim.size());//Remove delimiter from stream
                return result;
            }
        case resultTimeoutExpired:
            port.cancel();
            throw(timeout_exception("Timeout expired"));
            cout<<"timeout on readuntill"<<endl;
        case resultError:
            timer.cancel();
            port.cancel();
            throw(boost::system::system_error(boost::system::error_code(),
                    "Error while reading"));
    }
}

/////////////////////////////////////////////////////////////////////////////

void myclass::performReadSetup(const ReadSetupParameters& param)
{
if(param.fixedSize)
{
    asio::async_read(port,asio::buffer(param.data,param.size),boost::bind(
            &myclass::readCompleted,this,asio::placeholders::error,
            asio::placeholders::bytes_transferred));
} else {
    asio::async_read_until(port,readData,param.delim,boost::bind(
            &myclass::readCompleted,this,asio::placeholders::error,
            asio::placeholders::bytes_transferred));
}
}

/////////////////////////////////////////////////////////////////////////////

void myclass::timeoutExpired(const boost::system::error_code& error)
{
 if(!error && result==resultInProgress) result=resultTimeoutExpired;
}

/////////////////////////////////////////////////////////////////////////////

void myclass::readCompleted(const boost::system::error_code& error,
    const size_t bytesTransferred)
{
if(!error)
{
    result=resultSuccess;
    this->bytesTransferred=bytesTransferred;
    return;
}

#ifdef _WIN32
if(error.value()==995) return; //Windows spits out error 995
#elif defined(__APPLE__)
if(error.value()==45)
{
    //Bug on OS X, it might be necessary to repeat the setup
    //http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
    performReadSetup(setupParameters);
    return;
}
#else //Linux
if(error.value()==125) return; //Linux outputs error 125
#endif

result=resultError;
}

Without io.run_one(), I go into an infinite loop and not entering the switch case.

How could I fixed my code so that it gets out of the indefinite block? I can't confirm, but I think the run_one() is causing an error#125

Body:
First off, error 125 is operation aborted: so that would mean (probably) a cancel() call (or the destructor of the io object causing cancellation).

That's just normal.

I've painstakenly completed your incomplete code¹ and don't readily see your problem:

Live On Coliru

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>

struct myclass {
    struct timeout_exception : std::runtime_error {
        timeout_exception(std::string const &msg) : std::runtime_error(msg) {}
    };

    enum {
        resultInProgress,
        resultTimeoutExpired,
        resultSuccess,
        resultError,
    } result = resultInProgress;

    std::string readStringUntil(std::string const &);
    struct ReadSetupParameters {
        ReadSetupParameters(std::string const &d = "") : delim{ d } {}
        std::string delim;
        bool fixedSize = false;
        char mutable data[1024];
        size_t size = sizeof(data);
    };

    void performReadSetup(const ReadSetupParameters &param);

    ReadSetupParameters setupParameters;
    boost::posix_time::time_duration timeout{ boost::posix_time::seconds(3) };
    boost::asio::io_service io;
    boost::asio::deadline_timer timer{ io };

    // more likely a serial port, but I'm not gonna bother mocking that:
    boost::asio::ip::tcp::socket port{ io };
    boost::asio::streambuf readData;
    size_t bytesTransferred;

    myclass() { port.connect({ {}, 6767 }); }

    void timeoutExpired(boost::system::error_code const &ec);
    void readCompleted(boost::system::error_code const &ec, size_t bytesTransferred);
};

std::string myclass::readStringUntil(const std::string &delim) {
    using namespace boost;

    setupParameters = ReadSetupParameters(delim);
    performReadSetup(setupParameters);

    if (timeout != posix_time::seconds(0))
        timer.expires_from_now(timeout);
    else
        timer.expires_from_now(posix_time::hours(100000));

    timer.async_wait(boost::bind(&myclass::timeoutExpired, this, asio::placeholders::error));

    result = resultInProgress;
    for (;;) {
        io.run_one();
        switch (result) {
        case resultSuccess: {
            timer.cancel();
            bytesTransferred -= delim.size(); // Don't count delim
            std::istream is(&readData);
            std::string result(bytesTransferred, '\0'); // Alloc string
            is.read(&result[0], bytesTransferred);      // Fill values
            is.ignore(delim.size());                    // Remove delimiter from stream
            return result;
        } break;
        case resultTimeoutExpired:
            port.cancel();
            std::cout << "timeout on readuntill" << std::endl;
            throw(timeout_exception("Timeout expired"));
            break;
        case resultError:
            timer.cancel();
            port.cancel();
            throw(boost::system::system_error(boost::system::error_code(), "Error while reading"));
        }
    }
}

/////////////////////////////////////////////////////////////////////////////

void myclass::performReadSetup(const ReadSetupParameters &param) {
    using namespace boost;
    if (param.fixedSize) {
        asio::async_read(port, asio::buffer(param.data, param.size),
                         boost::bind(&myclass::readCompleted, this, asio::placeholders::error,
                                     asio::placeholders::bytes_transferred));
    } else {
        asio::async_read_until(port, readData, param.delim,
                               boost::bind(&myclass::readCompleted, this, asio::placeholders::error,
                                           asio::placeholders::bytes_transferred));
    }
}

/////////////////////////////////////////////////////////////////////////////

void myclass::timeoutExpired(const boost::system::error_code &error) {
    if (!error && result == resultInProgress)
        result = resultTimeoutExpired;
}

/////////////////////////////////////////////////////////////////////////////

void myclass::readCompleted(const boost::system::error_code &error, const size_t bytesTransferred) {
    if (!error) {
        result = resultSuccess;
        this->bytesTransferred = bytesTransferred;
        return;
    }

#ifdef _WIN32
    if (error.value() == 995)
        return; // Windows spits out error 995
#elif defined(__APPLE__)
    if (error.value() == 45) {
        // Bug on OS X, it might be necessary to repeat the setup
        // http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
        performReadSetup(setupParameters);
        return;
    }
#else // Linux
    if (error.value() == 125)
        return; // Linux outputs error 125
#endif

    result = resultError;
}

int main() {
    myclass absent;
    std::cout << "Ok: '" << absent.readStringUntil("Transferred") << "'\n";
}

Notes:

it looks as if you're basically trying really hard to avoid asynch calls at all. This is making things clumsy. If all you need is the timeout, see Boost::Asio synchronous client with timeout and boost::asio + std::future - Access violation after closing socket

you seem unaware that *read_until can read beyond the delimiter (it will read at least up to and including the first time it sees the delimiter). You should really account for it

You never check the return value for run_one(). If it returns 0 the loop should exit. Running it again without performing a reset() will never do anything.

¹ why?


来源: stackexchange

问:
Multiple "order by" in LINQ
I have two tables, movies and categories, and I want to get an ordered list by categoryID first and then by Name.

The movie table has three columns ID, Name and CategoryID.
The category table has two columns ID and Name.

I tried something like the following, but it didn't work.

```<code>var movies = _db.Movies.OrderBy( m => { m.CategoryID, m.Name })
</code>```

答:
I have created some extension methods (below) so you don't have to worry if an IQueryable is already ordered or not. If you want to order by multiple properties just do it as follows:

```<code>// We do not have to care if the queryable is already sorted or not.
// The order of the Smart* calls defines the order priority
queryable.SmartOrderBy(i => i.Property1).SmartOrderByDescending(i => i.Property2);
</code>```

This is especially helpful if you create the ordering dynamically, f.e. from a list of properties to sort.

```<code>public static class IQueryableExtension
{
    public static bool IsOrdered<T>(this IQueryable<T> queryable) {
        if(queryable == null) {
            throw new ArgumentNullException("queryable");
        }

        return queryable.Expression.Type == typeof(IOrderedQueryable<T>);
    }

    public static IQueryable<T> SmartOrderBy<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
        if(queryable.IsOrdered()) {
            var orderedQuery = queryable as IOrderedQueryable<T>;
            return orderedQuery.ThenBy(keySelector);
        } else {
            return queryable.OrderBy(keySelector);
        }
    }

    public static IQueryable<T> SmartOrderByDescending<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
        if(queryable.IsOrdered()) {
            var orderedQuery = queryable as IOrderedQueryable<T>;
            return orderedQuery.ThenByDescending(keySelector);
        } else {
            return queryable.OrderByDescending(keySelector);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Multiple "order by" in LINQ

Body:
I have two tables, movies and categories, and I want to get an ordered list by categoryID first and then by Name.

The movie table has three columns ID, Name and CategoryID.
The category table has two columns ID and Name.

I tried something like the following, but it didn't work.

var movies = _db.Movies.OrderBy( m => { m.CategoryID, m.Name })

Body:
I have created some extension methods (below) so you don't have to worry if an IQueryable is already ordered or not. If you want to order by multiple properties just do it as follows:

// We do not have to care if the queryable is already sorted or not.
// The order of the Smart* calls defines the order priority
queryable.SmartOrderBy(i => i.Property1).SmartOrderByDescending(i => i.Property2);

This is especially helpful if you create the ordering dynamically, f.e. from a list of properties to sort.

public static class IQueryableExtension
{
    public static bool IsOrdered<T>(this IQueryable<T> queryable) {
        if(queryable == null) {
            throw new ArgumentNullException("queryable");
        }

        return queryable.Expression.Type == typeof(IOrderedQueryable<T>);
    }

    public static IQueryable<T> SmartOrderBy<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
        if(queryable.IsOrdered()) {
            var orderedQuery = queryable as IOrderedQueryable<T>;
            return orderedQuery.ThenBy(keySelector);
        } else {
            return queryable.OrderBy(keySelector);
        }
    }

    public static IQueryable<T> SmartOrderByDescending<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
        if(queryable.IsOrdered()) {
            var orderedQuery = queryable as IOrderedQueryable<T>;
            return orderedQuery.ThenByDescending(keySelector);
        } else {
            return queryable.OrderByDescending(keySelector);
        }
    }
}

ContentLicense: CC BY-SA 3.0


问:
parsing xml data return empty value in php
i'm trying to parse data in xml with simple_load_string function in php and it's return an empty data in the $parsed (data parsed) .

the data to parse is like :

```<code><cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
    <cas:authenticationSuccess>
        <cas:user>yassine458</cas:user>
    </cas:authenticationSuccess>
</cas:serviceResponse>
</code>```

is that possible to parse data with this format or there is another method to do it .

this is my code :

```<code>$xml = simplexml_load_string($result);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$parsed= simplexml_load_string($result);
</code>```

i'm trying to convert it to json format

答:
i find this solution :

```<code>$todelete="xmlns:cas=\"http://www.yale.edu/tp/cas\"";

        $result="<cas:serviceResponse xmlns:cas=\"http://www.yale.edu/tp/cas\">
                    <cas:authenticationSuccess>
                     <cas:user>pdurant2</cas:user>
                      </cas:authenticationSuccess>
                        </cas:serviceResponse>";
        if (strpos($result, $todelete) !== false) {
            $result= str_replace($todelete,null,$result);
        }
        if (strpos($result, "cas:") !== false) {
            $result= str_replace("cas:",null,$result);

        }
        if (strpos($result, "/cas:") !== false) {
            $result= str_replace("/cas:",null,$result);

        }
        $parsed=simplexml_load_string($result);
</code>```

and it's work for me .

Body:
i'm trying to parse data in xml with simple_load_string function in php and it's return an empty data in the $parsed (data parsed) .

the data to parse is like :

<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">
    <cas:authenticationSuccess>
        <cas:user>yassine458</cas:user>
    </cas:authenticationSuccess>
</cas:serviceResponse>

is that possible to parse data with this format or there is another method to do it .

this is my code :

$xml = simplexml_load_string($result);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$parsed= simplexml_load_string($result);

i'm trying to convert it to json format

Body:
i find this solution :

$todelete="xmlns:cas=\"http://www.yale.edu/tp/cas\"";

        $result="<cas:serviceResponse xmlns:cas=\"http://www.yale.edu/tp/cas\">
                    <cas:authenticationSuccess>
                     <cas:user>pdurant2</cas:user>
                      </cas:authenticationSuccess>
                        </cas:serviceResponse>";
        if (strpos($result, $todelete) !== false) {
            $result= str_replace($todelete,null,$result);
        }
        if (strpos($result, "cas:") !== false) {
            $result= str_replace("cas:",null,$result);

        }
        if (strpos($result, "/cas:") !== false) {
            $result= str_replace("/cas:",null,$result);

        }
        $parsed=simplexml_load_string($result);

and it's work for me .


问:
Section with background image expanding to overall sidebar
I am currently building a web page and encountered the following problem and would appreciate if someone helped me solve it:

I want to have a full-width background image for every "section" (div) of the page. Within this background, there is a smaller div for content (text). On the right, there is a scrolling sidebar which scrolls with the user. I could not find how to have a full-width div and the sidebar(which is a div element with descendants) going over it?

The current structure looks like:

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      here go all the "sections"...

      and that is the sidebar...

```

So in short, what is needed is background images with some html content on top of them and a sidebar on the right (but being covered by the image). Thank you in advance!

答:
You need to create a div outside of your container class. That div can be set to a full width.</p>

```<code>    <div class="row"> <!-- begins full width row-->

      <div class="container">
         <div class="col-md-9">
             here go all the "sections"...
         </div>
         <div class="col-md-3">
          and that is the sidebar...
         </div>
      </div>

    </div><!-- ends full width row-->
</code>```

Body:
I am currently building a web page and encountered the following problem and would appreciate if someone helped me solve it:

I want to have a full-width background image for every "section" (div) of the page. Within this background, there is a smaller div for content (text). On the right, there is a scrolling sidebar which scrolls with the user. I could not find how to have a full-width div and the sidebar(which is a div element with descendants) going over it?

The current structure looks like:

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      here go all the "sections"...

      and that is the sidebar...

So in short, what is needed is background images with some html content on top of them and a sidebar on the right (but being covered by the image). Thank you in advance!

Body:
You need to create a div outside of your container class. That div can be set to a full width.

    <div class="row"> <!-- begins full width row-->

      <div class="container">
         <div class="col-md-9">
             here go all the "sections"...
         </div>
         <div class="col-md-3">
          and that is the sidebar...
         </div>
      </div>

    </div><!-- ends full width row-->


问:
I need to know how many times temperatures;20 & 30 are crossed in the given data set 'Tair' using R
This is what I have done

```<code>maxT<-c(20,30)
Tair<-c(28.8,0,0,28.8,29.1,28.5,28.7,28.2,28.3,28.8,30.1,31.3,30.7,31.9,31.5,30.7,32,33,33,33.6,33.7,32.4,32.7,30.5,27.4,27.1,25.9,26.2,28.3,29.8,30.8,31.4,32)
dmx<-c(0)
 for (i in maxT)
 {
   for (j in Tair)
   {
     if(j>i){dmx=dmx+1}
   }
   dmx
 }
}
</code>```

When I run the above given script, It returns a single value for 'dmax' which is a sum of times temperatures crosses 20 and 30.
Thanks in advance.

答:
```<code>dmx <- sapply(1:length(maxT), function(x) sum(Tair) >= maxT[x]))
</code>```

This gives me:

```<code>31 17
</code>```

Body:
This is what I have done

maxT<-c(20,30)
Tair<-c(28.8,0,0,28.8,29.1,28.5,28.7,28.2,28.3,28.8,30.1,31.3,30.7,31.9,31.5,30.7,32,33,33,33.6,33.7,32.4,32.7,30.5,27.4,27.1,25.9,26.2,28.3,29.8,30.8,31.4,32)
dmx<-c(0)
 for (i in maxT)
 {
   for (j in Tair)
   {
     if(j>i){dmx=dmx+1}
   }
   dmx
 }
}

When I run the above given script, It returns a single value for 'dmax' which is a sum of times temperatures crosses 20 and 30.
Thanks in advance.

Body:
dmx <- sapply(1:length(maxT), function(x) sum(Tair) >= maxT[x]))

This gives me:

31 17


问:
The import org.zeromq cannot be resolved, what can I do?
The import org.zeromq cannot be resolved, what can I do?

Im trying to Subscribe ZMQ for my web app. First time working with ZMQ and im getting a little frusty. Can anybody help?

It has been a while since I used Java the last time.

```<code>import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Context;
import org.zeromq.ZMQ.Socket;

/**
* Pubsub envelope subscriber
*/

public class psenvsub {

    public static void main (String[] args) {

        // Prepare our context and subscriber
        Context context = ZMQ.context(1);
        Socket subscriber = context.socket(ZMQ.SUB);

        subscriber.connect("tcp://localhost:5563");
        subscriber.subscribe("B".getBytes());
        while (!Thread.currentThread ().isInterrupted ()) {
            // Read envelope with address
            String address = subscriber.recvStr ();
            // Read message contents
            String contents = subscriber.recvStr ();
            System.out.println(address + " : " + contents);
        }
        subscriber.close ();
        context.term ();
    }
}
</code>```

答:
You need to have zeromq implementation. Looks like there are multiple implementations in maven central: https://mvnrepository.com/artifact/org.zeromq

This POM should resolve imports:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>zmq</groupId>
    <artifactId>zmq-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.zeromq/jeromq -->
        <dependency>
            <groupId>org.zeromq</groupId>
            <artifactId>jeromq</artifactId>
            <version>0.4.0</version>
        </dependency>
    </dependencies>

</project>
</code>```

If you aren't familiar with Maven, read here

Body:
The import org.zeromq cannot be resolved, what can I do?

Im trying to Subscribe ZMQ for my web app. First time working with ZMQ and im getting a little frusty. Can anybody help?

It has been a while since I used Java the last time.

import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Context;
import org.zeromq.ZMQ.Socket;

/**
* Pubsub envelope subscriber
*/

public class psenvsub {

    public static void main (String[] args) {

        // Prepare our context and subscriber
        Context context = ZMQ.context(1);
        Socket subscriber = context.socket(ZMQ.SUB);

        subscriber.connect("tcp://localhost:5563");
        subscriber.subscribe("B".getBytes());
        while (!Thread.currentThread ().isInterrupted ()) {
            // Read envelope with address
            String address = subscriber.recvStr ();
            // Read message contents
            String contents = subscriber.recvStr ();
            System.out.println(address + " : " + contents);
        }
        subscriber.close ();
        context.term ();
    }
}

Body:
You need to have zeromq implementation. Looks like there are multiple implementations in maven central: https://mvnrepository.com/artifact/org.zeromq

This POM should resolve imports:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>zmq</groupId>
    <artifactId>zmq-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.zeromq/jeromq -->
        <dependency>
            <groupId>org.zeromq</groupId>
            <artifactId>jeromq</artifactId>
            <version>0.4.0</version>
        </dependency>
    </dependencies>

</project>

If you aren't familiar with Maven, read here


问:
pick item from list at random, each has different chance
I wanted to write a simple function that allows to roll random item from list, i did it with this code:

```<code>this.resources = [false, 'nitrogen', 'silicon', 'cobalt', 'magnesium'];

this.assign_resource = function() {
    var index = tools.rnd(0, this.resources.length - 1);
    return this.resources[index];
};
</code>```

But it doesn't play well, so i wanted to change it to different system that allows a list of items (including empty one) and it picks one at random but each one has different chance (for example this one has 10%, this one has 20%). Maybe someone could help me with this kind of function.

Edited -----

for example this could be new list:

```<code>this.resources = [
    { type: 'empty', chance: 30 },
    { type: 'nitrogen', chance: 10 },
    { type: 'silicon', chance: 20 },
    { type: 'cobalt', chance: 30 },
    { type: 'magnesium', chance: 10 }
];
</code>```

How to use it now to make it happen properly?

Edited 2 -----

I am trying to figure out well done programming solution using math rather then simply duplicating items in array, answers presented in this topic are just work arounds to a problem.

答:
Here is another implementation.

var res = [
    ["empty", 3],
    ["nitrogen", 1],
    ["silicon", 2],
    ["cobalt", 3],
    ["magnesium", 1]
];
var flat = [];
var item;
for(var i = 0, l = res.length; i < l; i++) {
    item = Array(res[i][1]+1).join(i+",");
    item = item.substr(0, item.length-1);
    flat.push(item);
}
flat = flat.join(",").split(",");

function get_random_item() {
    var ridx = Math.floor(Math.random() * (flat.length));
    return res[flat[ridx]][0];
}

var pick;
for(var p = 0; p < 50; p++) {
    pick = get_random_item();
    console.log(p, pick);
}```

Body:
I wanted to write a simple function that allows to roll random item from list, i did it with this code:

this.resources = [false, 'nitrogen', 'silicon', 'cobalt', 'magnesium'];

this.assign_resource = function() {
    var index = tools.rnd(0, this.resources.length - 1);
    return this.resources[index];
};

But it doesn't play well, so i wanted to change it to different system that allows a list of items (including empty one) and it picks one at random but each one has different chance (for example this one has 10%, this one has 20%). Maybe someone could help me with this kind of function.

Edited -----

for example this could be new list:

this.resources = [
    { type: 'empty', chance: 30 },
    { type: 'nitrogen', chance: 10 },
    { type: 'silicon', chance: 20 },
    { type: 'cobalt', chance: 30 },
    { type: 'magnesium', chance: 10 }
];

How to use it now to make it happen properly?

Edited 2 -----

I am trying to figure out well done programming solution using math rather then simply duplicating items in array, answers presented in this topic are just work arounds to a problem.


问:
Export queries from SSMS to files - not the results but the query
I want to export all my queries as individual files for purposes of putting them into mercurial source control, but I don't know how to export the individual queries as individual files without having to open each one, then save to the folder, then add into the project, or some equally convoluted process.

I wouldn't mind having to add each one individually, but how do I get them out of the database as individual files without opening them all and doing each one save as? Ostensibly I would like them named with the name they have in the database right now.

I could easily dump the whole lot into one long file using database tasks, but that's not really super helpful is it?

I have SSMS 2k5 and 2k8 (and VS 2k5, 2k8, 2010 to boot) to work with, any thoughts?

答: Right click on the database. Select Generate Script. On the last page. Script To file you can choose single file or file per object</p>

ContentLicense: CC BY-SA 2.5


问:
Regex evaluate to true but its not supposed to
I have input field which db is expecting to come as integer. if i type 60 it works fine, but 60.00 doesn't. I did RegExp for validation with the ^[0-9]+/ expession. It works fine for inputs like 60.asdass, 60.0320320, dasdasdas.60 etc. but if i type 60. and it evaluates to true and it passes the validation and i get an error from db. How can i make my regex to sets as false in this situation?

答:
Add the end of string anchor ($):

```<code>^[0-9]+$
</code>```

Body:
Add the end of string anchor ($):

^[0-9]+$


问:
How do I render a shadow?
How do I render a shadow on a View? I've tried many combinations of shadowColor, shadowOffset, shadowOpacity, and shadowRadius, which seem to do nothing. I am sure the style is applied correctly, since other attributes I've set work.

答:
You have to give elevation prop to View

```<code><View elevation={5} style={styles.container}>
   <Text>Hello World !</Text>
 </View>
</code>```

styles can be added like this:

```<code> const styles = StyleSheet.create({

     container:{
        padding:20,
        backgroundColor:'#d9d9d9',
        shadowColor: "#000000",
        shadowOpacity: 0.8,
        shadowRadius: 2,
        shadowOffset: {
          height: 1,
          width: 1
        }
       },
   })
</code>```

Title: How do I render a shadow?

Body:
You have to give elevation prop to View

<View elevation={5} style={styles.container}>
   <Text>Hello World !</Text>
 </View>

styles can be added like this:

 const styles = StyleSheet.create({

     container:{
        padding:20,
        backgroundColor:'#d9d9d9',
        shadowColor: "#000000",
        shadowOpacity: 0.8,
        shadowRadius: 2,
        shadowOffset: {
          height: 1,
          width: 1
        }
       },
   })


问:
Random unique binary matrices
I want Random BUT unique binary matrices of dimension n*n.

For example, if n = 5, then there are 2^(5*5) = 33554432 unique combinations (matrices), which is a HUGE number. I only need 1000. This is my current approach but it takes ALOT of time (which I can not afford because I need to increase the dimensions in future). And I feel it is redundant because in the end I am only selecting 1000 random combinations out of the full number. Any other approach to handle this? This is how I am currently doing it:

I start with a data frame of n*n variables, first row all 1s and second row all 0s:

```<code> Length = 25
 m <- as.data.frame(matrix(c(rep(0, connections), rep(1,
      connections)),ncol=25, byrow = TRUE))
</code>```

m looks like this:

```<code>#V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21
#V22 V23 V24 V25
#1  0  0  0  0  0  0  0  0  0   0   0   0   0   0   0   0   0   0   0   0
#0   0   0   0   0
#2  1  1  1  1  1  1  1  1  1   1   1   1   1   1   1   1   1   1   1   1
#1   1   1   1   1
</code>```

Next I get all the unique combinations using expand.grid

```<code>mFull = expand.grid(m) # This takes forever
</code>```

And then I select 1000 random rows:

```<code>mRand = mFull[sample(1:nrow(mFull), 1000,)]
</code>```

And after this I convert each row into a n*n matrix, for example, for 1st row:

```<code>mRand[1,]
#     V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20
#V21 V22 V23 V24 V25
#21788869  1  1  0  1  1  1  0  0  1   1   1   0   0   0   0   1   1   1   0
#0   1   1   0   1   0
</code>```

Convert it to a matrix:

```<code>> matrix(mRand[1,], nrow = 5, byrow = TRUE)
 [,1] [,2] [,3] [,4] [,5]
 [1,] 1    1    0    1    1
 [2,] 1    0    0    1    1
 [3,] 1    0    0    0    0
 [4,] 1    1    1    0    0
 [5,] 1    1    0    1    0
</code>```

Does anyone has a suggestion for a more efficient solution?

答:
As long as the number of possible matrices fits in an integer, you can encode each matrix as the binary representation of an integer. So if you sample integers without replacement and then turn those integers into binary matrices, you're done.

Here's a couple of functions:

```<code>binmat <- function(dec,n){
    matrix(as.integer(intToBits(dec)[1:(n*n)]),n,n)

}
rbinmats <- function(n,m){
    max = 2^(m*m)
    stopifnot(max < .Machine$integer.max)

    m_decimal = sample(max,n)-1

    lapply(m_decimal, binmat, n=m)

}
</code>```

binmat works like this:

```<code>> binmat(123,3)
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    0
[3,]    0    1    0
</code>```

That's just the 9 bit binary representation of 123 (001111011) written as a matrix (backwards).

rbinmats just samples and creates random matrices of this form:

```<code>> rbinmats(4,3)
[[1]]
     [,1] [,2] [,3]
[1,]    1    0    1
[2,]    0    1    0
[3,]    0    1    0

[[2]]
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    1    1    0
[3,]    1    1    1

[[3]]
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    0    1    0
[3,]    0    1    0

[[4]]
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    0    1
[3,]    1    0    1
</code>```

Here it is sampling 4 integers from 0 to  (2^9)-1, without replacement, and encoding them, so they will be unique.

5x5 seems to be the largest you can do in integers, since 2^(5*5) is less than max int, but 2^(6*6) isn't. Unless there's a way to do this with 64 bit numbers.

Title: Random unique binary matrices

Body:
I want Random BUT unique binary matrices of dimension n*n.

For example, if n = 5, then there are 2^(5*5) = 33554432 unique combinations (matrices), which is a HUGE number. I only need 1000. This is my current approach but it takes ALOT of time (which I can not afford because I need to increase the dimensions in future). And I feel it is redundant because in the end I am only selecting 1000 random combinations out of the full number. Any other approach to handle this? This is how I am currently doing it:

I start with a data frame of n*n variables, first row all 1s and second row all 0s:

 Length = 25
 m <- as.data.frame(matrix(c(rep(0, connections), rep(1,
      connections)),ncol=25, byrow = TRUE))

m looks like this:

#V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21
#V22 V23 V24 V25
#1  0  0  0  0  0  0  0  0  0   0   0   0   0   0   0   0   0   0   0   0
#0   0   0   0   0
#2  1  1  1  1  1  1  1  1  1   1   1   1   1   1   1   1   1   1   1   1
#1   1   1   1   1

Next I get all the unique combinations using expand.grid

mFull = expand.grid(m) # This takes forever

And then I select 1000 random rows:

mRand = mFull[sample(1:nrow(mFull), 1000,)]

And after this I convert each row into a n*n matrix, for example, for 1st row:

mRand[1,]
#     V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20
#V21 V22 V23 V24 V25
#21788869  1  1  0  1  1  1  0  0  1   1   1   0   0   0   0   1   1   1   0
#0   1   1   0   1   0

Convert it to a matrix:

> matrix(mRand[1,], nrow = 5, byrow = TRUE)
 [,1] [,2] [,3] [,4] [,5]
 [1,] 1    1    0    1    1
 [2,] 1    0    0    1    1
 [3,] 1    0    0    0    0
 [4,] 1    1    1    0    0
 [5,] 1    1    0    1    0

Does anyone has a suggestion for a more efficient solution?

Body:
As long as the number of possible matrices fits in an integer, you can encode each matrix as the binary representation of an integer. So if you sample integers without replacement and then turn those integers into binary matrices, you're done.

Here's a couple of functions:

binmat <- function(dec,n){
    matrix(as.integer(intToBits(dec)[1:(n*n)]),n,n)

}
rbinmats <- function(n,m){
    max = 2^(m*m)
    stopifnot(max < .Machine$integer.max)

    m_decimal = sample(max,n)-1

    lapply(m_decimal, binmat, n=m)

}

binmat works like this:

> binmat(123,3)
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    0
[3,]    0    1    0

That's just the 9 bit binary representation of 123 (001111011) written as a matrix (backwards).

rbinmats just samples and creates random matrices of this form:

> rbinmats(4,3)
[[1]]
     [,1] [,2] [,3]
[1,]    1    0    1
[2,]    0    1    0
[3,]    0    1    0

[[2]]
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    1    1    0
[3,]    1    1    1

[[3]]
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    0    1    0
[3,]    0    1    0

[[4]]
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    0    1
[3,]    1    0    1

Here it is sampling 4 integers from 0 to  (2^9)-1, without replacement, and encoding them, so they will be unique.

5x5 seems to be the largest you can do in integers, since 2^(5*5) is less than max int, but 2^(6*6) isn't. Unless there's a way to do this with 64 bit numbers.


问:
cx_oracle: write sql that use all the bind variables
for my code to be generic I need to rewrite all my sql queries in such a way that it uses all the bind variables. Currently If some bind variables passed in the
cx_Oracle.execute(sql,params) does not exist in the sql query I am getting error

```<code>ORA-01036: illegal variable name/number
</code>```

Thanks for your suggestions

答: Not sure exactly what you mean -- but you can use the cursor.bindnames() function to determine all of the bind variables.</p>

Body:
for my code to be generic I need to rewrite all my sql queries in such a way that it uses all the bind variables. Currently If some bind variables passed in the
cx_Oracle.execute(sql,params) does not exist in the sql query I am getting error

ORA-01036: illegal variable name/number

Thanks for your suggestions


问:
How do check if I left the app under test in a UI test?
I have a button that sends the user to the Maps app and I want to check if the user left the app. Any idea how I can check this?
I tried adding an AssertFalse using an element from app under test, but it does not work as it can't retrieve the elements of the app since it's not in focus. </p>

答: In iOS 11, you can do this using XCUIApplication.state to see if the app is in the background or foreground, but this isn't possible in Swift 3 and below.


问:
Creation of buttons for SpriteKit
I am creating the main menu for a sprite kit application I am building. Throughout my entire project, I have used SKScenes to hold my levels and the actual gameplay. However, now I need a main menu, which holds buttons like "Play," "Levels," "Shop," etc... However, I don't feel really comfortable the way I am adding buttons now, which is like this:

```<code>let currentButton = SKSpriteNode(imageNamed: button)  // Create the SKSpriteNode that holds the button

self.addChild(currentButton) // Add that SKSpriteNode to the SKScene
</code>```

And I check for the touch of the button like this:

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    let touchLocation = touch!.location(in: self)

    for node in self.nodes(at: touchLocation) {
        guard let nodeName = node.name else {
            continue
        }
        if nodeName == ButtonLabel.Play.rawValue {
            DispatchQueue.main.asyncAfter(deadline: .now()) {
                let transition = SKTransition.reveal(with: .left, duration: 1)
                self.view?.presentScene(self.initialLevel, transition: transition)
                self.initialLevel.loadStartingLevel()
            }
            return
        }
        if nodeName == ButtonLabel.Levels.rawValue {
            slideOut()
        }

    }
}
</code>```

However, I don't know if this is considered efficient. I was thinking of using UIButtons instead, but for that would I have to use an UIView?

Or can I add UIButtons to an SKView (I don't really get the difference between an SKView, SKScene, and UIView) What is recommended for menus?

答:
I totally agree with @Whirlwind here, create a separate class for your button that handles the work for you. I do not think the advice from @ElTomato is the right advice. If you create one image with buttons included you have no flexibility on placement, size, look and button state for those buttons.

Here is a very simple button class that is a subclass of SKSpriteNode. It uses delegation to send information back to the parent (such as which button has been pushed), and gives you a simple state change (gets smaller when you click it, back to normal size when released)

```<code>import Foundation
import SpriteKit

protocol ButtonDelegate: class {
    func buttonClicked(sender: Button)
}

class Button: SKSpriteNode {

    //weak so that you don't create a strong circular reference with the parent
    weak var delegate: ButtonDelegate!

    override init(texture: SKTexture?, color: SKColor, size: CGSize) {

        super.init(texture: texture, color: color, size: size)

        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        setup()
    }

    func setup() {
        isUserInteractionEnabled = true
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        setScale(0.9)
        self.delegate.buttonClicked(sender: self)
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        setScale(1.0)
    }
}
</code>```

This button can be instantiated 2 ways. You can create an instance of it in the Scene editor, or create an instance in code.

```<code>class MenuScene: SKScene, ButtonDelegate {

    private var button = Button()

    override func didMove(to view: SKView) {

        if let button = self.childNode(withName: "button") as? Button {
            self.button = button
            button.delegate = self
        }

        let button2 = Button(texture: nil, color: .magenta, size: CGSize(width: 200, height: 100))
        button2.name = "button2"
        button2.position = CGPoint(x: 0, y: 300)
        button2.delegate = self
        addChild(button2)
    }
}

func buttonClicked(sender: Button) {
    print("you clicked the button named \(sender.name!)")
}
</code>```

You have to remember to make the scene conform to the delegate

```<code>class MenuScene: SKScene, ButtonDelegate

func buttonClicked(sender: Button) {
    print("you clicked the button named \(sender.name!)")
}
</code>```

Title: Creation of buttons for SpriteKit

Body:
I am creating the main menu for a sprite kit application I am building. Throughout my entire project, I have used SKScenes to hold my levels and the actual gameplay. However, now I need a main menu, which holds buttons like "Play," "Levels," "Shop," etc... However, I don't feel really comfortable the way I am adding buttons now, which is like this:

let currentButton = SKSpriteNode(imageNamed: button)  // Create the SKSpriteNode that holds the button

self.addChild(currentButton) // Add that SKSpriteNode to the SKScene

And I check for the touch of the button like this:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    let touchLocation = touch!.location(in: self)

    for node in self.nodes(at: touchLocation) {
        guard let nodeName = node.name else {
            continue
        }
        if nodeName == ButtonLabel.Play.rawValue {
            DispatchQueue.main.asyncAfter(deadline: .now()) {
                let transition = SKTransition.reveal(with: .left, duration: 1)
                self.view?.presentScene(self.initialLevel, transition: transition)
                self.initialLevel.loadStartingLevel()
            }
            return
        }
        if nodeName == ButtonLabel.Levels.rawValue {
            slideOut()
        }

    }
}

However, I don't know if this is considered efficient. I was thinking of using UIButtons instead, but for that would I have to use an UIView?

Or can I add UIButtons to an SKView (I don't really get the difference between an SKView, SKScene, and UIView) What is recommended for menus?

Body:
I totally agree with @Whirlwind here, create a separate class for your button that handles the work for you. I do not think the advice from @ElTomato is the right advice. If you create one image with buttons included you have no flexibility on placement, size, look and button state for those buttons.

Here is a very simple button class that is a subclass of SKSpriteNode. It uses delegation to send information back to the parent (such as which button has been pushed), and gives you a simple state change (gets smaller when you click it, back to normal size when released)

import Foundation
import SpriteKit

protocol ButtonDelegate: class {
    func buttonClicked(sender: Button)
}

class Button: SKSpriteNode {

    //weak so that you don't create a strong circular reference with the parent
    weak var delegate: ButtonDelegate!

    override init(texture: SKTexture?, color: SKColor, size: CGSize) {

        super.init(texture: texture, color: color, size: size)

        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        setup()
    }

    func setup() {
        isUserInteractionEnabled = true
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        setScale(0.9)
        self.delegate.buttonClicked(sender: self)
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        setScale(1.0)
    }
}

This button can be instantiated 2 ways. You can create an instance of it in the Scene editor, or create an instance in code.

class MenuScene: SKScene, ButtonDelegate {

    private var button = Button()

    override func didMove(to view: SKView) {

        if let button = self.childNode(withName: "button") as? Button {
            self.button = button
            button.delegate = self
        }

        let button2 = Button(texture: nil, color: .magenta, size: CGSize(width: 200, height: 100))
        button2.name = "button2"
        button2.position = CGPoint(x: 0, y: 300)
        button2.delegate = self
        addChild(button2)
    }
}

func buttonClicked(sender: Button) {
    print("you clicked the button named \(sender.name!)")
}

You have to remember to make the scene conform to the delegate

class MenuScene: SKScene, ButtonDelegate

func buttonClicked(sender: Button) {
    print("you clicked the button named \(sender.name!)")
}


问:
Cannot recreate CheckSum result provided by client
I have a client that gave me the following test datastring:

AAA|E0071001|D|20090401010101|EC|UKDC|BP|********|1|TR01|

  CPD|AAA123|Test Participant A123|P|BBB456|New Participant B456|P|

  ER2|NAHNAH1|Test Participant|20090401||

  EAD|7|||

  ZZZ|5|474617386|

The first row is considered header data (starts with AAA), the last row is considered a footer (ZZZ). The rest is the body (lines starting with : CPD,ER2,EAD)

The footer contains a checkSum value (here : 474617386). I need to be able to arrive with this value myself following these rules :

Init result variable to 0

consider each record in turn (including header, but excluding footer)

Break each record into four byte (character) sections (excluding he end of the line character), padded with nulls if required, and exclusive OR (XOR) them into the result variable.

The client provides a c like pseudo code :

```<code>num_chars = strlen (record_buffer)
FOR (i = 0;i < num_chars;)
  value = 0
  FOR (j = 0; j < 4; i++, j++)
    IF i < num_chars
      value = ((value << 8 ) + record_buffer[i])
    ELSE
      value = value << 8
    END IF
  ENDFOR

result = result XOR value
ENDFOR
</code>```

I thought I could translate this straight to C# doing the following :

```<code>var result = 0;
var num_chars = record_buffer.Length;

for (int i = 0; i < num_chars;)
{
  var value = 0;
    for (int j = 0; j < 4;i++, j++)
    {
      if (i < num_chars)
        value = ((value << 8) + record_buffer[i]);
      else
        value = value << 8;
    }

    result = result ^ value;
}
</code>```

Unfortunately my results are always off. Reading in the entire string or reading each record (row) and then summing them up.

I would be thankful for your help.

答:
Problem was with the client providing outdated files.
The code works just fine.</p>

Body:
I have a client that gave me the following test datastring:

AAA|E0071001|D|20090401010101|EC|UKDC|BP|********|1|TR01|

  CPD|AAA123|Test Participant A123|P|BBB456|New Participant B456|P|

  ER2|NAHNAH1|Test Participant|20090401||

  EAD|7|||

  ZZZ|5|474617386|

The first row is considered header data (starts with AAA), the last row is considered a footer (ZZZ). The rest is the body (lines starting with : CPD,ER2,EAD)

The footer contains a checkSum value (here : 474617386). I need to be able to arrive with this value myself following these rules :

Init result variable to 0

consider each record in turn (including header, but excluding footer)

Break each record into four byte (character) sections (excluding he end of the line character), padded with nulls if required, and exclusive OR (XOR) them into the result variable.

The client provides a c like pseudo code :

num_chars = strlen (record_buffer)
FOR (i = 0;i < num_chars;)
  value = 0
  FOR (j = 0; j < 4; i++, j++)
    IF i < num_chars
      value = ((value << 8 ) + record_buffer[i])
    ELSE
      value = value << 8
    END IF
  ENDFOR

result = result XOR value
ENDFOR

I thought I could translate this straight to C# doing the following :

var result = 0;
var num_chars = record_buffer.Length;

for (int i = 0; i < num_chars;)
{
  var value = 0;
    for (int j = 0; j < 4;i++, j++)
    {
      if (i < num_chars)
        value = ((value << 8) + record_buffer[i]);
      else
        value = value << 8;
    }

    result = result ^ value;
}

Unfortunately my results are always off. Reading in the entire string or reading each record (row) and then summing them up.

I would be thankful for your help.


问:
R - C interface: extracting an object from an environment
Say that you pass an environment R object to an internal C routine through the .Call interface. Said enviromnent has (by design) a someObject object which I want to extract and manipulate from the C side. How to do it?

To simplify my question, I just want to write a C function that returns someObject. Like this:

```<code>en <- new.env()
en$someObject <- someValue
.Call("extractObject",en)
#the above should return en$someObject
</code>```

Guess the C code should then look something like

```<code>SEXP extractObject(SEXP env) {
   return SOMEMACROORFUNCTION(env, "someObject");
}
</code>```

Unfortunately, I was not able to find the real SOMEMACROORFUNCTION.

答:
After a little bit of googling and searching, I've found the solution:

```<code>findVar(install("someObject"),env)
</code>```

in the C code is basically the equivalent of get("someObject",env) in R.

Body:
Say that you pass an environment R object to an internal C routine through the .Call interface. Said enviromnent has (by design) a someObject object which I want to extract and manipulate from the C side. How to do it?

To simplify my question, I just want to write a C function that returns someObject. Like this:

en <- new.env()
en$someObject <- someValue
.Call("extractObject",en)
#the above should return en$someObject

Guess the C code should then look something like

SEXP extractObject(SEXP env) {
   return SOMEMACROORFUNCTION(env, "someObject");
}

Unfortunately, I was not able to find the real SOMEMACROORFUNCTION.

Body:
After a little bit of googling and searching, I've found the solution:

findVar(install("someObject"),env)

in the C code is basically the equivalent of get("someObject",env) in R.


问:
Outlook Email via a Webpage
I have a web application developed with ASP.net and C#  that is running on my companies' intranet.  Because all the users for this application are all using Microsoft Outlook without exception, I would like for the the application to open up an Outlook message on the client-side.  I understand that Office is designed to be run on the desktop and not from a server, however I have no trouble creating a Word or Excel document on the client-side.

I have code that instantiates the Outlook object using the Microsoft.Office.Interop.Outlook namespace and Outlook installed on the server.  When I try to run the code from the server, I get a DCOM source error message that states "The machine-default permission settings do not grant Local Activation permission for the COM Server application with CLSID {000C101C-0000-0000-C000-000000000046} to the user This security permission can be modified using the Component Services administrative tool."  I have modified the permissions using the Component Services tool, but still get this same error.

Is there a way to overcome this or is this a fruitless exercise because Outlook cannot be opened on the client side from the server-side code?

Mailto will not work due to the extreme length that the emails can obtain.  Also, the user that sends it needs add in eye-candy to the text for the recipients.

答:
(hint: formatting in your question)

I'm not understanding what's wrong with a mailto link or a formmail-type page.

OwnerDisplayName: Keng

Title: Outlook Email via a Webpage

LastEditorDisplayName: Keng

OwnerDisplayName: hometoast


问:
Testing a PHP script on a local computer
New to PHP and web development in general. I am trying to get information from an HTML form to appear in a table on another web page after clicking submit. So I installed Apache and then PHP on my local PC and expected to be able to test a PHP script locally however it does not return the information I was expecting.
The following is the code for the form:

```<code><form method="post" action="showform.php">

Please fill out the following form if you would like to be contacted: <br/>
    Name:<input type="text" name="name" /> <br/><br/>
    Company: <input type="text" name="company"/> <br/><br/>
    Phone: <input type="text" name="phone" /> <br/><br/>
    Email: <input type="text" name="email" /> <br/><br/>

    <input type="submit" name="Submit" value="Submit" />
</form>
</code>```

The following is the code for the php script:

```<code><table>
<tr><th>Field Name</th><th>Value(s)</th></tr>

<?php
if (empty($_POST)) {
print "<p>No data was submitted.</p>";
 } else {

foreach ($_POST as $key => $value) {
if (get_magic_quotes_gpc()) $value=stripslashes($value);
if ($key=='extras') {

if (is_array($_POST['extras']) ){
    print "<tr><td><code>$key</code></td><td>";
    foreach ($_POST['extras'] as $value) {
            print "<i>$value</i><br />";
            }
            print "</td></tr>";
    } else {
    print "<tr><td><code>$key</code></td><td><i>$value</i></td></tr>\n";
    }
} else {

print "<tr><td><code>$key</code></td><td><i>$value</i></td></tr>\n";
}
 }
}
?>
</table>
</body>
</html>
</code>```

I know it works when used on the internet but how come it doesn't work locally. I have checked that apache and php are installed correctly. What could be the issue?
The current result is a table with $key and $value in the places where the correct values should be, in other words in the table cells.
Thanks for your help.

UPDATE: Now working though WAMPSERVER- thanks to all who helped!

答:
Sounds like your PHP script isn't being parsed if you're literally getting $value. Try running a basic phpinfo() to check this.

If PHP doesn't pick that up make sure the path to PHP is set in httpd.conf. I'd reccommend using xampp though - I'm terrible at all the local configuration and just let the auto installer set it up for me. I know enough to add new modules etc. later on.

OwnerDisplayName: Andrew

LastEditorDisplayName: Andrew

Body:
New to PHP and web development in general. I am trying to get information from an HTML form to appear in a table on another web page after clicking submit. So I installed Apache and then PHP on my local PC and expected to be able to test a PHP script locally however it does not return the information I was expecting.
The following is the code for the form:

<form method="post" action="showform.php">

Please fill out the following form if you would like to be contacted:

    Name:<input type="text" name="name" />

    Company: <input type="text" name="company"/>

    Phone: <input type="text" name="phone" />

    Email: <input type="text" name="email" />

    <input type="submit" name="Submit" value="Submit" />
</form>

The following is the code for the php script:

Field Name	Value(s)

<?php
if (empty($_POST)) {
print "
No data was submitted.
";
 } else {

foreach ($_POST as $key => $value) {
if (get_magic_quotes_gpc()) $value=stripslashes($value);
if ($key=='extras') {

if (is_array($_POST['extras']) ){
    print "
$key	";
    foreach ($_POST['extras'] as $value) {
            print "$value
";
            }
            print "
";
    } else {
    print "
$key	$value
\n";
    }
} else {

print "
$key	$value
\n";
}
 }
}
?>

I know it works when used on the internet but how come it doesn't work locally. I have checked that apache and php are installed correctly. What could be the issue?
The current result is a table with $key and $value in the places where the correct values should be, in other words in the table cells.
Thanks for your help.

UPDATE: Now working though WAMPSERVER- thanks to all who helped!

OwnerDisplayName: Ross


问:
Check when script has loaded
I am trying to call a function that, on the load of the script above it, will run some JavaScript.

```<code><script src="../Layout/jquery.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript" src="helperscript.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var itemid = '1';
        if(itemid)
        {
            idselect(itemid);
        }
    })
</script>
</code>```

helperscript.js contains the function idselect.
When I load the page I get an error saying that 'idselect is undefined', even though it is in the above file. I suspect that this is due to helperscript not being fully loaded yet, but that is just a hunch.

Can anyone help me?

答:
Use jQuery.getScript() and register a success function. It will be safe to use idselect on or after the success function is executed.

http://api.jquery.com/jQuery.getScript/

Title: Check when script has loaded

Body:
I am trying to call a function that, on the load of the script above it, will run some JavaScript.

helperscript.js contains the function idselect.
When I load the page I get an error saying that 'idselect is undefined', even though it is in the above file. I suspect that this is due to helperscript not being fully loaded yet, but that is just a hunch.

Can anyone help me?


问:
How to override UIImageView's image property in an IBDesignable subclass?
I made a subclass of UIImageView which uses Core Graphics to generate a new image that is cropped to a circle with an optional border. It works fine when I run the app. In Interface Builder, however, the generated image renders properly, but it does so underneath the "no image set" placeholder for a UIImageView. Also, the image property shows up twice in IB, and the new image is only generated if I set the overridden field. If I set the image in the regular UIImageView field, it just acts as though it isn't subclassed. Is this just a bug in IB, or is there a fix?

```<code>@IBInspectable override var image : UIImage? {
    didSet {
        // Make the image a circle
        makeCircleImage()
    }
}
</code>```

答: We are stuck with Apple's IB implementation, I'm afraid. I recommend that you find a workaround to overriding image. You can instead implement prepareForInterfaceBuilder and awakeFromNib and do it there, or have a method of doing this operation once in the draw or layout methods, or have a boolean IBInspectable var that does this operation when set.

Body:
I made a subclass of UIImageView which uses Core Graphics to generate a new image that is cropped to a circle with an optional border. It works fine when I run the app. In Interface Builder, however, the generated image renders properly, but it does so underneath the "no image set" placeholder for a UIImageView. Also, the image property shows up twice in IB, and the new image is only generated if I set the overridden field. If I set the image in the regular UIImageView field, it just acts as though it isn't subclassed. Is this just a bug in IB, or is there a fix?

@IBInspectable override var image : UIImage? {
    didSet {
        // Make the image a circle
        makeCircleImage()
    }
}


问:
T-SQL DENSE_RANK() is not returning what I expect
I am having trouble getting the DENSE_RANK() (or similar) to get the values I want from a select query.  I have tried RANK() and ROW_NUMBER() and I have changed the PARTITION and ORDER-BY fields but no luck.
The query follows...

```<code>SELECT         100 * DENSE_RANK() OVER (PARTITION BY UID_CUSTOMER, INT_GROUP_BY ORDER BY UID_CUSTOMER) AS  aINT_GROUP_BY,
                 5 * ROW_NUMBER() OVER (PARTITION BY UID_DIVISION, UID_CUSTOMER,INT_GROUP_BY ORDER BY UID_DIVISION, UID_CUSTOMER, INT_GROUP_BY, INT_SORT_ORDER) AS  aINT_SORT_ORDER,
               UID_DIVISION, UID_CUSTOMER, UID_VEHICLE, INT_GROUP_BY, TXT_GROUP_NAME
FROM           tVEHICLES TV
ORDER BY       UID_DIVISION, UID_CUSTOMER, INT_GROUP_BY, INT_SORT_ORDER;
</code>```

I show the result with an offset of the UID_CUSTOMER-number so you can see three different customers are listed (Column captions are changed to narrow the list display).

```<code>aGROUP_BY  aSORT_ORDER  UID_DIVISION  UID_CUSTOMER  GROUP_BY  TXT_GROUP_NAME
100        5            5             82            100       Group-100
100        10           5             82            100       Group-100
100        15           5             82            100       Group-100
100        20           5             82            100       Group-100
100        25           5             82            100       Group-100
100        5            5             86            100       Group-100
100        10           5             86            100       Group-100
100        15           5             86            100       Group-100
100        20           5             86            100       Group-100
100        25           5             86            100       Group-100
100        30           5             86            100       Group-100
100        5            5             88            100       North
100        10           5             88            100       North
100        15           5             88            100       North
100        5            5             88            200       South
100        10           5             88            200       South
100        15           5             88            200       South
</code>```

The two columns shown are derived from the OVER-constructs and I expected the aGROUP_BY value to be 200 not 100.  The source of the field-data are in the remaining columns 3 to 6.

Your comments and advice is very welcome...John

答:
Here is your code:

```<code>DENSE_RANK() OVER (PARTITION BY UID_CUSTOMER, INT_GROUP_BY ORDER BY UID_CUSTOMER) AS  aINT_GROUP_BY,
</code>```

You've got the rank partitioned by two fields: customer and 'INT_GROUP_BY' -- so the rows 13 thru 17 in your data set actually contain two partitions.  the first is 88,100 and the second is 88,200.  The ranking in each group starts at 1, which is why you are seeing 100 in all six rows.

Modify your code to this:

```<code>DENSE_RANK() OVER (PARTITION BY UID_CUSTOMER ORDER BY UID_CUSTOMER, INT_GROUP_BY) AS  aINT_GROUP_BY,
</code>```

Where INT_GROUP_BY is in the order clause and not the partition clause, and you should see your expected behavior.

Body:
I am having trouble getting the DENSE_RANK() (or similar) to get the values I want from a select query.  I have tried RANK() and ROW_NUMBER() and I have changed the PARTITION and ORDER-BY fields but no luck.
The query follows...

SELECT         100 * DENSE_RANK() OVER (PARTITION BY UID_CUSTOMER, INT_GROUP_BY ORDER BY UID_CUSTOMER) AS  aINT_GROUP_BY,
                 5 * ROW_NUMBER() OVER (PARTITION BY UID_DIVISION, UID_CUSTOMER,INT_GROUP_BY ORDER BY UID_DIVISION, UID_CUSTOMER, INT_GROUP_BY, INT_SORT_ORDER) AS  aINT_SORT_ORDER,
               UID_DIVISION, UID_CUSTOMER, UID_VEHICLE, INT_GROUP_BY, TXT_GROUP_NAME
FROM           tVEHICLES TV
ORDER BY       UID_DIVISION, UID_CUSTOMER, INT_GROUP_BY, INT_SORT_ORDER;

I show the result with an offset of the UID_CUSTOMER-number so you can see three different customers are listed (Column captions are changed to narrow the list display).

aGROUP_BY  aSORT_ORDER  UID_DIVISION  UID_CUSTOMER  GROUP_BY  TXT_GROUP_NAME
100        5            5             82            100       Group-100
100        10           5             82            100       Group-100
100        15           5             82            100       Group-100
100        20           5             82            100       Group-100
100        25           5             82            100       Group-100
100        5            5             86            100       Group-100
100        10           5             86            100       Group-100
100        15           5             86            100       Group-100
100        20           5             86            100       Group-100
100        25           5             86            100       Group-100
100        30           5             86            100       Group-100
100        5            5             88            100       North
100        10           5             88            100       North
100        15           5             88            100       North
100        5            5             88            200       South
100        10           5             88            200       South
100        15           5             88            200       South

The two columns shown are derived from the OVER-constructs and I expected the aGROUP_BY value to be 200 not 100.  The source of the field-data are in the remaining columns 3 to 6.

Your comments and advice is very welcome...John

Body:
Here is your code:

DENSE_RANK() OVER (PARTITION BY UID_CUSTOMER, INT_GROUP_BY ORDER BY UID_CUSTOMER) AS  aINT_GROUP_BY,

You've got the rank partitioned by two fields: customer and 'INT_GROUP_BY' -- so the rows 13 thru 17 in your data set actually contain two partitions.  the first is 88,100 and the second is 88,200.  The ranking in each group starts at 1, which is why you are seeing 100 in all six rows.

Modify your code to this:

DENSE_RANK() OVER (PARTITION BY UID_CUSTOMER ORDER BY UID_CUSTOMER, INT_GROUP_BY) AS  aINT_GROUP_BY,

Where INT_GROUP_BY is in the order clause and not the partition clause, and you should see your expected behavior.


问:
Optimize the number of ng-repeat |angularJS
I want to separate everything in my code according to predefined  levels given , from level 1 to level 6 , now my JSON reads

```<code>$scope.myJson=[{
  id: 1,
  level: 1,
  name: "any name"
},
{
  id: 2,
  level: 2,
  name: "any name"
},
{
  id: 3,
  level: 2,
  name: "any name"
}....]
</code>```

now in my HTML I have written something like

```<code><div>level 1
  <div ng-repeat="prod in myJson"  ng-if="prod.level==1">{{prod.name}}
  </div>
</div>
<div>level 2
  <div ng-repeat="prod in myJson"  ng-if="prod.level==2">{{prod.name}}
  </div>
</div>
</code>```

and so on , I want to use only one ng-repeat to filter all the results in HTML on basis of the levels , as the results number in thousands the app is taking too much of time to respond

答:
You could try a switch case in your ng repeat, for example :

```<code><div ng-repeat="prod in myJson">
   <div ng-switch-on = "prod.level">
        <div ng-switch-when="1">
             Level 1 {{prod.name}}
        </div>
        <div ng-switch-when="2">
             Level 2 {{prod.name}}
        </div>
        <div ng-switch-default>
             Another level {{prod.name}}
        </div>
  </div>
</div>
</code>```

So you will only do one run over your data.

Body:
I want to separate everything in my code according to predefined  levels given , from level 1 to level 6 , now my JSON reads

$scope.myJson=[{
  id: 1,
  level: 1,
  name: "any name"
},
{
  id: 2,
  level: 2,
  name: "any name"
},
{
  id: 3,
  level: 2,
  name: "any name"
}....]

now in my HTML I have written something like

level 1

{{prod.name}}

level 2

{{prod.name}}

and so on , I want to use only one ng-repeat to filter all the results in HTML on basis of the levels , as the results number in thousands the app is taking too much of time to respond

Body:
You could try a switch case in your ng repeat, for example :

<div ng-repeat="prod in myJson">
   <div ng-switch-on = "prod.level">
        <div ng-switch-when="1">
             Level 1 {{prod.name}}
        </div>
        <div ng-switch-when="2">
             Level 2 {{prod.name}}
        </div>
        <div ng-switch-default>
             Another level {{prod.name}}
        </div>
  </div>
</div>

So you will only do one run over your data.


问:
Problem while hosting codeigniter project
After hosting the codeigniter project, while I run it I shows me 404 number error.
 please tell me what change I should do?</p>

答:
Checklist

Make sure your base_url is properly set in config.php

If its your first time using CodeIgniter, a good practice is to keep index.php included in urls and get a better understanding of the framework

If you're removing index.php as the index_page in config.php, then make sure you have correct .htacess settings so that your URL's are rewritten properly.

Make sure the default controller is set properly in config/routes.php. Also make sure the default controller/method that you're calling in your URL actually exists in your code.

Other than the above, it starts to get very specific with how your project is currently configured to provide any help. Please post more specific information if the above doesn't help.


问:
Set HEX string as MQ Correlation ID
I am trying to set the correlation ID of my MQ message as this Hex number:
correlationID = "414d51205350434954495f5550493032115bf458a7180410"
It is initially passed as a string to the function

```<code>        MQMessage msg = new MQMessage();
        byte[] corrID = null;
        corrID = Base64.getDecoder().decode(correlationID);
        try
        {
            msg.writeString(message);
            msg.correlationId = corrID;
            queue_con.put(msg,pmo);
            corrID = msg.correlationId;
            System.out.println(corrID);
            System.out.println(Base64.getEncoder().encodeToString(corrID));

        }
</code>```

This is 48digits long. I've read that the CorrelationID field can hold 24bytes/48hexadecimal digits. But when I try to set the msg.correlationId field, the number gets truncated to only 32 digits. Can you please help me with this?

答:
Using the XML framework part of JRE17: </p>

```<code>try {
 msg.correlationId = javax.xml.bind.DatatypeConverter.parseHexBinary(correlationID);
} catch (IllegalArgumentException e) {
 msg.correlationId = correlationID.getBytes();
}
</code>```

Title: Set HEX string as MQ Correlation ID

Body:
I am trying to set the correlation ID of my MQ message as this Hex number:
correlationID = "414d51205350434954495f5550493032115bf458a7180410"
It is initially passed as a string to the function

        MQMessage msg = new MQMessage();
        byte[] corrID = null;
        corrID = Base64.getDecoder().decode(correlationID);
        try
        {
            msg.writeString(message);
            msg.correlationId = corrID;
            queue_con.put(msg,pmo);
            corrID = msg.correlationId;
            System.out.println(corrID);
            System.out.println(Base64.getEncoder().encodeToString(corrID));

        }

This is 48digits long. I've read that the CorrelationID field can hold 24bytes/48hexadecimal digits. But when I try to set the msg.correlationId field, the number gets truncated to only 32 digits. Can you please help me with this?

Body:
Using the XML framework part of JRE17:

try {
 msg.correlationId = javax.xml.bind.DatatypeConverter.parseHexBinary(correlationID);
} catch (IllegalArgumentException e) {
 msg.correlationId = correlationID.getBytes();
}


问:
How to debug when Flyway doesn't work on Spring Boot?
I am using Maven and Spring Boot. I run the application using mvn spring-boot:run.

https://flywaydb.org/documentation/plugins/springboot says Flyway should be called on Spring Boot start.

So my pom.xml contains the dependency to Flyway.

```<code><dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-core</artifactId>
    <version>4.1.2</version>
</dependency>
</code>```

The first time I ran the Maven command above it downloaded Flyway stuff, so I think the dependency is working.

I have the following files:

```<code>./src/main/resources/db/migration/V123__foo.sql
./src/main/resources/application.properties
</code>```

The above article implied it should "just work", but I don't understand where it would find the JDBC URL to the database. So I added the following to the application.properties file:

```<code>flyway.url=jdbc:postgresql://localhost:5432/services?user=postgres&password=postgres
flyway.enabled=true
</code>```

When Spring Boot starts up (and loads and makes available my web application) there are no logs from Flyway. I think Flyway is ignored.

What can I do? Or, more generally, how would I go about debugging this problem myself?

答:
Nobody has posted an answer so I'll post what I found out.

M. Deinum was indeed correct in their comments to the question, the problem was a lack of a data source.

My original question was what the approach should be to debugging this kind of issue. Obviously one option is to post to stackoverflow :) But I wanted to know how to do it myself.

Spring Boot has a number of classes which look at your code and classpath, and act appropriately. For example, there are classes providing implementations to the rules like "if Flyway is on the path, and there is a data source, then execute Flyway". That rule wasn't getting triggered in my case, because I had no data source.

It's not the case that the code you write calls Spring Boot, it's the other way around, Spring Boot (external to your code) inspects your code and decides what to do based on rules. This architecture is known as action at a distance. The main problem with action at a distance is it's very difficult to debug.

The only real way to find the solution, and it was the way I went about confirming M. Deinum's diagnostic, is to read the Spring Boot source code and understand the annotations which are used to create Spring Boot code.

From the source code to Spring Boot's Flyway integration we see

```<code>@ConditionalOnClass(Flyway.class)
@ConditionalOnBean(DataSource.class)
</code>```

This means "this code will get executed if Flyway is on the classpath, and if there is a DataSource bean available; otherwise it silently won't get executed".

So the answer to the question "how to debug this problem" is that there is no mechanism other than to read the source code of Spring Boot and find out how it works.

If you want to avoid this sort of problem, you have to avoid frameworks which work via "action at a distance", and that includes Spring Boot.

Body:
I am using Maven and Spring Boot. I run the application using mvn spring-boot:run.

https://flywaydb.org/documentation/plugins/springboot says Flyway should be called on Spring Boot start.

So my pom.xml contains the dependency to Flyway.

<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-core</artifactId>
    <version>4.1.2</version>
</dependency>

The first time I ran the Maven command above it downloaded Flyway stuff, so I think the dependency is working.

I have the following files:

./src/main/resources/db/migration/V123__foo.sql
./src/main/resources/application.properties

The above article implied it should "just work", but I don't understand where it would find the JDBC URL to the database. So I added the following to the application.properties file:

flyway.url=jdbc:postgresql://localhost:5432/services?user=postgres&password=postgres
flyway.enabled=true

When Spring Boot starts up (and loads and makes available my web application) there are no logs from Flyway. I think Flyway is ignored.

What can I do? Or, more generally, how would I go about debugging this problem myself?

Body:
Nobody has posted an answer so I'll post what I found out.

M. Deinum was indeed correct in their comments to the question, the problem was a lack of a data source.

My original question was what the approach should be to debugging this kind of issue. Obviously one option is to post to stackoverflow :) But I wanted to know how to do it myself.

Spring Boot has a number of classes which look at your code and classpath, and act appropriately. For example, there are classes providing implementations to the rules like "if Flyway is on the path, and there is a data source, then execute Flyway". That rule wasn't getting triggered in my case, because I had no data source.

It's not the case that the code you write calls Spring Boot, it's the other way around, Spring Boot (external to your code) inspects your code and decides what to do based on rules. This architecture is known as action at a distance. The main problem with action at a distance is it's very difficult to debug.

The only real way to find the solution, and it was the way I went about confirming M. Deinum's diagnostic, is to read the Spring Boot source code and understand the annotations which are used to create Spring Boot code.

From the source code to Spring Boot's Flyway integration we see

@ConditionalOnClass(Flyway.class)
@ConditionalOnBean(DataSource.class)

This means "this code will get executed if Flyway is on the classpath, and if there is a DataSource bean available; otherwise it silently won't get executed".

So the answer to the question "how to debug this problem" is that there is no mechanism other than to read the source code of Spring Boot and find out how it works.

If you want to avoid this sort of problem, you have to avoid frameworks which work via "action at a distance", and that includes Spring Boot.


问:
How to iterate worksheets in workbook - Scala - spoiwo/poi.apache.org
I am trying to iterate worksheets in an Excel workbook.
    I am using Scala's spoiwo/poi.apache

Here is the documentation in Java:

```<code>for (Sheet sheet : wb ) {
    for (Row row : sheet) {
        for (Cell cell : row) {
            // Do something here
        }
    }
}
</code>```

Here is what I've tried.

```<code>def IterateSheets(): Unit ={
    var wb:XSSFWorkbook = new XSSFWorkbook();
    var sheet:XSSFSheet = wb.createSheet();
    sheet = wb.createSheet();
    sheet = wb.createSheet();
    for(sht:XSSFSheet <- wb ){
      println(sht.getSheetName());
    }
}
</code>```

I am given the error:

```<code>Error:(28, 22) value filter is not a member of org.apache.poi.xssf.usermodel.XSSFWorkbook
for(sht:Sheet <- wb ){
</code>```

I have also tried

```<code>for(sht:XSSFSheet <- wb.iterator() ){
</code>```

And I don't see any workbook.sheetIterator() methods.

答:
Here is the simple example of creating a sheet and displaying the list in Apache Poi and Scala. There is a sheetIterator() method in workbook.

```<code>  val myWorkbook = new XSSFWorkbook()

  var sheets = myWorkbook.createSheet()

  sheets = myWorkbook.createSheet()

  val sheetItr = myWorkbook.sheetIterator()
  while (sheetItr.hasNext){
    println("******** " + sheetItr.next().getSheetName)
  }
</code>```

Hope this helps!

Body:
I am trying to iterate worksheets in an Excel workbook.
    I am using Scala's spoiwo/poi.apache

Here is the documentation in Java:

for (Sheet sheet : wb ) {
    for (Row row : sheet) {
        for (Cell cell : row) {
            // Do something here
        }
    }
}

Here is what I've tried.

def IterateSheets(): Unit ={
    var wb:XSSFWorkbook = new XSSFWorkbook();
    var sheet:XSSFSheet = wb.createSheet();
    sheet = wb.createSheet();
    sheet = wb.createSheet();
    for(sht:XSSFSheet <- wb ){
      println(sht.getSheetName());
    }
}

I am given the error:

Error:(28, 22) value filter is not a member of org.apache.poi.xssf.usermodel.XSSFWorkbook
for(sht:Sheet <- wb ){

I have also tried

for(sht:XSSFSheet <- wb.iterator() ){

And I don't see any workbook.sheetIterator() methods.

Body:
Here is the simple example of creating a sheet and displaying the list in Apache Poi and Scala. There is a sheetIterator() method in workbook.

  val myWorkbook = new XSSFWorkbook()

  var sheets = myWorkbook.createSheet()

  sheets = myWorkbook.createSheet()

  val sheetItr = myWorkbook.sheetIterator()
  while (sheetItr.hasNext){
    println("******** " + sheetItr.next().getSheetName)
  }

Hope this helps!


问:
xcode error when compiling build failed
I'm doing an app using firebase, I've already done the set up with pod and today when I re-opened the project after a bit of time I have this problem in the picture, any help on how to fix it?

I've already tried to clean and deleting pod files and re-executing a "pod install" but it seems he can no longer see my "import Firebase"

答:
Unfortunately there could be a number of reasons for your error. Here are a couple easily overlooked steps when installing Firebase with cocoapods:

The top of your pod file likely looks similar to the snippet below. It appears you're using swift so make sure you uncomment the "use_frameworks!" line as I've done here :

```<code># Uncomment this line to define a global platform for your project
# platform :ios, '10.0'
# Uncomment this line if you're using Swift
use_frameworks!
</code>```

Make sure from now on you open your project from the terminal:

```<code>$ open your-project.xcworkspace
</code>```

If you still don't have any luck it may be worth carefully reviewing the getting started guide for Firebase: Add Firebase to your iOS Project

Title: xcode error when compiling build failed

Body:
Unfortunately there could be a number of reasons for your error. Here are a couple easily overlooked steps when installing Firebase with cocoapods:

The top of your pod file likely looks similar to the snippet below. It appears you're using swift so make sure you uncomment the "use_frameworks!" line as I've done here :

# Uncomment this line to define a global platform for your project
# platform :ios, '10.0'
# Uncomment this line if you're using Swift
use_frameworks!

Make sure from now on you open your project from the terminal:

$ open your-project.xcworkspace

If you still don't have any luck it may be worth carefully reviewing the getting started guide for Firebase: Add Firebase to your iOS Project


问:
What is an MvcHtmlString and when should I use it?
The documentation for MvcHtmlString is not terribly enlightening:

Represents an HTML-encoded string that should not be encoded again.

It's not clear to me what exactly the implications of this are. It seems that some HTML helper methods return an MvcHtmlString, but several examples I've seen online of custom helpers just return a regular string.

Questions:

What is an MvcHtmlString?

When should I choose MvcHtmlString over string and vice versa? Why?

答:
A nice practical use of this is if you want to make your own HtmlHelper extensions.  For example, I hate trying to remember the <link> tag syntax, so I've created my own extension method to make a <link> tag:

```<code><Extension()> _
Public Function CssBlock(ByVal html As HtmlHelper, ByVal src As String, ByVal Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
    Dim tag = New TagBuilder("link")
    tag.MergeAttribute("type", "text/css")
    tag.MergeAttribute("rel", "stylesheet")
    tag.MergeAttribute("href", src)
    tag.MergeAttributes(New RouteValueDictionary(htmlAttributes))
    Dim result = tag.ToString(TagRenderMode.Normal)
    Return MvcHtmlString.Create(result)
End Function
</code>```

I could have returned String from this method, but if I had the following would break:

<%: Html.CssBlock(Url.Content("~/sytles/mysite.css")) %>

With MvcHtmlString, using either <%: ... %> or <%= ... %> will both work correctly.

Body:
A nice practical use of this is if you want to make your own HtmlHelper extensions.  For example, I hate trying to remember the <link> tag syntax, so I've created my own extension method to make a <link> tag:

<Extension()> _
Public Function CssBlock(ByVal html As HtmlHelper, ByVal src As String, ByVal Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
    Dim tag = New TagBuilder("link")
    tag.MergeAttribute("type", "text/css")
    tag.MergeAttribute("rel", "stylesheet")
    tag.MergeAttribute("href", src)
    tag.MergeAttributes(New RouteValueDictionary(htmlAttributes))
    Dim result = tag.ToString(TagRenderMode.Normal)
    Return MvcHtmlString.Create(result)
End Function

I could have returned String from this method, but if I had the following would break:

<%: Html.CssBlock(Url.Content("~/sytles/mysite.css")) %>

With MvcHtmlString, using either <%: ... %> or <%= ... %> will both work correctly.


问:
Add a new branch to a TTree in a ROOT file with root_numpy (Python)
I would like to know how I could add a new branch to one of my TTree in a ROOT file using Python.

```<code>with root_open('MC_output.root', mode='a') as myfile:
    new_column = numpy.array(gb_weights , dtype=[('weight', 'f8')])
    root_numpy.array2tree(new_column , tree=myfile.TrainTree)
    new_column_test = numpy.array(gb_weights_test , dtype=[('weight', 'f8')])
    root_numpy.array2tree(new_column_test, tree=myfile.TestTree)
    myfile.write()
    myfile.close()
</code>```

In this example, TrainTree and TestTree already exist in the ROOT file. I just want to add to them a new branch 'weight'. The problem I have here is that it will duplicate the trees, so in my file I have 2 TrainTree and 2 TestTree.

Do I have to use a temporary file to solve this issue? Or is there a better, simpler way to do it?

Thanks for your help!

答:
Actually I could found out the solution by myself:

I was not using the correct method from numpy, I should have used the array2root instead of the array2tree.

```<code>new_column = numpy.array(gb_weights , dtype=[('weight', 'f8')])
root_numpy.array2root(new_column, 'MC_output.root' , 'TrainTree')

new_column_test = numpy.array(gb_weights_test , dtype=[('weight', 'f8')])
root_numpy.array2root(new_column_test, 'MC_output.root', 'TestTree')
</code>```

Is the correct way to do it. Notice that in this case the file is not opened, and so its contain is not temporarily loaded.

Body:
I would like to know how I could add a new branch to one of my TTree in a ROOT file using Python.

with root_open('MC_output.root', mode='a') as myfile:
    new_column = numpy.array(gb_weights , dtype=[('weight', 'f8')])
    root_numpy.array2tree(new_column , tree=myfile.TrainTree)
    new_column_test = numpy.array(gb_weights_test , dtype=[('weight', 'f8')])
    root_numpy.array2tree(new_column_test, tree=myfile.TestTree)
    myfile.write()
    myfile.close()

In this example, TrainTree and TestTree already exist in the ROOT file. I just want to add to them a new branch 'weight'. The problem I have here is that it will duplicate the trees, so in my file I have 2 TrainTree and 2 TestTree.

Do I have to use a temporary file to solve this issue? Or is there a better, simpler way to do it?

Thanks for your help!

Body:
Actually I could found out the solution by myself:

I was not using the correct method from numpy, I should have used the array2root instead of the array2tree.

new_column = numpy.array(gb_weights , dtype=[('weight', 'f8')])
root_numpy.array2root(new_column, 'MC_output.root' , 'TrainTree')

new_column_test = numpy.array(gb_weights_test , dtype=[('weight', 'f8')])
root_numpy.array2root(new_column_test, 'MC_output.root', 'TestTree')

Is the correct way to do it. Notice that in this case the file is not opened, and so its contain is not temporarily loaded.


问:
Regex evaluate to true but its not supposed to
I have input field which db is expecting to come as integer. if i type 60 it works fine, but 60.00 doesn't. I did RegExp for validation with the ^[0-9]+/ expession. It works fine for inputs like 60.asdass, 60.0320320, dasdasdas.60 etc. but if i type 60. and it evaluates to true and it passes the validation and i get an error from db. How can i make my regex to sets as false in this situation?

答:
You can use this. By using anchors it will fail if the full input is not the regular expression specified.</p>

```<code>^\d+$
</code>```

Body:
You can use this. By using anchors it will fail if the full input is not the regular expression specified.

^\d+$


问:
force gcc to compile when stack-overflow is detected
How can i force gcc to compile a program in which i declare an array of unsigned integers that is bigger than my ram - without getting the warning warning: "integer overflow in expression"?

eg. i have 8gb of ram and i want do declare an array of 8.5gb.

edit:

thanks everybody, i figured out that the problem wasnt with the datatype but with some preprocessor stuff. it took me quite a while though. :)
i wrote

```<code>#define GIBI 1073741824
#define ARRAYSIZE 2*GIBI
</code>```

and obviously the compiler didnt like that.

答:
integer overflow in expression isn't a stack overflow, it means that GCC has detected that the result of your expression is causing an integral overflow in the lvalue you're assigning it to. For instance, if you try to malloc something like INT_MAX * 2, that expression will cause an integral overflow. If you cast it to a size_t, you should be warning-free:

```<code>void *myvar = malloc((size_t) INT_MAX * 2);
</code>```

size_t is, of course, platform-dependent, and you could also overflow that if you can't represent the size of the block you want to allocate in sizeof(size_t) bits. Basically, make sure you're using a type capable of representing the amount of memory you want to allocate and that it's compatible with size_t (since that's what malloc() expects, according to stdlib.h).

Body:
How can i force gcc to compile a program in which i declare an array of unsigned integers that is bigger than my ram - without getting the warning warning: "integer overflow in expression"?

eg. i have 8gb of ram and i want do declare an array of 8.5gb.

edit:

thanks everybody, i figured out that the problem wasnt with the datatype but with some preprocessor stuff. it took me quite a while though. :)
i wrote

#define GIBI 1073741824
#define ARRAYSIZE 2*GIBI

and obviously the compiler didnt like that.

Body:
integer overflow in expression isn't a stack overflow, it means that GCC has detected that the result of your expression is causing an integral overflow in the lvalue you're assigning it to. For instance, if you try to malloc something like INT_MAX * 2, that expression will cause an integral overflow. If you cast it to a size_t, you should be warning-free:

void *myvar = malloc((size_t) INT_MAX * 2);

size_t is, of course, platform-dependent, and you could also overflow that if you can't represent the size of the block you want to allocate in sizeof(size_t) bits. Basically, make sure you're using a type capable of representing the amount of memory you want to allocate and that it's compatible with size_t (since that's what malloc() expects, according to stdlib.h).