问:
Rx subscribe FromEvents merge all
Say I have a set of stock symbols:

```<code>StockTicker stockTicker =
  new StockTicker("MSFT", "APPL", "YHOO", "GOOG");
stockTicker.OnPriceChanged += (sender, args ) =>
{
  Console.WriteLine(
    "{0}: Price - {1}  Volume - {2}",
    args.StockSymbol, args.Price, args.Volume);
};
</code>```

I can subscribe to the events and get it as a hot IObservable:

```<code>IObservable<PriceChangedEventArgs> priceChangedObservable =
  Observable.FromEventPattern<PriceChangedEventArgs>(
    eventHandler => stockTicker.OnPriceChanged += eventHandler,
    eventHandler => stockTicker.OnPriceChanged -= eventHandler )
      .Select( eventPattern => eventPattern.EventArgs );

priceChangedObservable.Subscribe(args => Console.WriteLine(
  "{0}: Price - {1}  Volume - {2}",
    args.StockSymbol, args.Price, args.Volume ) );
</code>```

This prints the quote for each symbol as a new quote comes in: In sequence each event is a single qute YHOO 25.33, MSFT 127, AAPL 175, GOOG 1126 etc.

How do I modify the code above so that each "quote" is a combination of all the current quotes of each individual quote? (YHOO 25.33, MSFT 127, GOOG 1126, AAPL 175). A "quote" is now the state of the last quote seen from all of them, served as one "quote".

I see that Rx has a Zip operator, but the semantics of that appear to need n IObservables to zip. Here there are multiple quotes coming through the same IObservable?

So the Console.WriteLine would print all n-quotes subscribed to as a single point-event (and only print when all of them have a value)

答:
If these are random events arriving in any order and you are only interested in the latest value at any time, then perhaps you want a dictionary that is kept updated using the Scan operator:

```<code>source
    /* keep track of the latest value for each symbol */
    .Scan(new Dictionary<string, decimal>(), (a, b) => a[b.StockSymbol] = b.Price)

    /* example logic to wait until they all have values */
    .Where(dict => stockTicker.StockSymbols.All(dict.ContainsKey))

    .Subscribe(dict => { ... });
</code>```

If the number of events you want to buffer remains constant and you know the source is cycling between the events, the Buffer operator might work for you:

```<code>source
    /* burst values periodically */
    .Buffer(count)

    .Subscribe(list => { ... })
</code>```

Title: Rx subscribe FromEvents merge all

Body:
Say I have a set of stock symbols:

StockTicker stockTicker =
  new StockTicker("MSFT", "APPL", "YHOO", "GOOG");
stockTicker.OnPriceChanged += (sender, args ) =>
{
  Console.WriteLine(
    "{0}: Price - {1}  Volume - {2}",
    args.StockSymbol, args.Price, args.Volume);
};

I can subscribe to the events and get it as a hot IObservable:

IObservable<PriceChangedEventArgs> priceChangedObservable =
  Observable.FromEventPattern<PriceChangedEventArgs>(
    eventHandler => stockTicker.OnPriceChanged += eventHandler,
    eventHandler => stockTicker.OnPriceChanged -= eventHandler )
      .Select( eventPattern => eventPattern.EventArgs );

priceChangedObservable.Subscribe(args => Console.WriteLine(
  "{0}: Price - {1}  Volume - {2}",
    args.StockSymbol, args.Price, args.Volume ) );

This prints the quote for each symbol as a new quote comes in: In sequence each event is a single qute YHOO 25.33, MSFT 127, AAPL 175, GOOG 1126 etc.

How do I modify the code above so that each "quote" is a combination of all the current quotes of each individual quote? (YHOO 25.33, MSFT 127, GOOG 1126, AAPL 175). A "quote" is now the state of the last quote seen from all of them, served as one "quote".

I see that Rx has a Zip operator, but the semantics of that appear to need n IObservables to zip. Here there are multiple quotes coming through the same IObservable?

So the Console.WriteLine would print all n-quotes subscribed to as a single point-event (and only print when all of them have a value)

Body:
If these are random events arriving in any order and you are only interested in the latest value at any time, then perhaps you want a dictionary that is kept updated using the Scan operator:

source
    /* keep track of the latest value for each symbol */
    .Scan(new Dictionary<string, decimal>(), (a, b) => a[b.StockSymbol] = b.Price)

    /* example logic to wait until they all have values */
    .Where(dict => stockTicker.StockSymbols.All(dict.ContainsKey))

    .Subscribe(dict => { ... });

If the number of events you want to buffer remains constant and you know the source is cycling between the events, the Buffer operator might work for you:

source
    /* burst values periodically */
    .Buffer(count)

    .Subscribe(list => { ... })


来源: stackexchange

问:
distance between two pointers in C
I have a function that it is supposed to read a string (only with numbers in it) and return the biggest sequence that doenst have repeated numbers.
for example:
12345267890

it should return: 345267890

i've experimented the code manually and I believe it should work. but when I run it, and when it reaches this line i=(strchr(v+i, *(v+j)))-v; instead of getting the distance between the pointers I get something like -1046583. can I do this?

```<code>char* bigSeq(char *v){

    int i, j;
    char *aux, *bgst;
    aux=(char*) malloc(10*sizeof(char));
    bgst=(char*) malloc(10*sizeof(char));
    for(i=0;i<strlen(v);i++){
        for(j=0;j<strlen(v+i);j++){
            if(strchr(v+i, *(v+j)) != (v+j)){
                if(strlen(strncpy(aux, (v+i),j)) > strlen(bgst))
                    strncpy(bgst, (v+i),j);
                i=(strchr(v+i, *(v+j)))-v;
                break;
            }
        }
    }
    return bgst;
}
</code>```

答:
I think your trouble is with strchr() and what it returns when it doesn't find the character you are searching for.  In that case, it returns 0, not either the start or the end of the string that is passed to it.

You should also review making the input a 'const char *', and look at why you need to call strlen() on every iteration of the two loops.  You can probably do better than that.

Note that if the longest substring of non-repeating digits is all 10 digits, your allocated space is too small - you need to allocate a byte for the NUL '\0' at the end of the string too.  Also, strncpy() does not guarantee to null-terminate your string; I'm not sure whether that is part of your problem here.

ContentLicense: CC BY-SA 3.0

Title: distance between two pointers in C

Body:
I have a function that it is supposed to read a string (only with numbers in it) and return the biggest sequence that doenst have repeated numbers.
for example:
12345267890

it should return: 345267890

i've experimented the code manually and I believe it should work. but when I run it, and when it reaches this line i=(strchr(v+i, *(v+j)))-v; instead of getting the distance between the pointers I get something like -1046583. can I do this?

char* bigSeq(char *v){

    int i, j;
    char *aux, *bgst;
    aux=(char*) malloc(10*sizeof(char));
    bgst=(char*) malloc(10*sizeof(char));
    for(i=0;i<strlen(v);i++){
        for(j=0;j<strlen(v+i);j++){
            if(strchr(v+i, *(v+j)) != (v+j)){
                if(strlen(strncpy(aux, (v+i),j)) > strlen(bgst))
                    strncpy(bgst, (v+i),j);
                i=(strchr(v+i, *(v+j)))-v;
                break;
            }
        }
    }
    return bgst;
}


问:
SDL not printing to console
I'm trying to use SDL with Visual Studio 2019 but my programs are only showing an empty console. At the moment I just want to be able to compile my program with the SDL libraries.

#include <iostream>
#include <SDL.h>

int main(int argc, char** argv)
{
    std::cout << "yee haw!" << std::endl;

    return 0;
}
```

This code is just giving me a console with the text:

(process 32) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

Where I would want 'yee haw!' preceding it.

It works fine when I take out the #include <SDL.h> (but I want the SDL.h)

I've heard that SDL now redirects to a stdout.txt file but I couldn't find that anywhere. I've also tried displaying a window with code from a tutorial I found, but that also gives me the empty console.

I'm using Visual Studio 2019 on Windows and SDL 2.0.9

Thanks!

答:
By default, SDL uses a macro hack to replace the main function. The user defined main function must be in the following format:

```<code>int main(int argc, char** argv)
{
    // whatever
    return 0;
}
</code>```

Alternatively, if you don't want this behaviour you can use SDL_SetMainReady.

```<code>#define SDL_MAIN_HANDLED
#include <SDL.h>

int main()
{
    SDL_SetMainReady();

    // whatever

    return 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: SDL not printing to console

Body:
I'm trying to use SDL with Visual Studio 2019 but my programs are only showing an empty console. At the moment I just want to be able to compile my program with the SDL libraries.

#include <iostream>
#include <SDL.h>

int main(int argc, char** argv)
{
    std::cout << "yee haw!" << std::endl;

    return 0;
}

This code is just giving me a console with the text:

(process 32) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

Where I would want 'yee haw!' preceding it.

It works fine when I take out the #include <SDL.h> (but I want the SDL.h)

I've heard that SDL now redirects to a stdout.txt file but I couldn't find that anywhere. I've also tried displaying a window with code from a tutorial I found, but that also gives me the empty console.

I'm using Visual Studio 2019 on Windows and SDL 2.0.9

Thanks!

Body:
By default, SDL uses a macro hack to replace the main function. The user defined main function must be in the following format:

int main(int argc, char** argv)
{
    // whatever
    return 0;
}

Alternatively, if you don't want this behaviour you can use SDL_SetMainReady.

#define SDL_MAIN_HANDLED
#include <SDL.h>

int main()
{
    SDL_SetMainReady();

    // whatever

    return 0;
}


问:
don't have jekyll-paginate or one of its dependencies installed
I have installed this jekyll theme. But faced with one issue.

If I do:

```<code>bundle exec jekyll serve
</code>```

All work fine (_site folder contains necessary files and server is running), but if I use the following command:

```<code>jekyll build -d /var/www/budka/data/www/blog
</code>```

I get the error:

Dependency Error: Yikes! It looks like you don't have jekyll-paginate
  or one of its dependencies installed. In order to use Jekyll as
  currently configured, you'll need to install this gem. The full error
  message from Ruby is: 'cannot load such file -- jekyll-paginate' If
  you run into trouble, you can find helpful resources at
  http://jekyllrb.com/help/!

jekyll 3.1.1 | Error:  jekyll-paginate

I tried to solve the issue, but unsuccessfully.
Now Gemfile file contains:

```<code>source 'http://rubygems.org'
gem 'github-pages'
gem 'html-proofer'
gem "jekyll"
gem 'jekyll-paginate'
gem "pygments.rb"
</code>```

jekyll-paginate (1.1.0) gem is installed, because I see it in gem list commnad:

```<code>*** LOCAL GEMS ***

actionmailer (4.2.5)
actionpack (4.2.5)
actionpack-action_caching (1.1.1)
actionpack-xml_parser (1.0.2)
actionview (4.2.5)
activejob (4.2.5)
activemodel (4.2.5)
activerecord (4.2.5)
activesupport (4.2.5.1, 4.2.5)
addressable (2.4.0, 2.3.8)
arel (6.0.3)
awesome_nested_set (3.0.3)
bigdecimal (1.2.4)
builder (3.2.2)
bundler (1.11.2)
climate_control (0.0.3)
cocaine (0.5.8)
coderay (1.1.0)
coffee-script (2.4.1)
coffee-script-source (1.10.0)
colorator (0.1)
colored (1.2)
concurrent-ruby (1.0.0)
css_parser (1.3.7)
erubis (2.7.0)
ethon (0.8.1)
execjs (2.6.0)
faraday (0.9.2)
ffi (1.9.10)
gemoji (2.1.0)
github-pages (48)
github-pages-health-check (0.6.1)
globalid (0.3.6)
html-pipeline (2.3.0)
html-proofer (2.6.4)
htmlentities (4.3.1)
i18n (0.7.0)
io-console (0.4.2)
jekyll (3.1.1, 3.0.3)
jekyll-coffeescript (1.0.1)
jekyll-feed (0.3.1)
jekyll-gist (1.4.0)
jekyll-mentions (1.0.0)
jekyll-paginate (1.1.0)
jekyll-redirect-from (0.9.1)
jekyll-sass-converter (1.4.0, 1.3.0)
jekyll-seo-tag (1.0.0)
jekyll-sitemap (0.10.0)
jekyll-textile-converter (0.1.0)
jekyll-watch (1.3.1)
jemoji (0.5.1)
jquery-rails (3.1.4)
json (1.8.3, 1.8.1)
kaminari (0.16.3)
kramdown (1.9.0)
liquid (3.0.6)
listen (3.0.6)
loofah (2.0.3)
mail (2.6.3)
mercenary (0.3.5)
mime-types (2.99)
mini_portile2 (2.0.0)
minitest (5.8.4, 4.7.5)
multi_json (1.11.2)
multipart-post (2.0.0)
mysql2 (0.3.20)
net-dns (0.8.0)
net-ldap (0.12.1)
nokogiri (1.6.7.2)
octokit (4.2.0)
pandoc-ruby (1.0.0)
paperclip (4.2.4)
parallel (1.6.1)
passenger (5.0.23)
posix-spawn (0.3.11)
protected_attributes (1.1.3)
psych (2.0.5)
public_suffix (1.5.3)
pygments.rb (0.6.3)
rack (1.6.4, 1.5.2)
rack-openid (1.4.2)
rack-raw-upload (1.1.1)
rack-test (0.6.3)
rails (4.2.5)
rails-deprecated_sanitizer (1.0.3)
rails-dom-testing (1.0.7)
rails-html-sanitizer (1.0.3)
railties (4.2.5)
rake (10.5.0, 10.1.0)
rb-fsevent (0.9.7)
rb-inotify (0.9.7)
rbpdf (1.19.0)
rbpdf-font (1.19.0)
rdiscount (2.1.8)
rdoc (4.1.0)
redcarpet (3.3.4, 3.3.3)
RedCloth (4.2.9)
redmine_crm (0.0.22)
request_store (1.0.5)
rmagick (2.15.4)
roadie (3.1.1)
roadie-rails (1.1.0)
rouge (1.10.1)
ruby-ole (1.2.12)
ruby-openid (2.3.0)
rubyzip (1.1.7, 1.1.6)
safe_yaml (1.0.4)
sass (3.4.21)
sass-rails (5.0.4)
sawyer (0.6.0)
spreadsheet (0.6.9)
sprockets (3.5.2)
sprockets-rails (3.0.0)
terminal-table (1.5.2)
test-unit (2.1.5.0)
thor (0.19.1)
thread_safe (0.3.5)
tilt (2.0.2)
typhoeus (0.8.0)
tzinfo (1.2.2)
vcard (0.2.12)
yajl-ruby (1.2.1)
yell (2.0.5)
</code>```

Also, I added this row:

```<code>gems: [jekyll-paginate, jekyll-gist]
</code>```

into _config.yml file, but jekyll build -d /var/www/budka/data/www/blog command does not still working.

Could you please advise how to solve the issue?

答:
What is the Problem

I had the same problem in jekyll 3.8.5 version and short error message is like below

jekyll 3.8.5 | Error: jekyll-paginate

Investigate the Problem

Then I read my project Gemfile.

If you want to use GitHub Pages, remove the "gem "jekyll"" above and
  uncomment the line below. To upgrade, run bundle update github-pages.

Solution

So I did what it suggested, comment the # gem "jekyll", "~> 3.8.5" and uncommented below line

gem "github-pages", group: :jekyll_plugins

then run bundle update github-pages and bundle exec jekyll serve.

Because github-pages have all necessary gem files, I solved my problem.

Body:
I have installed this jekyll theme. But faced with one issue.

If I do:

bundle exec jekyll serve

All work fine (_site folder contains necessary files and server is running), but if I use the following command:

jekyll build -d /var/www/budka/data/www/blog

I get the error:

Dependency Error: Yikes! It looks like you don't have jekyll-paginate
  or one of its dependencies installed. In order to use Jekyll as
  currently configured, you'll need to install this gem. The full error
  message from Ruby is: 'cannot load such file -- jekyll-paginate' If
  you run into trouble, you can find helpful resources at
  http://jekyllrb.com/help/!

jekyll 3.1.1 | Error:  jekyll-paginate

I tried to solve the issue, but unsuccessfully.
Now Gemfile file contains:

source 'http://rubygems.org'
gem 'github-pages'
gem 'html-proofer'
gem "jekyll"
gem 'jekyll-paginate'
gem "pygments.rb"

jekyll-paginate (1.1.0) gem is installed, because I see it in gem list commnad:

*** LOCAL GEMS ***

actionmailer (4.2.5)
actionpack (4.2.5)
actionpack-action_caching (1.1.1)
actionpack-xml_parser (1.0.2)
actionview (4.2.5)
activejob (4.2.5)
activemodel (4.2.5)
activerecord (4.2.5)
activesupport (4.2.5.1, 4.2.5)
addressable (2.4.0, 2.3.8)
arel (6.0.3)
awesome_nested_set (3.0.3)
bigdecimal (1.2.4)
builder (3.2.2)
bundler (1.11.2)
climate_control (0.0.3)
cocaine (0.5.8)
coderay (1.1.0)
coffee-script (2.4.1)
coffee-script-source (1.10.0)
colorator (0.1)
colored (1.2)
concurrent-ruby (1.0.0)
css_parser (1.3.7)
erubis (2.7.0)
ethon (0.8.1)
execjs (2.6.0)
faraday (0.9.2)
ffi (1.9.10)
gemoji (2.1.0)
github-pages (48)
github-pages-health-check (0.6.1)
globalid (0.3.6)
html-pipeline (2.3.0)
html-proofer (2.6.4)
htmlentities (4.3.1)
i18n (0.7.0)
io-console (0.4.2)
jekyll (3.1.1, 3.0.3)
jekyll-coffeescript (1.0.1)
jekyll-feed (0.3.1)
jekyll-gist (1.4.0)
jekyll-mentions (1.0.0)
jekyll-paginate (1.1.0)
jekyll-redirect-from (0.9.1)
jekyll-sass-converter (1.4.0, 1.3.0)
jekyll-seo-tag (1.0.0)
jekyll-sitemap (0.10.0)
jekyll-textile-converter (0.1.0)
jekyll-watch (1.3.1)
jemoji (0.5.1)
jquery-rails (3.1.4)
json (1.8.3, 1.8.1)
kaminari (0.16.3)
kramdown (1.9.0)
liquid (3.0.6)
listen (3.0.6)
loofah (2.0.3)
mail (2.6.3)
mercenary (0.3.5)
mime-types (2.99)
mini_portile2 (2.0.0)
minitest (5.8.4, 4.7.5)
multi_json (1.11.2)
multipart-post (2.0.0)
mysql2 (0.3.20)
net-dns (0.8.0)
net-ldap (0.12.1)
nokogiri (1.6.7.2)
octokit (4.2.0)
pandoc-ruby (1.0.0)
paperclip (4.2.4)
parallel (1.6.1)
passenger (5.0.23)
posix-spawn (0.3.11)
protected_attributes (1.1.3)
psych (2.0.5)
public_suffix (1.5.3)
pygments.rb (0.6.3)
rack (1.6.4, 1.5.2)
rack-openid (1.4.2)
rack-raw-upload (1.1.1)
rack-test (0.6.3)
rails (4.2.5)
rails-deprecated_sanitizer (1.0.3)
rails-dom-testing (1.0.7)
rails-html-sanitizer (1.0.3)
railties (4.2.5)
rake (10.5.0, 10.1.0)
rb-fsevent (0.9.7)
rb-inotify (0.9.7)
rbpdf (1.19.0)
rbpdf-font (1.19.0)
rdiscount (2.1.8)
rdoc (4.1.0)
redcarpet (3.3.4, 3.3.3)
RedCloth (4.2.9)
redmine_crm (0.0.22)
request_store (1.0.5)
rmagick (2.15.4)
roadie (3.1.1)
roadie-rails (1.1.0)
rouge (1.10.1)
ruby-ole (1.2.12)
ruby-openid (2.3.0)
rubyzip (1.1.7, 1.1.6)
safe_yaml (1.0.4)
sass (3.4.21)
sass-rails (5.0.4)
sawyer (0.6.0)
spreadsheet (0.6.9)
sprockets (3.5.2)
sprockets-rails (3.0.0)
terminal-table (1.5.2)
test-unit (2.1.5.0)
thor (0.19.1)
thread_safe (0.3.5)
tilt (2.0.2)
typhoeus (0.8.0)
tzinfo (1.2.2)
vcard (0.2.12)
yajl-ruby (1.2.1)
yell (2.0.5)

Also, I added this row:

gems: [jekyll-paginate, jekyll-gist]

into _config.yml file, but jekyll build -d /var/www/budka/data/www/blog command does not still working.

Could you please advise how to solve the issue?


问:
Why is R merging all the rows in my CSV file as one whole document?
I am using R for a sentiment analysis. My source file which contains around 50 reviews made by guests has been created in Excel (with each review recorded in a single row and single column). So, all reviews are found in Column A, with no headers. The file has then been saved as a csv file and stored in a folder.

My R codes are as follows:

```<code>library (tm)
docs<-Corpus(DirSource('E:/Sentiment Analysis'))
#checking a particular review in the document
writeLines(as.character(docs[[20]]))
</code>```

Running that last line gives me an out of bound error message.
When I change it to writeLines(as.character(docs[[1]])), R displays all the reviews as if they were one whole paragraph.

How can I correct this issue?

答:
The tm::Corpus() function used with DirSource() treats each file as a separate document, rather than each line within one file as a separate document.

To read each row of a text file as a separate document, one can use the Corpus(VectorSource()) syntax.

As an example, we'll create a text file, read it from a directory to illustrate how Corpus() behaves with DirSource(), versus how we would read it with VectorSource().

```<code># represent contents of the text file that was stored in
# ./data/ExcelFile1.csv
aTextFile <- "This is line one of text.
This is line two of text. This is a second sentence in line two."

library(tm)
# read as the OP read it
corpusDir <- "./data/textMining"
aCorpus <- Corpus(DirSource(corpusDir))
length(aCorpus) # shows only one item in list, entire file

# use pipe as separator because documents include commas.
aDataFrame <- read.table("./data/textMining/ExcelFile1.csv",header=FALSE,
                         sep="|",stringsAsFactors=FALSE)
# use VectorSource to treat each row as a separate document
aCorpus <- Corpus(VectorSource(aDataFrame$V1))
# print the two documents
aCorpus[1]$content
aCorpus[2]$content
</code>```

...and the output. First, the length of the corpus as we read it with DirSource():

```<code>> length(aCorpus) # shows only one item in list, entire file
[1] 1
</code>```

Second, we'll print the two rows from the second read, illustrating that they are treated as separate documents.

```<code>> aCorpus <- Corpus(VectorSource(aDataFrame$V1))
> aCorpus[1]$content
[1] "This is line one of text."
> aCorpus[2]$content
[1] "This is line two of text. This is a second sentence in line two. "
>
</code>```

Body:
I am using R for a sentiment analysis. My source file which contains around 50 reviews made by guests has been created in Excel (with each review recorded in a single row and single column). So, all reviews are found in Column A, with no headers. The file has then been saved as a csv file and stored in a folder.

My R codes are as follows:

library (tm)
docs<-Corpus(DirSource('E:/Sentiment Analysis'))
#checking a particular review in the document
writeLines(as.character(docs[[20]]))

Running that last line gives me an out of bound error message.
When I change it to writeLines(as.character(docs[[1]])), R displays all the reviews as if they were one whole paragraph.

How can I correct this issue?

Body:
The tm::Corpus() function used with DirSource() treats each file as a separate document, rather than each line within one file as a separate document.

To read each row of a text file as a separate document, one can use the Corpus(VectorSource()) syntax.

As an example, we'll create a text file, read it from a directory to illustrate how Corpus() behaves with DirSource(), versus how we would read it with VectorSource().

# represent contents of the text file that was stored in
# ./data/ExcelFile1.csv
aTextFile <- "This is line one of text.
This is line two of text. This is a second sentence in line two."

library(tm)
# read as the OP read it
corpusDir <- "./data/textMining"
aCorpus <- Corpus(DirSource(corpusDir))
length(aCorpus) # shows only one item in list, entire file

# use pipe as separator because documents include commas.
aDataFrame <- read.table("./data/textMining/ExcelFile1.csv",header=FALSE,
                         sep="|",stringsAsFactors=FALSE)
# use VectorSource to treat each row as a separate document
aCorpus <- Corpus(VectorSource(aDataFrame$V1))
# print the two documents
aCorpus[1]$content
aCorpus[2]$content

...and the output. First, the length of the corpus as we read it with DirSource():

> length(aCorpus) # shows only one item in list, entire file
[1] 1

Second, we'll print the two rows from the second read, illustrating that they are treated as separate documents.

> aCorpus <- Corpus(VectorSource(aDataFrame$V1))
> aCorpus[1]$content
[1] "This is line one of text."
> aCorpus[2]$content
[1] "This is line two of text. This is a second sentence in line two. "
>


问:
LoadError no such file when trying to load gems under rails
I'm getting a 'no such file' error when I try to require some gems in a rails console. Strangely, I don't get this error when requiring them in irb.

Thanks in advance.

```<code>        $ irb
irb(main):001:0> $LOAD_PATH
=> ["/usr/local/lib/site_ruby/1.9.1", "/usr/local/lib/site_ruby/1.9.1/x86_64-linux", "/usr/local/lib/site_ruby", "/usr/lib/ruby/vendor_ruby/1.9.1", "/usr/lib/ruby/vendor_ruby/1.9.1/x86_64-linux", "/usr/lib/ruby/vendor_ruby", "/usr/lib/ruby/1.9.1", "/usr/lib/ruby/1.9.1/x86_64-linux"]
        irb(main):002:0> require 'rubygems'
        => true
        irb(main):003:0> require 'image_science'
        => true
        irb(main):004:0> require 'mini_magick'
        => true
        irb(main):005:0>
        $ rails console
        Loading development environment (Rails 3.0.5)
        irb(main):001:0> require 'rubygems'
        => nil
        irb(main):002:0> require 'image_science'
        LoadError: no such file to load -- image_science
            from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:239:in `require'
    ...
            from script/rails:6:in `require'
            from script/rails:6:in `<main>'
        irb(main):003:0> require 'mini_magick'
        LoadError: no such file to load -- mini_magick
            from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:239:in `require'
    ...
            from script/rails:6:in `require'
            from script/rails:6:in `<main>'
        irb(main):004:0> $LOAD_PATH
        => ["/var/lib/gems/1.9.1/gems/haml-3.0.25/vendor/fssm/lib",  "/home/username/appname/lib", "/home/username/appname/vendor", "/home/username/appname/app/models", "/home/username/appname/app/mailers", "/home/username/appname/app/helpers", "/home/username/appname/app/controllers", "/var/lib/gems/1.9.1/gems/rails-3.0.5/lib", "/var/lib/gems/1.9.1/gems/railties-3.0.5/lib", "/var/lib/gems/1.9.1/gems/thor-0.14.6/lib", "/var/lib/gems/1.9.1/gems/pg-0.10.1/lib", "/var/lib/gems/1.9.1/gems/pg-0.10.1/ext", "/var/lib/gems/1.9.1/gems/oauth2-0.1.1/lib", "/var/lib/gems/1.9.1/gems/multi_json-0.0.5/lib", "/var/lib/gems/1.9.1/gems/haml-3.0.25/lib", "/var/lib/gems/1.9.1/gems/faraday-0.5.7/lib", "/var/lib/gems/1.9.1/gems/multipart-post-1.1.0/lib", "/var/lib/gems/1.9.1/gems/addressable-2.2.4/lib", "/var/lib/gems/1.9.1/gems/activeresource-3.0.5/lib", "/var/lib/gems/1.9.1/gems/activerecord-3.0.5/lib", "/var/lib/gems/1.9.1/gems/arel-2.0.9/lib", "/var/lib/gems/1.9.1/gems/actionmailer-3.0.5/lib", "/var/lib/gems/1.9.1/gems/mail-2.2.15/lib", "/var/lib/gems/1.9.1/gems/treetop-1.4.9/lib", "/var/lib/gems/1.9.1/gems/polyglot-0.3.1/lib", "/var/lib/gems/1.9.1/gems/mime-types-1.16/lib", "/var/lib/gems/1.9.1/gems/actionpack-3.0.5/lib", "/var/lib/gems/1.9.1/gems/tzinfo-0.3.24/lib", "/var/lib/gems/1.9.1/gems/rack-test-0.5.7/lib", "/var/lib/gems/1.9.1/gems/rack-mount-0.6.13/lib", "/var/lib/gems/1.9.1/gems/rack-1.2.1/lib", "/var/lib/gems/1.9.1/gems/erubis-2.6.6/lib", "/var/lib/gems/1.9.1/gems/activemodel-3.0.5/lib", "/var/lib/gems/1.9.1/gems/i18n-0.5.0/lib", "/var/lib/gems/1.9.1/gems/builder-2.1.2/lib", "/var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib", "/var/lib/gems/1.9.1/gems/abstract-1.0.0/lib", "/var/lib/gems/1.9.1/gems/rake-0.8.7/lib", "/var/lib/gems/1.9.1/gems/bundler-1.0.10/lib", "/usr/local/lib/site_ruby/1.9.1", "/usr/local/lib/site_ruby/1.9.1/x86_64-linux", "/usr/local/lib/site_ruby", "/usr/lib/ruby/vendor_ruby/1.9.1", "/usr/lib/ruby/vendor_ruby/1.9.1/x86_64-linux", "/usr/lib/ruby/vendor_ruby", "/usr/lib/ruby/1.9.1", "/usr/lib/ruby/1.9.1/x86_64-linux", "/var/lib/gems/1.9.1/gems/actionpack-3.0.5/lib/action_controller/vendor/html-scanner", "/var/lib/gems/1.9.1/gems/rack-mount-0.6.13/lib/rack/mount/vendor/multimap", "/var/lib/gems/1.9.1/gems/rack-mount-0.6.13/lib/rack/mount/vendor/regin"]
</code>```

Gemfile:

```<code>source 'http://rubygems.org'

gem 'rails', '3.0.5'

gem 'pg'
gem 'oauth2'
gem 'haml'
</code>```

答:
You cannot require gems in Rails that are not in your Gemfile. You have to either include them in your Gemfile, or specify the full path to the gem when requiring, e.g. require "/full/path/to/gem".

This is because of the way Bundler works and overrides your existing load path. If you run $LOAD_PATH in the Rails console you'll see that it differs significantly from the one in IRB.

Body:
I'm getting a 'no such file' error when I try to require some gems in a rails console. Strangely, I don't get this error when requiring them in irb.

Thanks in advance.

        $ irb
irb(main):001:0> $LOAD_PATH
=> ["/usr/local/lib/site_ruby/1.9.1", "/usr/local/lib/site_ruby/1.9.1/x86_64-linux", "/usr/local/lib/site_ruby", "/usr/lib/ruby/vendor_ruby/1.9.1", "/usr/lib/ruby/vendor_ruby/1.9.1/x86_64-linux", "/usr/lib/ruby/vendor_ruby", "/usr/lib/ruby/1.9.1", "/usr/lib/ruby/1.9.1/x86_64-linux"]
        irb(main):002:0> require 'rubygems'
        => true
        irb(main):003:0> require 'image_science'
        => true
        irb(main):004:0> require 'mini_magick'
        => true
        irb(main):005:0>
        $ rails console
        Loading development environment (Rails 3.0.5)
        irb(main):001:0> require 'rubygems'
        => nil
        irb(main):002:0> require 'image_science'
        LoadError: no such file to load -- image_science
            from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:239:in `require'
    ...
            from script/rails:6:in `require'
            from script/rails:6:in `'
        irb(main):003:0> require 'mini_magick'
        LoadError: no such file to load -- mini_magick
            from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:239:in `require'
    ...
            from script/rails:6:in `require'
            from script/rails:6:in `'
        irb(main):004:0> $LOAD_PATH
        => ["/var/lib/gems/1.9.1/gems/haml-3.0.25/vendor/fssm/lib",  "/home/username/appname/lib", "/home/username/appname/vendor", "/home/username/appname/app/models", "/home/username/appname/app/mailers", "/home/username/appname/app/helpers", "/home/username/appname/app/controllers", "/var/lib/gems/1.9.1/gems/rails-3.0.5/lib", "/var/lib/gems/1.9.1/gems/railties-3.0.5/lib", "/var/lib/gems/1.9.1/gems/thor-0.14.6/lib", "/var/lib/gems/1.9.1/gems/pg-0.10.1/lib", "/var/lib/gems/1.9.1/gems/pg-0.10.1/ext", "/var/lib/gems/1.9.1/gems/oauth2-0.1.1/lib", "/var/lib/gems/1.9.1/gems/multi_json-0.0.5/lib", "/var/lib/gems/1.9.1/gems/haml-3.0.25/lib", "/var/lib/gems/1.9.1/gems/faraday-0.5.7/lib", "/var/lib/gems/1.9.1/gems/multipart-post-1.1.0/lib", "/var/lib/gems/1.9.1/gems/addressable-2.2.4/lib", "/var/lib/gems/1.9.1/gems/activeresource-3.0.5/lib", "/var/lib/gems/1.9.1/gems/activerecord-3.0.5/lib", "/var/lib/gems/1.9.1/gems/arel-2.0.9/lib", "/var/lib/gems/1.9.1/gems/actionmailer-3.0.5/lib", "/var/lib/gems/1.9.1/gems/mail-2.2.15/lib", "/var/lib/gems/1.9.1/gems/treetop-1.4.9/lib", "/var/lib/gems/1.9.1/gems/polyglot-0.3.1/lib", "/var/lib/gems/1.9.1/gems/mime-types-1.16/lib", "/var/lib/gems/1.9.1/gems/actionpack-3.0.5/lib", "/var/lib/gems/1.9.1/gems/tzinfo-0.3.24/lib", "/var/lib/gems/1.9.1/gems/rack-test-0.5.7/lib", "/var/lib/gems/1.9.1/gems/rack-mount-0.6.13/lib", "/var/lib/gems/1.9.1/gems/rack-1.2.1/lib", "/var/lib/gems/1.9.1/gems/erubis-2.6.6/lib", "/var/lib/gems/1.9.1/gems/activemodel-3.0.5/lib", "/var/lib/gems/1.9.1/gems/i18n-0.5.0/lib", "/var/lib/gems/1.9.1/gems/builder-2.1.2/lib", "/var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib", "/var/lib/gems/1.9.1/gems/abstract-1.0.0/lib", "/var/lib/gems/1.9.1/gems/rake-0.8.7/lib", "/var/lib/gems/1.9.1/gems/bundler-1.0.10/lib", "/usr/local/lib/site_ruby/1.9.1", "/usr/local/lib/site_ruby/1.9.1/x86_64-linux", "/usr/local/lib/site_ruby", "/usr/lib/ruby/vendor_ruby/1.9.1", "/usr/lib/ruby/vendor_ruby/1.9.1/x86_64-linux", "/usr/lib/ruby/vendor_ruby", "/usr/lib/ruby/1.9.1", "/usr/lib/ruby/1.9.1/x86_64-linux", "/var/lib/gems/1.9.1/gems/actionpack-3.0.5/lib/action_controller/vendor/html-scanner", "/var/lib/gems/1.9.1/gems/rack-mount-0.6.13/lib/rack/mount/vendor/multimap", "/var/lib/gems/1.9.1/gems/rack-mount-0.6.13/lib/rack/mount/vendor/regin"]

Gemfile:

source 'http://rubygems.org'

gem 'rails', '3.0.5'

gem 'pg'
gem 'oauth2'
gem 'haml'


问:
Does PHP 7 throw an error when passing too few parameters to a function?
I'm upgrading my webapp to php7 from 5.6, and I'm suddenly getting errors when I pass too few arguments to functions.  In php 5.6 I was able to have functions with say three parameters, and I could pass two, and it would work fine.  Has anyone else run into this?  Is this new in php7?

I used to be able to pass two arguments to a function with three parameters, but suddenly I'm getting errors.

```<code>function displayField ($fieldname,$fieldval,$nobold)  { ... };

displayField ("testname","this value");
</code>```

In this case I get:

Fatal error: Uncaught ArgumentCountError: Too few arguments to
  function displayField(), 2 passed in
  /home/cabox/workspace/php/encscripts.php on line 31 and exactly 3
  expected in /home/cabox/workspace/php/encscripts.php:3

Is there a way around this, or do I have to find every example of passing fewer than the expected parameters and rewrite my code?  Thanks for your help!

答:
From PHP manual:

Previously, a warning would be emitted for invoking user-defined functions with too few arguments. Now, this warning has been promoted to an Error exception. This change only applies to user-defined functions, not internal functions. For example:

https://www.php.net/manual/en/migration71.incompatible.php

Try to make the third parameter optional:

```<code>function displayField($fieldname, $fieldval, $nobold = null) { ... };
</code>```

Body:
I'm upgrading my webapp to php7 from 5.6, and I'm suddenly getting errors when I pass too few arguments to functions.  In php 5.6 I was able to have functions with say three parameters, and I could pass two, and it would work fine.  Has anyone else run into this?  Is this new in php7?

I used to be able to pass two arguments to a function with three parameters, but suddenly I'm getting errors.

function displayField ($fieldname,$fieldval,$nobold)  { ... };

displayField ("testname","this value");

In this case I get:

Fatal error: Uncaught ArgumentCountError: Too few arguments to
  function displayField(), 2 passed in
  /home/cabox/workspace/php/encscripts.php on line 31 and exactly 3
  expected in /home/cabox/workspace/php/encscripts.php:3

Is there a way around this, or do I have to find every example of passing fewer than the expected parameters and rewrite my code?  Thanks for your help!

Body:
From PHP manual:

Previously, a warning would be emitted for invoking user-defined functions with too few arguments. Now, this warning has been promoted to an Error exception. This change only applies to user-defined functions, not internal functions. For example:

https://www.php.net/manual/en/migration71.incompatible.php

Try to make the third parameter optional:

function displayField($fieldname, $fieldval, $nobold = null) { ... };


问:
How to set css property according to css property of other element
I am using ionic 4 and want to set some mask element above other element.
My mask element is a fixed image that I want to set just above the ion-tab-bar - it means that I want my image "bottom" css property will be just the same as the ion-tab-bar css "height" property value.

I have already tried this inside the tabs page:

```<code>ionViewDidEnter() {
    document.getElementById('mask').style.bottom = document.getElementById('tabsbar').style.height;
}
</code>```

But the style property returned empty fields...

Is there some other way? maybe with ngStyle?

答:
Solved this way:</p>

```<code>ionViewDidEnter() {

  document.getElementById('mask').style.bottom = document.getElementById('tabsbar').getBoundingClientRect().height+'px';

}
</code>```

Body:
I am using ionic 4 and want to set some mask element above other element.
My mask element is a fixed image that I want to set just above the ion-tab-bar - it means that I want my image "bottom" css property will be just the same as the ion-tab-bar css "height" property value.

I have already tried this inside the tabs page:

ionViewDidEnter() {
    document.getElementById('mask').style.bottom = document.getElementById('tabsbar').style.height;
}

But the style property returned empty fields...

Is there some other way? maybe with ngStyle?

Body:
Solved this way:

ionViewDidEnter() {

  document.getElementById('mask').style.bottom = document.getElementById('tabsbar').getBoundingClientRect().height+'px';

}


问:
spring.resources.chain.strategy.content.enabled only working on .css files
I am trying to enable ContentVersionStrategy for JavaScript and CSS files within a Spring Boot application using Thymeleaf as the view engine.

In a sample project I have added the following to the application properties file:

```<code># add classpath:/custom/ as a possible location
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/custom/

# enable ContentVersionStrategy
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
</code>```

This works for .css files in the application but not .js files. From what I can read it should also work on .js files.

I have also tried to do this manually rather than just in the properties file with:

@Configuration
public class WebConfiguration implements WebMvcConfigurer
{
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/", "classpath:/custom/"};

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS)
                .resourceChain(true)
                .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
    }
}
```

But this does not work for .css files or .js.

I have tried with with Spring Boot 2.1.4.RELEASE, 2.2.0.M2, 2.2.0.BUILD-SNAPSHOT, Java 11 and 12 just in case there were any differences.

Any reason my the property file method does not seem to apply to .js files?

Is there anything obviously wrong with my WebMvcConfigurer implementation that means it does not apply to either .css or .js?

答:
So after 5 hours of digging through Spring to try and work out why the content hash values for javascript files were not being generated I spotted the difference between the css and js links:

<!doctype html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Test page</title>

    <link rel="stylesheet" th:href="@{/css/jquery-ui.min.css}"/>
    <link rel="stylesheet" th:href="@{/directory/select2.min.css}"/>

Text page

```

<p>the script tags are missing the forward slash at the start. Adding it fixes the issue.</p>

<p>Also found the bit I was missing to do it manually:</p>

<pre class="lang-java prettyprint-override"><code>@Configuration
public class WebConfiguration implements WebMvcConfigurer
{
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/", "classpath:/custom/"};

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS)
                .resourceChain(true)
                .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
    }

    @Bean
    public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
        return new ResourceUrlEncodingFilter();
    }
}
</code>```

I needed to add the ResourceUrlEncodingFilter bean.

Body:
I am trying to enable ContentVersionStrategy for JavaScript and CSS files within a Spring Boot application using Thymeleaf as the view engine.

In a sample project I have added the following to the application properties file:

# add classpath:/custom/ as a possible location
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/custom/

# enable ContentVersionStrategy
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

This works for .css files in the application but not .js files. From what I can read it should also work on .js files.

I have also tried to do this manually rather than just in the properties file with:

@Configuration
public class WebConfiguration implements WebMvcConfigurer
{
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/", "classpath:/custom/"};

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS)
                .resourceChain(true)
                .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
    }
}

But this does not work for .css files or .js.

I have tried with with Spring Boot 2.1.4.RELEASE, 2.2.0.M2, 2.2.0.BUILD-SNAPSHOT, Java 11 and 12 just in case there were any differences.

Any reason my the property file method does not seem to apply to .js files?

Is there anything obviously wrong with my WebMvcConfigurer implementation that means it does not apply to either .css or .js?

Body:
So after 5 hours of digging through Spring to try and work out why the content hash values for javascript files were not being generated I spotted the difference between the css and js links:

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Test page</title>

    <link rel="stylesheet" th:href="@{/css/jquery-ui.min.css}"/>
    <link rel="stylesheet" th:href="@{/directory/select2.min.css}"/>
</head>
<body>
    <p>Text page</p>
    <script th:src="@{js/jquery.js}"></script>
    <script th:src="@{js/select2.min.js}"></script>
    <script th:src="@{directory/jquery-ui.min.js}"></script>
</body>
</html>

the script tags are missing the forward slash at the start. Adding it fixes the issue.

Also found the bit I was missing to do it manually:

@Configuration
public class WebConfiguration implements WebMvcConfigurer
{
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/", "classpath:/custom/"};

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS)
                .resourceChain(true)
                .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
    }

    @Bean
    public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
        return new ResourceUrlEncodingFilter();
    }
}

I needed to add the ResourceUrlEncodingFilter bean.


问:
Firefox and IE continue to load after content has been inserted into a DIV
I have a situation where I'm inserting javascript generated HTML code into a DIV.  One would think this would be a no brainer, but for some reason, once the code is in, the status bar and tab loading graphics start up in both browsers and never stop again.  The page continually appears to be loading data, but in reality, there's nothing more to load.  Any idea why this may be happening?  Solutions?  I appreciate any help. Thanks!</p>

答: Install the Firebug plug-in for Firefox. Open it up and got to the NET tab. That will allow you to see your network activity. Something on the server may be stalling. This will help you find it.


问:
How to calculate working time in Google Sheet
I have a task to calculate the working hours in Google Sheet.

Below is my sheet screenshot, where I am facing an issue if the logout time is in AM.

Example:

Current Formula:

=(hour(D6-C6-E6)*60 + minute(D6-C6-E6))/60

答:
Please try:

```<code> =24*(D6-C6-E6+(D6<C6))
</code>```

Perhaps formatted as Number to two decimal places.

Body:
Please try:

 =24*(D6-C6-E6+(D6<C6))

Perhaps formatted as Number to two decimal places.


问:
Is there a function that can display an object from a class that I've created into a QTextBrowser?
I'm creating a GUI that stores and displays objects of various data types such as int, double, string and three other class that i have created that are Rational, Date, and Complex. These objects are stored into Linked Lists of the same type. For int, double, and string i've had to problem storing values that the user enters into a QPlainTextEdit to the lists and displaying them into the QTextBrowser, however, i'm unsure on how to display objects from classes that i've created into the QTextBrowser. Is there a function that can do this?

I'm currently working with my Rational class that takes in objects in the form of "Rational(3,4);" and displays them like fractions such as "3/4".
I've managed to create the objects from user inputs that are in the form "3/4" and push them into the linked list but i have not been able to display them into my QTextBrowser

```<code>//sample code
else if(ui->Rational_button->isChecked())
{
    ui->main_display->setText("");

    //Iterator that goes through the linked list to get the objects
    LinkedList<Rational>::Iterator it = rationalvec.begin();

    while(it != nullptr)
    {
       ui->main_display->append(QString::fromStdString(*it));
                                      /* Trying to display all Rational
                                      objects in the QTextBrowser */
       ++it;
    }
}

//There should be an output like the following inside the QTextBrowser

4/5
2/3
7/9
9/11

//These are all Rational type objects
</code>```

I'm getting a "semantic issue" no viable conversion from 'Rational' to QString/const std::string. I can't seem to find a way to convert or display these objects into the QTextBrowser.

EDIT: Here is the Rational class

```<code>class Rational
{
private:
    int numer;  //IN/OUT - the numerator int
    int denom;  //IN/OUT - the denominator int
public:
    /******************************
    ** CONSTRUCTOR & DESTRUCTOR **
    ******************************/
    Rational()         //Constructor
    {
       numer = 0;
       denom = 1;
    }
    Rational(int number)               //Constructor
    {
       numer = number;
       denom = 1;
    }
    Rational(int number1, int number2) //Constructor
    {
      numer = number1;
      denom = number2;
    }

    /***************
    ** ACCESSORS **
    ***************/
    const Rational add(const Rational &) const;
    const Rational subtract(const Rational &) const;
    const Rational multiply(const Rational &) const;
    const Rational divide(const Rational &) const;

    void display() const
    {
       cout << numer << "/" << denom;
    }

    friend ostream& operator<<(ostream &, const Rational &)    //FOR WIDGET
    {
       out << object.numer;
       out << '/';
       out << object.denom;

       return out;
   }

    bool operator <(const Rational& )                          //FOR WIDGET
    {
       if((numer/denom) < (other.numer/other.denom))
           return true;
       else
           return false;
    }
    bool operator >(const Rational& )                          //FOR WIDGET
    {
       if((numer/denom) > (other.numer/other.denom))
           return true;
       else
           return false;
     }

};
</code>```

Only showing the function definition for the functions i'm using, the other functions whose definitions are not shown are the ones im not gonna use during this program.

答:
Is something like this that you're looking for?

Edit your code like this:

Add to your Classes a toString function:

class Rational
{

...

public:
    QString toString() [
        return QString::number(numer) + "/" + QString::number(denom);
    }

...

}
```

<ul>
<li>Display in <code>QTextBrowser</code>:</li>
</ul>

<pre class="lang-cpp prettyprint-override"><code>else if(ui->Rational_button->isChecked())
{
    ui->main_display->setText("");

    for( Rational r : rationalvec )
    {

       ui->main_display->append( r.toString() );    // Here use toString() to append
                                                    // it->toString() if iterator
    }
}
</code>```

Hope it helps you.

Body:
I'm creating a GUI that stores and displays objects of various data types such as int, double, string and three other class that i have created that are Rational, Date, and Complex. These objects are stored into Linked Lists of the same type. For int, double, and string i've had to problem storing values that the user enters into a QPlainTextEdit to the lists and displaying them into the QTextBrowser, however, i'm unsure on how to display objects from classes that i've created into the QTextBrowser. Is there a function that can do this?

I'm currently working with my Rational class that takes in objects in the form of "Rational(3,4);" and displays them like fractions such as "3/4".
I've managed to create the objects from user inputs that are in the form "3/4" and push them into the linked list but i have not been able to display them into my QTextBrowser

//sample code
else if(ui->Rational_button->isChecked())
{
    ui->main_display->setText("");

    //Iterator that goes through the linked list to get the objects
    LinkedList<Rational>::Iterator it = rationalvec.begin();

    while(it != nullptr)
    {
       ui->main_display->append(QString::fromStdString(*it));
                                      /* Trying to display all Rational
                                      objects in the QTextBrowser */
       ++it;
    }
}

//There should be an output like the following inside the QTextBrowser

4/5
2/3
7/9
9/11

//These are all Rational type objects

I'm getting a "semantic issue" no viable conversion from 'Rational' to QString/const std::string. I can't seem to find a way to convert or display these objects into the QTextBrowser.

EDIT: Here is the Rational class

class Rational
{
private:
    int numer;  //IN/OUT - the numerator int
    int denom;  //IN/OUT - the denominator int
public:
    /******************************
    ** CONSTRUCTOR & DESTRUCTOR **
    ******************************/
    Rational()         //Constructor
    {
       numer = 0;
       denom = 1;
    }
    Rational(int number)               //Constructor
    {
       numer = number;
       denom = 1;
    }
    Rational(int number1, int number2) //Constructor
    {
      numer = number1;
      denom = number2;
    }

    /***************
    ** ACCESSORS **
    ***************/
    const Rational add(const Rational &) const;
    const Rational subtract(const Rational &) const;
    const Rational multiply(const Rational &) const;
    const Rational divide(const Rational &) const;

    void display() const
    {
       cout << numer << "/" << denom;
    }

    friend ostream& operator<<(ostream &, const Rational &)    //FOR WIDGET
    {
       out << object.numer;
       out << '/';
       out << object.denom;

       return out;
   }

    bool operator <(const Rational& )                          //FOR WIDGET
    {
       if((numer/denom) < (other.numer/other.denom))
           return true;
       else
           return false;
    }
    bool operator >(const Rational& )                          //FOR WIDGET
    {
       if((numer/denom) > (other.numer/other.denom))
           return true;
       else
           return false;
     }

};

Only showing the function definition for the functions i'm using, the other functions whose definitions are not shown are the ones im not gonna use during this program.

Body:
Is something like this that you're looking for?

Edit your code like this:

Add to your Classes a toString function:

class Rational
{

...

public:
    QString toString() [
        return QString::number(numer) + "/" + QString::number(denom);
    }

...

}

Display in QTextBrowser:

else if(ui->Rational_button->isChecked())
{
    ui->main_display->setText("");

    for( Rational r : rationalvec )
    {

       ui->main_display->append( r.toString() );    // Here use toString() to append
                                                    // it->toString() if iterator
    }
}

Hope it helps you.


问:
Is there a way to run multiple bash scripts with one script at the same time?
I am running an Instagram bot using python and selenium. I use a bash script to run a python script with the accounts credentials(Username, password, hashtags, etc...) I run multiple Instagrams so I have made multiple copies of this file. Is there a way to put this in a single file that I can click on and run?
To open multiple terminals running their assigned account?

I've already tried just to add them to one big file but the scripts wont run until the previous one finishes.

Also since I'm using selenium, trying multi threading in python is somewhat difficult but would not mind going that route if someone could point me to where I could start with that.

#!/bin/sh
cd PycharmProjects/InstaBot
python3 W.py
```

答:
Only one process in shell can run in foreground mode. So the command gets executed only when the previous completes.
Adding "&" symbol at the end of the command line tells shell that the command should be executed in the background. This way the shell will start python and continue without waiting.

This will execute two instances simultaneously, but they will all output to the same terminal:

```<code>    #!/bin/sh
    cd PycharmProjects/InstaBot
    python3 W.py first_credentials &
    python3 W.py second_credentials &
</code>```

You can use the same technique to start a new terminal process for each python script:

```<code>    #!/bin/sh
    cd PycharmProjects/InstaBot
    gnome-terminal   -e "python3 W.py first_credentials"  &
    gnome-terminal   -e "python3 W.py second_credentials" &
</code>```

Body:
Only one process in shell can run in foreground mode. So the command gets executed only when the previous completes.
Adding "&" symbol at the end of the command line tells shell that the command should be executed in the background. This way the shell will start python and continue without waiting.

This will execute two instances simultaneously, but they will all output to the same terminal:

    #!/bin/sh
    cd PycharmProjects/InstaBot
    python3 W.py first_credentials &
    python3 W.py second_credentials &

You can use the same technique to start a new terminal process for each python script:

    #!/bin/sh
    cd PycharmProjects/InstaBot
    gnome-terminal   -e "python3 W.py first_credentials"  &
    gnome-terminal   -e "python3 W.py second_credentials" &


问:
NHibernate SaveOrUpdate Child Collection Not Updated With Identity Ids
I am clearly missing something (hopefully obvious), and I have had no luck with Google so far.

I have a Parent-Child relationship mapped as follows

Simplified Parent Map

```<code>  public sealed class ParentMap : ClassMap<ParentEntity>
  {
    public ParentMap()
    {
      Table("Parent");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.ServeralNotNullableProperties).Not.Nullable();

      HasMany(x => x.Children).KeyColumn("ChildId")
                              .Inverse()
                              .LazyLoad()
                              .Cascade
                              .AllDeleteOrphan();

      References(x => x.SomeUnrelatedLookupColumn).Column("LookupColumnId").Not.Nullable();
    }
  }
</code>```

Simplified Child Map

```<code>  public sealed class ChildMap : ClassMap<ChildEntity>
  {
    public ChildMap()
    {
      Table("Child");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.MoreNotNullableProperties).Not.Nullable();

      References(x => x.Parent).Column("ParentId").Not.Nullable();
    }
  }
</code>```

Simplified Service Method Steps

I then have a service method that retrieves Parent and adds a new Child via some domain method. The underlying NHibernate code boils down to:

1) Session Opened on WCF AfterReceiveRequest (IDispatchMessageInspector)

```<code>_sessionFactory.OpenSession();
</code>```

2) Retrieve existing instance of parent via .Query

```<code>_session.Query<ParentEntity>()
        .Where(item => item.Id == parentId)
        .Fetch(item => item.SomeLookupColumn)
        .First();
</code>```

3) Add new 'Child' entity to 'Parent' via domain object method such as...

```<code>public ChildEntity CreateChild()
{
  var child = new ChildEntity{ Parent = this };

  Children.Add(child);

  return child;
}
</code>```

4) Ultimately calls SaveOrUpdate on 'Parent' entity.

```<code> // ChildEntity Id is 0
 _session.SaveOrUpdate(parentEntity)
 // Expect ChildEntity Id to NOT be 0
</code>```

Note: Use of SaveOrUpdate Does persist changes to database; use of Merge results in TransientObjectException mentioned below.

5) Finally, transaction committed on WCF BeforeSendReply (IDispatchMessageInspector)

```<code> _session.Commit();
</code>```

The Problem

Typically when an entity is saved, after the call to SaveOrUpdate, the Id of said entity refects the Identity generated by the INSERT statement. However, when I add a new child entity to an existing parent, the associated entity in Children does not get assigned an Id. I need to pass this Id back to the caller so subsequent calls result in UPDATES and not additional INSERTS.

Why is NHibernate not updating the underlying entity?
Do I explicitly have to call SaveOrUpdate on the child (that sucks if that is the case)?

Any thoughts on the matter greatly appreciated. Thanks!

EDIT
I should note, that the new child entity IS being saved as expected; I just don't get back the Id assigned.

UPDATE
Tried switching to .Merge(~) as suggested by Michael Buen below; resulting in a TransientObjectException telling me to explicitly save my modified child entity before calling merge. I also experimented with .Persist(~) to no avail. Any additional insight greatly appreciated.

object is an unsaved transient instance - save the transient instance before merging: My.NameSpace.ChildEntity

答:
I finally found the time to dig around in the NHibernate code... the reason this is happening makes sense... short answer - the Cascade actions are processed on Session.Commit(); well after the above service operation has completed. Thus, my child objects haven't been refreshed to reflect the assigned ids by the time the service method returns the updated child entity.

Turns out I must call SaveOrUpdate directly on child entity if I need to know the Id immediately.

Body:
I am clearly missing something (hopefully obvious), and I have had no luck with Google so far.

I have a Parent-Child relationship mapped as follows

Simplified Parent Map

  public sealed class ParentMap : ClassMap<ParentEntity>
  {
    public ParentMap()
    {
      Table("Parent");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.ServeralNotNullableProperties).Not.Nullable();

      HasMany(x => x.Children).KeyColumn("ChildId")
                              .Inverse()
                              .LazyLoad()
                              .Cascade
                              .AllDeleteOrphan();

      References(x => x.SomeUnrelatedLookupColumn).Column("LookupColumnId").Not.Nullable();
    }
  }

Simplified Child Map

  public sealed class ChildMap : ClassMap<ChildEntity>
  {
    public ChildMap()
    {
      Table("Child");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.MoreNotNullableProperties).Not.Nullable();

      References(x => x.Parent).Column("ParentId").Not.Nullable();
    }
  }

Simplified Service Method Steps

I then have a service method that retrieves Parent and adds a new Child via some domain method. The underlying NHibernate code boils down to:

1) Session Opened on WCF AfterReceiveRequest (IDispatchMessageInspector)

_sessionFactory.OpenSession();

2) Retrieve existing instance of parent via .Query

_session.Query<ParentEntity>()
        .Where(item => item.Id == parentId)
        .Fetch(item => item.SomeLookupColumn)
        .First();

3) Add new 'Child' entity to 'Parent' via domain object method such as...

public ChildEntity CreateChild()
{
  var child = new ChildEntity{ Parent = this };

  Children.Add(child);

  return child;
}

4) Ultimately calls SaveOrUpdate on 'Parent' entity.

 // ChildEntity Id is 0
 _session.SaveOrUpdate(parentEntity)
 // Expect ChildEntity Id to NOT be 0

Note: Use of SaveOrUpdate Does persist changes to database; use of Merge results in TransientObjectException mentioned below.

5) Finally, transaction committed on WCF BeforeSendReply (IDispatchMessageInspector)

 _session.Commit();

The Problem

Typically when an entity is saved, after the call to SaveOrUpdate, the Id of said entity refects the Identity generated by the INSERT statement. However, when I add a new child entity to an existing parent, the associated entity in Children does not get assigned an Id. I need to pass this Id back to the caller so subsequent calls result in UPDATES and not additional INSERTS.

Why is NHibernate not updating the underlying entity?
Do I explicitly have to call SaveOrUpdate on the child (that sucks if that is the case)?

Any thoughts on the matter greatly appreciated. Thanks!

EDIT
I should note, that the new child entity IS being saved as expected; I just don't get back the Id assigned.

UPDATE
Tried switching to .Merge(~) as suggested by Michael Buen below; resulting in a TransientObjectException telling me to explicitly save my modified child entity before calling merge. I also experimented with .Persist(~) to no avail. Any additional insight greatly appreciated.

object is an unsaved transient instance - save the transient instance before merging: My.NameSpace.ChildEntity


问:
How to run Python code using a specific Python environment in Visual Studio?
I've started working on a large-scale Python program, and I'm using Visual Studio as my main IDE.

I have the entirety of Visual Studio's extensions for the use of Python, including Anaconda, which I used to create an environment from which I want to run my Python code.

Any ideas on how I can get that to happen?

答:
Okay, so the answer was going into

```<code>View > Other Windows > Python Environments
</code>```

and selecting the version of Python to work with.

https://learn.microsoft.com/en-us/visualstudio/python/managing-python-environments-in-visual-studio?view=vs-2019

Body:
Okay, so the answer was going into

View > Other Windows > Python Environments

and selecting the version of Python to work with.

https://learn.microsoft.com/en-us/visualstudio/python/managing-python-environments-in-visual-studio?view=vs-2019


问:
Java Heap Dump error - Metadata does not appear to be polymorphic
I get this Stacktrace when trying to take a heap dump from a running Java process. What causes this and what do I have to do to make a proper heap dump?

```<code>Dumping heap to dump.bin ...
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.tools.jmap.JMap.runTool(JMap.java:201)
    at sun.tools.jmap.JMap.main(JMap.java:130)
Caused by: java.lang.InternalError: Metadata does not appear to be polymorphic
    at sun.jvm.hotspot.types.basic.BasicTypeDataBase.findDynamicTypeForAddress(BasicTypeDataBase.java:278)
    at sun.jvm.hotspot.runtime.VirtualBaseConstructor.instantiateWrapperFor(VirtualBaseConstructor.java:102)
    at sun.jvm.hotspot.oops.Metadata.instantiateWrapperFor(Metadata.java:68)
    at sun.jvm.hotspot.memory.DictionaryEntry.klass(DictionaryEntry.java:71)
    at sun.jvm.hotspot.memory.Dictionary.classesDo(Dictionary.java:66)
    at sun.jvm.hotspot.memory.SystemDictionary.classesDo(SystemDictionary.java:190)
    at sun.jvm.hotspot.memory.SystemDictionary.allClassesDo(SystemDictionary.java:183)
    at sun.jvm.hotspot.utilities.HeapHprofBinWriter.writeClasses(HeapHprofBinWriter.java:942)
    at sun.jvm.hotspot.utilities.HeapHprofBinWriter.write(HeapHprofBinWriter.java:427)
    at sun.jvm.hotspot.tools.HeapDumper.run(HeapDumper.java:62)
    at sun.jvm.hotspot.tools.Tool.startInternal(Tool.java:260)
    at sun.jvm.hotspot.tools.Tool.start(Tool.java:223)
    at sun.jvm.hotspot.tools.Tool.execute(Tool.java:118)
    at sun.jvm.hotspot.tools.HeapDumper.main(HeapDumper.java:83)
    ... 6 more
</code>```

Environment: CentOS 64 bit, Java OpenJDK Runtime Environment (build 1.8.0_31-b13) OpenJDK 64-Bit Server VM (build 25.31-b07, mixed mode)

Using ps to see the java version that is used:

```<code>/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31-1.b13.el6_6.x86_64/jre/bin/java
</code>```

My first try was:

```<code>/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31-1.b13.el6_6.x86_64/bin/jmap  -dump:format=b,file=dump.bin 14984
</code>```

That got me :

```<code>14984: Unable to open socket file: target process not responding or HotSpot VM not loaded
The -F option can be used when the target process is not responding
</code>```

So I ran with the -F option

```<code>/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31-1.b13.el6_6.x86_64/bin/jmap -F -dump:format=b,file=dump.bin 14984
</code>```

答:
On Ubuntu, I resolved this issue by installing the openjdk-dbg package:

```<code>sudo apt-get install openjdk-8-dbg
</code>```

I now suspect that this resolved my issue indirectly by upgrading the jdk to a version that corrected the bug.  You might be able to resolve this issue with:

```<code> sudo apt-get install openjdk-8
</code>```

Note: After java is upgraded, you must restart the java process in order to get a proper dump.  If you don't, you will get something like this:

```<code>Attaching to process ID 21957, please wait...
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.tools.jmap.JMap.runTool(JMap.java:201)
    at sun.tools.jmap.JMap.main(JMap.java:130)
Caused by: sun.jvm.hotspot.debugger.UnmappedAddressException: 7f21453c9bf8
    at sun.jvm.hotspot.debugger.PageCache.checkPage(PageCache.java:208)
    at sun.jvm.hotspot.debugger.PageCache.getData(PageCache.java:63)
    at sun.jvm.hotspot.debugger.DebuggerBase.readBytes(DebuggerBase.java:225)
    at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal.readCInteger(LinuxDebuggerLocal.java:498)
    at sun.jvm.hotspot.debugger.linux.LinuxAddress.getCIntegerAt(LinuxAddress.java:69)
    at sun.jvm.hotspot.HotSpotTypeDataBase.getLongValueFromProcess(HotSpotTypeDataBase.java:604)
    at sun.jvm.hotspot.HotSpotTypeDataBase.readVMTypes(HotSpotTypeDataBase.java:164)
    at sun.jvm.hotspot.HotSpotTypeDataBase.<init>(HotSpotTypeDataBase.java:89)
    at sun.jvm.hotspot.HotSpotAgent.setupVM(HotSpotAgent.java:395)
    at sun.jvm.hotspot.HotSpotAgent.go(HotSpotAgent.java:305)
    at sun.jvm.hotspot.HotSpotAgent.attach(HotSpotAgent.java:140)
    at sun.jvm.hotspot.tools.Tool.start(Tool.java:185)
    at sun.jvm.hotspot.tools.Tool.execute(Tool.java:118)
    at sun.jvm.hotspot.tools.HeapDumper.main(HeapDumper.java:83)
    ... 6 more
</code>```

Body:
I get this Stacktrace when trying to take a heap dump from a running Java process. What causes this and what do I have to do to make a proper heap dump?

Dumping heap to dump.bin ...
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.tools.jmap.JMap.runTool(JMap.java:201)
    at sun.tools.jmap.JMap.main(JMap.java:130)
Caused by: java.lang.InternalError: Metadata does not appear to be polymorphic
    at sun.jvm.hotspot.types.basic.BasicTypeDataBase.findDynamicTypeForAddress(BasicTypeDataBase.java:278)
    at sun.jvm.hotspot.runtime.VirtualBaseConstructor.instantiateWrapperFor(VirtualBaseConstructor.java:102)
    at sun.jvm.hotspot.oops.Metadata.instantiateWrapperFor(Metadata.java:68)
    at sun.jvm.hotspot.memory.DictionaryEntry.klass(DictionaryEntry.java:71)
    at sun.jvm.hotspot.memory.Dictionary.classesDo(Dictionary.java:66)
    at sun.jvm.hotspot.memory.SystemDictionary.classesDo(SystemDictionary.java:190)
    at sun.jvm.hotspot.memory.SystemDictionary.allClassesDo(SystemDictionary.java:183)
    at sun.jvm.hotspot.utilities.HeapHprofBinWriter.writeClasses(HeapHprofBinWriter.java:942)
    at sun.jvm.hotspot.utilities.HeapHprofBinWriter.write(HeapHprofBinWriter.java:427)
    at sun.jvm.hotspot.tools.HeapDumper.run(HeapDumper.java:62)
    at sun.jvm.hotspot.tools.Tool.startInternal(Tool.java:260)
    at sun.jvm.hotspot.tools.Tool.start(Tool.java:223)
    at sun.jvm.hotspot.tools.Tool.execute(Tool.java:118)
    at sun.jvm.hotspot.tools.HeapDumper.main(HeapDumper.java:83)
    ... 6 more

Environment: CentOS 64 bit, Java OpenJDK Runtime Environment (build 1.8.0_31-b13) OpenJDK 64-Bit Server VM (build 25.31-b07, mixed mode)

Using ps to see the java version that is used:

/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31-1.b13.el6_6.x86_64/jre/bin/java

My first try was:

/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31-1.b13.el6_6.x86_64/bin/jmap  -dump:format=b,file=dump.bin 14984

That got me :

14984: Unable to open socket file: target process not responding or HotSpot VM not loaded
The -F option can be used when the target process is not responding

So I ran with the -F option

/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.31-1.b13.el6_6.x86_64/bin/jmap -F -dump:format=b,file=dump.bin 14984

Body:
On Ubuntu, I resolved this issue by installing the openjdk-dbg package:

sudo apt-get install openjdk-8-dbg

I now suspect that this resolved my issue indirectly by upgrading the jdk to a version that corrected the bug.  You might be able to resolve this issue with:

 sudo apt-get install openjdk-8

Note: After java is upgraded, you must restart the java process in order to get a proper dump.  If you don't, you will get something like this:

Attaching to process ID 21957, please wait...
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.tools.jmap.JMap.runTool(JMap.java:201)
    at sun.tools.jmap.JMap.main(JMap.java:130)
Caused by: sun.jvm.hotspot.debugger.UnmappedAddressException: 7f21453c9bf8
    at sun.jvm.hotspot.debugger.PageCache.checkPage(PageCache.java:208)
    at sun.jvm.hotspot.debugger.PageCache.getData(PageCache.java:63)
    at sun.jvm.hotspot.debugger.DebuggerBase.readBytes(DebuggerBase.java:225)
    at sun.jvm.hotspot.debugger.linux.LinuxDebuggerLocal.readCInteger(LinuxDebuggerLocal.java:498)
    at sun.jvm.hotspot.debugger.linux.LinuxAddress.getCIntegerAt(LinuxAddress.java:69)
    at sun.jvm.hotspot.HotSpotTypeDataBase.getLongValueFromProcess(HotSpotTypeDataBase.java:604)
    at sun.jvm.hotspot.HotSpotTypeDataBase.readVMTypes(HotSpotTypeDataBase.java:164)
    at sun.jvm.hotspot.HotSpotTypeDataBase.<init>(HotSpotTypeDataBase.java:89)
    at sun.jvm.hotspot.HotSpotAgent.setupVM(HotSpotAgent.java:395)
    at sun.jvm.hotspot.HotSpotAgent.go(HotSpotAgent.java:305)
    at sun.jvm.hotspot.HotSpotAgent.attach(HotSpotAgent.java:140)
    at sun.jvm.hotspot.tools.Tool.start(Tool.java:185)
    at sun.jvm.hotspot.tools.Tool.execute(Tool.java:118)
    at sun.jvm.hotspot.tools.HeapDumper.main(HeapDumper.java:83)
    ... 6 more


问:
Serilog does not write log to file while using InProcess hosting model in ASP.NET Core 2.2
If I use newly introduced InProcess hosting model in ASP.NET Core 2.2 as follows:

<PropertyGroup>
  <TargetFramework>netcoreapp2.2</TargetFramework>
  <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
```

<p><code>Serilog</code> does not write log to file. but if I remove <code><AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel></code> from <code>.csproj</code> everything works as expected.</p>

<p>My <code>Serilog</code> configuration in the <code>Program</code> class as follows:</p>

```public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information() // Set the minimun log level
            .WriteTo.File("Logs\\log-.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7) // this is for logging into file system
            .CreateLogger();

        try
        {
            Log.Information("Starting web host");
            CreateWebHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
        }
        finally
        {
            Log.CloseAndFlush();
        }

    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging(logging => { logging.ClearProviders(); }) // clearing all other logging providers
            .UseSerilog(); // Using serilog
}
```

Any thought from the expert please!

答: Try to upgrade .Net Core version. This issue seems to be fixed in 2.2.3 .</p>

Body:
If I use newly introduced InProcess hosting model in ASP.NET Core 2.2 as follows:

<PropertyGroup>
  <TargetFramework>netcoreapp2.2</TargetFramework>
  <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>

Serilog does not write log to file. but if I remove <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> from .csproj everything works as expected.

My Serilog configuration in the Program class as follows:

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Information() // Set the minimun log level
            .WriteTo.File("Logs\\log-.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7) // this is for logging into file system
            .CreateLogger();

        try
        {
            Log.Information("Starting web host");
            CreateWebHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
        }
        finally
        {
            Log.CloseAndFlush();
        }

    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging(logging => { logging.ClearProviders(); }) // clearing all other logging providers
            .UseSerilog(); // Using serilog
}

Any thought from the expert please!


问:
How to fix two Knex MySQL queries dependent on each other in a router.get
I am attempting to display data from two database tables on a route using Node, Express and JavaScript. I have connected my Express app to the database using knex, and am attempting to use MySQL SELECT queries to elicit data from the two tables to display on the server.

The data in the 'column' attribute/column in the 'offence_columns' table appears as a column in the 'offences' table, hence why I have two promises, one in which takes the data from the 'column' attribute in the 'offence_columns' table, and the other in which selects the 'area' attribute in the 'offences' table and another attribute/column that is what was selected from the 'columns' attribute.

Since 'column' is a reserved word in MySQL, I have had some issues in selecting it. Using single quote marks like in the code provided provides me with a code in the terminal:

Unhandled rejection Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as 0 from offences' at line 1.

I get the same error if I substitute the single quotes for back ticks (column), but if I try using both ('column') I get a different error:

Error: ER_BAD_FIELD_ERROR: Unknown column 'column' in 'field list'.

I tried using aliases but it didn't seem to help.

```<code>router.get('/api/search/:offence', function(req, res, next) {
  req.db.from('offence_columns').select('column').where('pretty',"=",req.params.offence)
    .then((rows) => {
      req.db.from('offences').select('area', rows)
        .then((rows2) => {
          res.json({"Error" : false, "Message" : "Success", "City" : rows2})
        })
    })
    .catch((err) => {
      console.log(err);
      res.json({"Error" : true, "Message" : "Error in MySQL query"})
    })
});
</code>```

答:
First of all, consider adjusting your schema. column is a really terrible name for a database column... it'll cause all sorts of confusion, as you have already discovered!

However, Knex normally surrounds names with backticks in its output which should avoid the reserved word issue. This is not actually your problem. What you're seeing is the result of trying to issue a query with an array in it:

req.db.from('offences').select('area', rows)
```

<p>Here, <code>rows</code> is an array, which may or may not be empty. It's the result of the previous query.</p>

<p>I suspect what you're looking for is something more along these lines (guesswork, because I don't know what your schema is):</p>

<pre class="lang-js prettyprint-override"><code>db.from("offence_columns")
  .select("column")
  .where("pretty", "=", req.params.offence)
  .then(rows => {
    if (rows.length === 0) {
      res.json({ error: false, message: "No cities matched." });
    }

    req.db
      .from("offences")
      // This assumes that `offence_columns` has an `area` column
      .where("area", "=", rows[0].area)
      .then(areas => {
        res.json({ Error: false, Message: "Success", city: areas[0] });
      });
  });
</code>```

There are still a number of problems here. For one thing, what if either query can return more than one result? Furthermore, you're probably better off with a join in the first place:

db
  .select('city')
  .from('offence_columns')
  .join('offences', 'offence_columns.area', '=', 'offences.area')
  .where('pretty', '=', req.params.offence)
```

However, it's all guesswork without knowing what your schema looks like.

Body:
I am attempting to display data from two database tables on a route using Node, Express and JavaScript. I have connected my Express app to the database using knex, and am attempting to use MySQL SELECT queries to elicit data from the two tables to display on the server.

The data in the 'column' attribute/column in the 'offence_columns' table appears as a column in the 'offences' table, hence why I have two promises, one in which takes the data from the 'column' attribute in the 'offence_columns' table, and the other in which selects the 'area' attribute in the 'offences' table and another attribute/column that is what was selected from the 'columns' attribute.

Since 'column' is a reserved word in MySQL, I have had some issues in selecting it. Using single quote marks like in the code provided provides me with a code in the terminal:

Unhandled rejection Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as 0 from offences' at line 1.

I get the same error if I substitute the single quotes for back ticks (column), but if I try using both ('column') I get a different error:

Error: ER_BAD_FIELD_ERROR: Unknown column 'column' in 'field list'.

I tried using aliases but it didn't seem to help.

router.get('/api/search/:offence', function(req, res, next) {
  req.db.from('offence_columns').select('column').where('pretty',"=",req.params.offence)
    .then((rows) => {
      req.db.from('offences').select('area', rows)
        .then((rows2) => {
          res.json({"Error" : false, "Message" : "Success", "City" : rows2})
        })
    })
    .catch((err) => {
      console.log(err);
      res.json({"Error" : true, "Message" : "Error in MySQL query"})
    })
});

Body:
First of all, consider adjusting your schema. column is a really terrible name for a database column... it'll cause all sorts of confusion, as you have already discovered!

However, Knex normally surrounds names with backticks in its output which should avoid the reserved word issue. This is not actually your problem. What you're seeing is the result of trying to issue a query with an array in it:

req.db.from('offences').select('area', rows)

Here, rows is an array, which may or may not be empty. It's the result of the previous query.

I suspect what you're looking for is something more along these lines (guesswork, because I don't know what your schema is):

db.from("offence_columns")
  .select("column")
  .where("pretty", "=", req.params.offence)
  .then(rows => {
    if (rows.length === 0) {
      res.json({ error: false, message: "No cities matched." });
    }

    req.db
      .from("offences")
      // This assumes that `offence_columns` has an `area` column
      .where("area", "=", rows[0].area)
      .then(areas => {
        res.json({ Error: false, Message: "Success", city: areas[0] });
      });
  });

There are still a number of problems here. For one thing, what if either query can return more than one result? Furthermore, you're probably better off with a join in the first place:

db
  .select('city')
  .from('offence_columns')
  .join('offences', 'offence_columns.area', '=', 'offences.area')
  .where('pretty', '=', req.params.offence)

However, it's all guesswork without knowing what your schema looks like.


问:
I want to know why an error occurred when I sent an array to view with jquery ajax (django,jquery)
hello I have a question

I am trying to implement row delete with jquery ajax.

I sent an array to view in jquery ajax

At this time error has occured. The contents of the error are as follows.

error message:

```<code>During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\django_inflearn2\todo\views.py", line 23, in todo_delete_ajax
    todo_ids = request.POST['todo_arr']
  File "C:\django_inflearn2\venv\lib\site-packages\django\utils\datastructures.py", line 80, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'todo_arr'
[02/Jun/2019 06:11:29] "POST /todo/todo_delete_ajax/ HTTP/1.1" 500 19607

</code>```

if you know what is the reason and how fix plase let me know

thanks~!

jquery , ajax

```<code>$('#todo_delete_button').click(function(e){
    e.preventDefault();
    // todo_check
    alert("삭제 버튼 ")
    // Get checked checkboxes
    var todo_arr = [];
    $('.td_check').each(function() {
        if (jQuery(this).is(":checked")) {
            var id = this.id;
            todo_arr.push(id);
        }
    });
    alert('todo_arr : '+ todo_arr)

    $.ajax({
      type: "POST",
      url: 'todo_delete_ajax/',
      data: {
          todo_arr:todo_arr,
          csrfmiddlewaretoken: '{{ csrf_token }}'
      },
        success: function(result) {
            alert('todo_delete_ajax is success ');
        }
    });
})
</code>```

and

url pattern

```<code>    path('todo_delete_ajax/',views.todo_delete_ajax, name ="todo_delete_ajax"),

</code>```

view

```<code>
def todo_delete_ajax(request):
    # print("request " , request )
    todo_ids = request.POST['todo_arr']
    print("todo_ids : ", todo_ids)

    return redirect('/todo/')

</code>```

答:
I see that you're simply trying to send the ids of checkboxes that are checked to the server.

What this means is that if there are no checked checkboxes, then todo_arr becomes null

You need to give a chance to this occurrence this way:

```<code>def todo_delete_ajax(request):
    todo_ids = request.POST.get("todo_arr", None)

    // check if there are any todos
    if todo_ids:
        print("todo_ids : ", todo_ids)
        return redirect('/todo/')

    // else, do something else
</code>```

request.POST.get ensures that if todo_arr is empty, then todo_ids is None. You're getting that error because you're trying to get what doesn't exist.

Body:
hello I have a question

I am trying to implement row delete with jquery ajax.

I sent an array to view in jquery ajax

At this time error has occured. The contents of the error are as follows.

error message:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\django_inflearn2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\django_inflearn2\todo\views.py", line 23, in todo_delete_ajax
    todo_ids = request.POST['todo_arr']
  File "C:\django_inflearn2\venv\lib\site-packages\django\utils\datastructures.py", line 80, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'todo_arr'
[02/Jun/2019 06:11:29] "POST /todo/todo_delete_ajax/ HTTP/1.1" 500 19607

if you know what is the reason and how fix plase let me know

thanks~!

jquery , ajax

$('#todo_delete_button').click(function(e){
    e.preventDefault();
    // todo_check
    alert("삭제 버튼 ")
    // Get checked checkboxes
    var todo_arr = [];
    $('.td_check').each(function() {
        if (jQuery(this).is(":checked")) {
            var id = this.id;
            todo_arr.push(id);
        }
    });
    alert('todo_arr : '+ todo_arr)

    $.ajax({
      type: "POST",
      url: 'todo_delete_ajax/',
      data: {
          todo_arr:todo_arr,
          csrfmiddlewaretoken: '{{ csrf_token }}'
      },
        success: function(result) {
            alert('todo_delete_ajax is success ');
        }
    });
})

and

url pattern

    path('todo_delete_ajax/',views.todo_delete_ajax, name ="todo_delete_ajax"),

view

def todo_delete_ajax(request):
    # print("request " , request )
    todo_ids = request.POST['todo_arr']
    print("todo_ids : ", todo_ids)

    return redirect('/todo/')

Body:
I see that you're simply trying to send the ids of checkboxes that are checked to the server.

What this means is that if there are no checked checkboxes, then todo_arr becomes null

You need to give a chance to this occurrence this way:

def todo_delete_ajax(request):
    todo_ids = request.POST.get("todo_arr", None)

    // check if there are any todos
    if todo_ids:
        print("todo_ids : ", todo_ids)
        return redirect('/todo/')

    // else, do something else

request.POST.get ensures that if todo_arr is empty, then todo_ids is None. You're getting that error because you're trying to get what doesn't exist.


问:
Retrieving values from an rhandsontable object (R, R shiny)
I use the (awesome) package rhandsontable that will later be included in an R shiny webpage. The user can click at some places, and I want to know how to retrieve the info on which rows was clicked.
Here is an example, (to be copy&paste in an R terminal):

```<code>library(rhandsontable)

## Create the dataset
min = c(1,seq(2,34,by=2))
kmh = c(0,seq(7,23,by=1))
mph = round( kmh / 1.609344, digits=0 )
stop.speed = rep(FALSE, length(min))
DF = data.frame(min, kmh, mph, stop.speed, stringsAsFactors = FALSE)

#plot the table
r = rhandsontable(DF, useTypes = TRUE)
</code>```

I thought about converting it to an R object:

```<code>hot_to_r(r)

Error in (function (data, changes, params, ...)  :
argument "params" is missing, with no default
</code>```

答:
The question is 4 years old, but still relevant for the rhandsontable package users. Also, the solution provided by Lyx above no longer works. Following is an easy fix to the problem.

Every rhandsontable object is a deeply nested list. One of its elements is the data element, which itself is nested under the x element. However, the data is in json format, but it can easily be converted to a data.frame by using the fromJSON() function in the jsonlite package.

```<code>library(rhandsontable)
library(jsonlite)

hands_on_table <- rhandsontable(mtcars)
data_frame <- fromJSON(hands_on_table$x$data)
head(data_frame)

   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
</code>```

Edit:

It is important to also mention that the main difference between using hot_to_r and jsonlite::fromJSON is that the former is used while the app is running and the latter only works in an interactive R session.

Body:
I use the (awesome) package rhandsontable that will later be included in an R shiny webpage. The user can click at some places, and I want to know how to retrieve the info on which rows was clicked.
Here is an example, (to be copy&paste in an R terminal):

library(rhandsontable)

## Create the dataset
min = c(1,seq(2,34,by=2))
kmh = c(0,seq(7,23,by=1))
mph = round( kmh / 1.609344, digits=0 )
stop.speed = rep(FALSE, length(min))
DF = data.frame(min, kmh, mph, stop.speed, stringsAsFactors = FALSE)

#plot the table
r = rhandsontable(DF, useTypes = TRUE)

I thought about converting it to an R object:

hot_to_r(r)

Error in (function (data, changes, params, ...)  :
argument "params" is missing, with no default

Body:
The question is 4 years old, but still relevant for the rhandsontable package users. Also, the solution provided by Lyx above no longer works. Following is an easy fix to the problem.

Every rhandsontable object is a deeply nested list. One of its elements is the data element, which itself is nested under the x element. However, the data is in json format, but it can easily be converted to a data.frame by using the fromJSON() function in the jsonlite package.

library(rhandsontable)
library(jsonlite)

hands_on_table <- rhandsontable(mtcars)
data_frame <- fromJSON(hands_on_table$x$data)
head(data_frame)

   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Edit:

It is important to also mention that the main difference between using hot_to_r and jsonlite::fromJSON is that the former is used while the app is running and the latter only works in an interactive R session.


问:
How can I prevent re-rendering of the page with hooks in React?
i triying to find a solution for this particular problem but i can find it... in new with this, i have this code:

```<code>    import React, { Fragment, useState } from 'react'
import '../../media/style/modal.css'

export default function Modal(props) {
  const { activateModal } = props
const[values, setValues]= useState({name:'',email:''})

  if (activateModal) {
    document.getElementById('modals').click()
  }

  function handleValues(){
    setValues({
      name:document.getElementById('name').value,
      email:document.getElementById('email').value
    })
  }

  return (
    <Fragment>

      <button type="button" id="modals" style={{ display: 'none' }} data-toggle="modal" data-target="#exampleModalCenter">
        Launch demo modal
</button>

      <div className="modal fade" id="exampleModalCenter" tabIndex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div className="modal-dialog modal-dialog-centered" role="document">
          <div className="modal-content">
            <form onSubmit={handleSubmit}>
            <div className="container">
              <div className="row">
                <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">×</span>
                </button>
              </div>
              <div className="row justify-content-center">
                <h5 className="modal-title" id="modalTitle"><span style={{color:'rgb(197,115,199)'}}>get- </span>started</h5>
              </div>
              <div className="row justify-content-center">
                <input type="text" id="name" name="name"  onChange={handleValues} />
                <input type="email"  id="email" name="email" />
              </div>
              <div className="row justify-content-center">

                <button type="submit" id="btn2">Send</button>

              </div>
            </div>

            </form>

          </div>
        </div>
      </div>

    </Fragment>
  )

}
</code>```

When i write something in the input, my page re renders... and i dont know how to stop this behavior,any idea?... i try to use useRef but i dont know if im using it right so i dont get the desired effect

答:
I copied your code to a sandbox and fixed it up for you https://codesandbox.io/s/agitated-snow-lls4g?fontsize=14

Just to clarify, useRef will not re-render, even if you mutate it. The updated value will only show when something else triggers a re-render. so useState was the correct usage.

Although I did not change this for you (in order to show that it is possible without it) I would highly recommend putting email and name in their own useState's so that changing the one does not change the other. I would also not get the values from document.getElementById but rather use event.target.value that is passed in from the handleChange, and give a handleChange for each element. If you got multiple elements, use functional programming to create their functions. (e.g. handleEmailChange = handleChange('email') and then handleChange is a function that returns a function (also known as currying).

To clarify:

useRef is to keep data between renders(updating does not fire re-rendering)

useState is to keep data between renders(updating will fire re-rendering)

each input should probably use its own state to avoid changing values that other components and effects might subscribe to.

use currying to compute a handleChange for each input

Body:
i triying to find a solution for this particular problem but i can find it... in new with this, i have this code:

    import React, { Fragment, useState } from 'react'
import '../../media/style/modal.css'

export default function Modal(props) {
  const { activateModal } = props
const[values, setValues]= useState({name:'',email:''})

  if (activateModal) {
    document.getElementById('modals').click()
  }

  function handleValues(){
    setValues({
      name:document.getElementById('name').value,
      email:document.getElementById('email').value
    })
  }

  return (
    <Fragment>

      <button type="button" id="modals" style={{ display: 'none' }} data-toggle="modal" data-target="#exampleModalCenter">
        Launch demo modal
</button>

            <form onSubmit={handleSubmit}>

                <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                  ×
                </button>

get- started

                <input type="text" id="name" name="name"  onChange={handleValues} />
                <input type="email"  id="email" name="email" />

                <button type="submit" id="btn2">Send</button>

            </form>

    </Fragment>
  )

}

When i write something in the input, my page re renders... and i dont know how to stop this behavior,any idea?... i try to use useRef but i dont know if im using it right so i dont get the desired effect


问:
animate CSS3 gradient-positions using jQuery
Is it possible to animate the position of a CSS3-gradient-color using jQuery?

I'd like to animate from this

```<code>background: -moz-linear-gradient(top, #FF0000 0%, #FF0000 0%, #FFFFFF 0%,
   #FFFFFF 100%); /* firefox */

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#FF0000), color-stop(0%,#FF0000),
    color-stop(0%,#FFFFFF), color-stop(100%,#FFFFFF)); /* webkit */
</code>```

to this

```<code>background: -moz-linear-gradient(top, #FF0000 0%, #FF0000 50%, #FFFFFF 50%,
    #FFFFFF 100%); /* firefox */

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#FF0000),
    color-stop(50%,#FF0000), color-stop(50%,#FFFFFF), color-stop(100%,#FFFFFF)); /* webkit */
</code>```

in xx milliseconds

thank you in advance!

答:
You can make the gradient twice as big (meaning incorporate the first gradient in the first 50%, and the second gradient in the last 50%) as it needs to and use this code:

```<code>-webkit-background-size: 200%;
-moz-background-size: 200%;
-o-background-size: 200%;
-ms-background-size: 200%;
background-size: 200%;
</code>```

on the initial item and.
Not all the prefixes will work, but I do it for compatibility if they add it later

```<code>background-position:bottom;
</code>```

On the hover

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to animate the position of a CSS3-gradient-color using jQuery?

I'd like to animate from this

background: -moz-linear-gradient(top, #FF0000 0%, #FF0000 0%, #FFFFFF 0%,
   #FFFFFF 100%); /* firefox */

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#FF0000), color-stop(0%,#FF0000),
    color-stop(0%,#FFFFFF), color-stop(100%,#FFFFFF)); /* webkit */

to this

background: -moz-linear-gradient(top, #FF0000 0%, #FF0000 50%, #FFFFFF 50%,
    #FFFFFF 100%); /* firefox */

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#FF0000),
    color-stop(50%,#FF0000), color-stop(50%,#FFFFFF), color-stop(100%,#FFFFFF)); /* webkit */

in xx milliseconds

thank you in advance!

Body:
You can make the gradient twice as big (meaning incorporate the first gradient in the first 50%, and the second gradient in the last 50%) as it needs to and use this code:

-webkit-background-size: 200%;
-moz-background-size: 200%;
-o-background-size: 200%;
-ms-background-size: 200%;
background-size: 200%;

on the initial item and.
Not all the prefixes will work, but I do it for compatibility if they add it later

background-position:bottom;

On the hover