问:
How to use 'create-hive-table' with Sqoop correctly?
I'm trying to import data from MySQL table to Hive using Sqoop. From what I understood there are 2 ways of doing that.

Import data into HDFS and then create External Table in Hive and load data into that table.

Use create-hive-table while running Sqoop query to create a new table in Hive and directly load data into that. I am trying to do this but can't do it for some reason

This is my code

```<code>sqoop import \
--connect jdbc:mysql://localhost/EMPLOYEE \
--username root \
--password root \
--table emp \
--m 1 \
--hive-database sqoopimport \
--hive-table sqoopimport.employee \
--create-hive-table \
--fields-terminated-by ',';
</code>```

I tried using --hive-import as well but got error.
When I ran the above query, job was successful but there was no table created in hive as well as data was stored in \user\HDFS\emp\ location where \HDFS\emp was created during the job.

PS: Also I could not find any reason for using --m 1 with Sqoop. It's just there in all queries.

答:
I got the import working with following query. There is no need to write create-hive-table we can just write new table name with hive-table and that table will be created. Also if there is any issue then go to hive-metastore location and run rm *.lck then try import again.

```<code>sqoop import \
--connect jdbc:mysql://localhost/EMPLOYEE \
--username root \
--password root \
--table emp4 \
--hive-import \
--hive-table sqoopimport.emp4 \
--fields-terminated-by "," ;
</code>```

Body:
I'm trying to import data from MySQL table to Hive using Sqoop. From what I understood there are 2 ways of doing that.

Import data into HDFS and then create External Table in Hive and load data into that table.

Use create-hive-table while running Sqoop query to create a new table in Hive and directly load data into that. I am trying to do this but can't do it for some reason

This is my code

sqoop import \
--connect jdbc:mysql://localhost/EMPLOYEE \
--username root \
--password root \
--table emp \
--m 1 \
--hive-database sqoopimport \
--hive-table sqoopimport.employee \
--create-hive-table \
--fields-terminated-by ',';

I tried using --hive-import as well but got error.
When I ran the above query, job was successful but there was no table created in hive as well as data was stored in \user\HDFS\emp\ location where \HDFS\emp was created during the job.

PS: Also I could not find any reason for using --m 1 with Sqoop. It's just there in all queries.

Body:
I got the import working with following query. There is no need to write create-hive-table we can just write new table name with hive-table and that table will be created. Also if there is any issue then go to hive-metastore location and run rm *.lck then try import again.

sqoop import \
--connect jdbc:mysql://localhost/EMPLOYEE \
--username root \
--password root \
--table emp4 \
--hive-import \
--hive-table sqoopimport.emp4 \
--fields-terminated-by "," ;


来源: stackexchange

问:
Accessing the associated string of a stringstream object
I am trying to access the associated string of a stringstream object and keep iterators to it, but am not able to know whether this would be safe. Here is the code :

```<code>  stringstream HTMLss;   // string stream of HTML document

  // ... (load up HTMLss with HTML)

  const string & HTMLstr = HTMLss.str();   // grab reference to associated string
  string::const_iterator begin,end;
  begin = HTMLstr.begin();                 // grab iterators to that string as well
  end = HTMLstr.end();
  boost::match_results<std::string::const_iterator> matches;

  // do some processing, updating the iterators along the way
  while( boost::regex_search(begin, end, matches, metaexp) )
    {
      string key( matches[1].first, matches[1].second );
      string raw_val( matches[2].first, matches[2].second );

      // ... some processing which does NOT manipulate HTMLss stringstream in any way

      begin = matches[2].second;   // updating the iterator
    }
</code>```

My question is -- is the above safe to do ? Can it be assumed that one can keep/update iterators that point to the associated string of the stringstream object, and that the behavior is going to be correct? There are no other calls to any string stream function. How can one know whether this is safe or not?

答:
It's safe but for a another reason than you probably think. HTMLss.str() returns a copy of the internal string, and this copy is bound to a const reference. As per C++ rules a temporary that is bound to a local const reference has the lifetime of the reference. So basically the code you posted is almost equivalent to this:

```<code>string HTMLstr = HTMLss.str();
</code>```

The only difference is that this version may call the copy constructor. This call may be optimized away though.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to access the associated string of a stringstream object and keep iterators to it, but am not able to know whether this would be safe. Here is the code :

  stringstream HTMLss;   // string stream of HTML document

  // ... (load up HTMLss with HTML)

  const string & HTMLstr = HTMLss.str();   // grab reference to associated string
  string::const_iterator begin,end;
  begin = HTMLstr.begin();                 // grab iterators to that string as well
  end = HTMLstr.end();
  boost::match_results<std::string::const_iterator> matches;

  // do some processing, updating the iterators along the way
  while( boost::regex_search(begin, end, matches, metaexp) )
    {
      string key( matches[1].first, matches[1].second );
      string raw_val( matches[2].first, matches[2].second );

      // ... some processing which does NOT manipulate HTMLss stringstream in any way

      begin = matches[2].second;   // updating the iterator
    }

My question is -- is the above safe to do ? Can it be assumed that one can keep/update iterators that point to the associated string of the stringstream object, and that the behavior is going to be correct? There are no other calls to any string stream function. How can one know whether this is safe or not?

Body:
It's safe but for a another reason than you probably think. HTMLss.str() returns a copy of the internal string, and this copy is bound to a const reference. As per C++ rules a temporary that is bound to a local const reference has the lifetime of the reference. So basically the code you posted is almost equivalent to this:

string HTMLstr = HTMLss.str();

The only difference is that this version may call the copy constructor. This call may be optimized away though.


问:
Error:No such property: FOR_RUNTIME for class: org.gradle.api.attributes.Usage
I am using android studio 3.0 and  classpath com.android.tools.build:gradle:3.0.0 and distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
and got the compile issue

Error:No such property: FOR_RUNTIME for class:
  org.gradle.api.attributes.Usage

Please help me out of this.

答:
i also faced the same issue i solved it by updating the gradle version
Update Gradle version to 4.2.1

ContentLicense: CC BY-SA 3.0


问:
NSURLConnection delegate methods are not being called
I am trying to download a set of files from a  web server using NSURLConnection but at the point the connection appears to be made, the connection's delegate methods never get fired and so the file never gets downloaded.  I have read many answers on SO and other sources and have tried the fixes that have been advised but to no avail, which makes me think I have made a different mistake here.

I have a viewController (InitViewController.m) which loads another class's method:

```<code>GetData *getDataInstance = [[GetData alloc] init];
[getDataInstance startUpdate];
</code>```

GetData.m then does some checking and runs the class in charge of getting the files:

```<code>GetFiles *getFilesInstance = [[GetFiles alloc] init];
[getFilesInstance doFilesNeedDownloading];
</code>```

doFilesNeedDowngoading method checks to see if we need the file and then runs getFiles:

```<code>-(void)getFile//:(NSString *) fullURL
{

    // I have checked if the connection is run on the main thread and it is
    NSLog(@"Is%@ main thread", ([NSThread isMainThread] ? @"" : @" NOT"));

    NSURL *downloadURL = [NSURL URLWithString:fullURL];

    NSMutableURLRequest *dlRequest = [NSMutableURLRequest requestWithURL:downloadURL];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:dlRequest delegate:self];

    [theConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

    [theConnection start];

    if(theConnection) { //me checking for connection which is 'true'
        NSLog(@"Connection for %@ worked", fullURL);
    } else {
        NSLog(@"Connection for %@ failed", fullURL);
    }

}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    responseData = [[NSMutableData alloc] init];
    NSString *fileName = [[NSURL URLWithString:fullURL] lastPathComponent];
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:fileName];
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [file seekToEndOfFile];

}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [responseData appendData:data];
    [file seekToEndOfFile];
    [file writeData:data];

}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    [file closeFile];

}
</code>```

I did originally fire the getDataInstance startUpdate in a separate thread in an update to have the 'getting data' part of the app separate to the 'UI building' part of the app and thought this might be the issue but for now I have remove that and even put in'[theConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]' as per other answers to this kind of question on SO.

I'm sure there will be something really obvious that I have missed, any ideas?

Thanks,

EDIT

I have now tried this code again but in the initViewController so this is pretty much the first thing that is fired when the app loads.  This is no longer in another class or thread etc.:

```<code>-(void)getFile
{
    fullURL = @"http://myURL.com/terms-and-conditions.txt";
    NSURL *downloadURL = [NSURL URLWithString:fullURL];
    NSMutableURLRequest *dlRequest = [NSMutableURLRequest requestWithURL:downloadURL];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:dlRequest delegate:self];

    [theConnection start];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    responseData = [[NSMutableData alloc] init];
    NSString *fileName = [[NSURL URLWithString:fullURL] lastPathComponent];
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:fileName];
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [file seekToEndOfFile];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [responseData appendData:data];
    [file seekToEndOfFile];
    [file writeData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    [file closeFile];
}
</code>```

getFile gets fired but it's delegate methods still don't get fired?

答:
In the end I re-wrote the whole class and got the delegates firing.

```<code>NSString *currentURL = [NSString stringWithFormat:@"%@/api/sync", apiURL];
NSLog(@"URL = %@", currentURL);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:currentURL]];
[request addValue:@"application/json" forHTTPHeaderField:(@"Accept")];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
</code>```

Here are the delegates that now fire:

```<code>- (void)connection:(FileURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
    NSString *fileName = [[response URL] lastPathComponent];
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:fileName];
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    connection.file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
}
- (void)connection:(FileURLConnection *)connection didReceiveData:(NSData *)data
{
    [connection.file writeData:data];
}
- (NSCachedURLResponse *)connection:(FileURLConnection *)connection willCacheResponse:(NSCachedURLResponse*)cachedResponse
{
    return nil;
}
- (void)connectionDidFinishLoading:(FileURLConnection *)connection
{
    [connection.file closeFile];
}
- (void)connection:(FileURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"GetFiles - didFailWithError - error : %@ for URL %@", error, connection.currentRequest.URL);
}
</code>```

The class now downloads the file (from my own API) and saves it on the device.

Body:
I am trying to download a set of files from a  web server using NSURLConnection but at the point the connection appears to be made, the connection's delegate methods never get fired and so the file never gets downloaded.  I have read many answers on SO and other sources and have tried the fixes that have been advised but to no avail, which makes me think I have made a different mistake here.

I have a viewController (InitViewController.m) which loads another class's method:

GetData *getDataInstance = [[GetData alloc] init];
[getDataInstance startUpdate];

GetData.m then does some checking and runs the class in charge of getting the files:

GetFiles *getFilesInstance = [[GetFiles alloc] init];
[getFilesInstance doFilesNeedDownloading];

doFilesNeedDowngoading method checks to see if we need the file and then runs getFiles:

-(void)getFile//:(NSString *) fullURL
{

    // I have checked if the connection is run on the main thread and it is
    NSLog(@"Is%@ main thread", ([NSThread isMainThread] ? @"" : @" NOT"));

    NSURL *downloadURL = [NSURL URLWithString:fullURL];

    NSMutableURLRequest *dlRequest = [NSMutableURLRequest requestWithURL:downloadURL];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:dlRequest delegate:self];

    [theConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

    [theConnection start];

    if(theConnection) { //me checking for connection which is 'true'
        NSLog(@"Connection for %@ worked", fullURL);
    } else {
        NSLog(@"Connection for %@ failed", fullURL);
    }

}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    responseData = [[NSMutableData alloc] init];
    NSString *fileName = [[NSURL URLWithString:fullURL] lastPathComponent];
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:fileName];
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [file seekToEndOfFile];

}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [responseData appendData:data];
    [file seekToEndOfFile];
    [file writeData:data];

}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    [file closeFile];

}

I did originally fire the getDataInstance startUpdate in a separate thread in an update to have the 'getting data' part of the app separate to the 'UI building' part of the app and thought this might be the issue but for now I have remove that and even put in'[theConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]' as per other answers to this kind of question on SO.

I'm sure there will be something really obvious that I have missed, any ideas?

Thanks,

EDIT

I have now tried this code again but in the initViewController so this is pretty much the first thing that is fired when the app loads.  This is no longer in another class or thread etc.:

-(void)getFile
{
    fullURL = @"http://myURL.com/terms-and-conditions.txt";
    NSURL *downloadURL = [NSURL URLWithString:fullURL];
    NSMutableURLRequest *dlRequest = [NSMutableURLRequest requestWithURL:downloadURL];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:dlRequest delegate:self];

    [theConnection start];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    responseData = [[NSMutableData alloc] init];
    NSString *fileName = [[NSURL URLWithString:fullURL] lastPathComponent];
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:fileName];
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [file seekToEndOfFile];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [responseData appendData:data];
    [file seekToEndOfFile];
    [file writeData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    [file closeFile];
}

getFile gets fired but it's delegate methods still don't get fired?

Body:
In the end I re-wrote the whole class and got the delegates firing.

NSString *currentURL = [NSString stringWithFormat:@"%@/api/sync", apiURL];
NSLog(@"URL = %@", currentURL);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:currentURL]];
[request addValue:@"application/json" forHTTPHeaderField:(@"Accept")];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

Here are the delegates that now fire:

- (void)connection:(FileURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
    NSString *fileName = [[response URL] lastPathComponent];
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:fileName];
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    connection.file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
}
- (void)connection:(FileURLConnection *)connection didReceiveData:(NSData *)data
{
    [connection.file writeData:data];
}
- (NSCachedURLResponse *)connection:(FileURLConnection *)connection willCacheResponse:(NSCachedURLResponse*)cachedResponse
{
    return nil;
}
- (void)connectionDidFinishLoading:(FileURLConnection *)connection
{
    [connection.file closeFile];
}
- (void)connection:(FileURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"GetFiles - didFailWithError - error : %@ for URL %@", error, connection.currentRequest.URL);
}

The class now downloads the file (from my own API) and saves it on the device.


问:
Cannot update data in MySQL Database using mysqli
Hello can someone assist me im failing to update the data in my mysql database</p>

```<code><?php
    require "connection.php";

    $item_name = "cheese";
    $item_code = 123;
    $item_description = "cheese is good";
    $item_unit_price  = 235;

    $mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description = '$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name')";

    //execute the query
    $result = mysqli_query($conn,$mysql_query);

    if($conn->query($mysql_query) ===TRUE){

    echo "Stock Item Updated Successfully";

    }else{

        echo 'Error'.$mysql_query."<br>".$conn->error;
    }

    $conn->close();

    ?>
</code>```

答: first try to remove the closing bracket,remove one of the query execution by commenting this //$result = mysqli_query($conn,$mysql_query);out

Body:
Hello can someone assist me im failing to update the data in my mysql database

<?php
    require "connection.php";

    $item_name = "cheese";
    $item_code = 123;
    $item_description = "cheese is good";
    $item_unit_price  = 235;

    $mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description = '$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name')";

    //execute the query
    $result = mysqli_query($conn,$mysql_query);

    if($conn->query($mysql_query) ===TRUE){

    echo "Stock Item Updated Successfully";

    }else{

        echo 'Error'.$mysql_query."
".$conn->error;
    }

    $conn->close();

    ?>


问:
How to make click reveal in css/js?
Just want to know how to make click reveal when I click a button the word
"Phone" will change to "+971235051"

```<code><button type="button" class="btn btn-primary">Phone</button>
<span>+971235051</span>
</code>```

Any hint for this?I found a toggle, But can't find for click reveal.

Thankyou

答:
Create a function and user innerHTML to change the text of the button

function changeText(elem) {
  elem.innerHTML = "+971235051"

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" class="btn btn-primary" onclick="changeText(this)">Phone</button></code>```

Title: How to make click reveal in css/js?

Body:
Just want to know how to make click reveal when I click a button the word
"Phone" will change to "+971235051"

<button type="button" class="btn btn-primary">Phone</button>
+971235051

Any hint for this?I found a toggle, But can't find for click reveal.

Thankyou

Body:
Create a function and user innerHTML to change the text of the button

function changeText(elem) {
  elem.innerHTML = "+971235051"

}

<button type="button" class="btn btn-primary" onclick="changeText(this)">Phone</button>


问:
IOS 11 GoogleMaps crash on device (iphone 5s)
Xcode 8.3.2
iphone 5s ios 11
GoogleMaps 2.4

I getting error and crash in viewContoller

```<code>@IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() { }
</code>```

Logs:

```<code>CoreData: annotation:  Failed to load optimized model at path '/var/containers/Bundle/Application/2D2D05FB-A524-4594-B222-69B58E038E9A/Medico.app/GoogleMaps.bundle/GMSCacheStorage.momd/Storage.omo'
CoreData: annotation:  Failed to load optimized model at path '/var/containers/Bundle/Application/2D2D05FB-A524-4594-B222-69B58E038E9A/Medico.app/GoogleMaps.bundle/GMSCacheStorage.momd/Storage.omo'
CoreData: annotation:  Failed to load optimized model at path '/var/containers/Bundle/Application/2D2D05FB-A524-4594-B222-69B58E038E9A/Medico.app/GoogleMaps.bundle/GMSCacheStorage.momd/Storage.omo'
2017-09-21 16:02:08.805064+0300 Medico[2552:187180] [Common] _BSMachError: port 1187f; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND"
</code>```

It happens only in IOS 11

答:
Upgrade to Google Maps SDK 2.5.0 and compile with Xcode 9.It will fix the issue.

https://developers.google.com/places/ios-api/releases

Check 2.5.0 release notes.

Body:
Xcode 8.3.2
iphone 5s ios 11
GoogleMaps 2.4

I getting error and crash in viewContoller

@IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() { }

Logs:

CoreData: annotation:  Failed to load optimized model at path '/var/containers/Bundle/Application/2D2D05FB-A524-4594-B222-69B58E038E9A/Medico.app/GoogleMaps.bundle/GMSCacheStorage.momd/Storage.omo'
CoreData: annotation:  Failed to load optimized model at path '/var/containers/Bundle/Application/2D2D05FB-A524-4594-B222-69B58E038E9A/Medico.app/GoogleMaps.bundle/GMSCacheStorage.momd/Storage.omo'
CoreData: annotation:  Failed to load optimized model at path '/var/containers/Bundle/Application/2D2D05FB-A524-4594-B222-69B58E038E9A/Medico.app/GoogleMaps.bundle/GMSCacheStorage.momd/Storage.omo'
2017-09-21 16:02:08.805064+0300 Medico[2552:187180] [Common] _BSMachError: port 1187f; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND"

It happens only in IOS 11


问:
Cheerio get option values from select class
I'm trying to get all the values from a list of options in a select class:

```<code><select class="list_items">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
</code>```

How can I achieve this in cheerio?

答:
Use:</p>

```<code>const $ = require('cheerio');

$(".list_items option").each(() => {
    console.log($(this).val());
});
</code>```

Body:
I'm trying to get all the values from a list of options in a select class:

<select class="list_items">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

How can I achieve this in cheerio?

Body:
Use:

const $ = require('cheerio');

$(".list_items option").each(() => {
    console.log($(this).val());
});


问:
redirect www to non www url using Javascript
Hello I have this code but in this code it's redirect non www to www but i want www to non www.

Please check my script and then tell me how to do this Thanks

```<code> <script type="text/javascript">
if ( document.domain.substring(0,4) != 'www.' ) {
window.location = document.URL.replace("//","//www.");

}
</script>
</code>```

答:
You can do somthing like this</p>

```<code><script type="text/javascript">
if (window.location.hostname.indexOf("www") == 0) {
    window.location = window.location.href.replace("www.","");
}
</script>
</code>```

Body:
You can do somthing like this

<script type="text/javascript">
if (window.location.hostname.indexOf("www") == 0) {
    window.location = window.location.href.replace("www.","");
}
</script>


问:
MS Word mail merge, multiple columns into rows, dynamic table
im creating a invoice template for mail merge using Word. In my source excel sheet, each row represent different invoice, but each invoice can have one or two items. I want to list this items in dynamic table inside my Word document. So if particular invoice has one item, i want the table to have one row, if the invoice have two items i want the table to have two rows. Columns in my source excel are: InvoiceNumber, Date, InvoiceItem1Value, InvoiceItem2Value. So the last two columns represents my invoice items, if they are both filled, then the table in my output document will have 2 rows, each containing one of the value. If only one column will be filled, then the output table will have only one row with a value from that filled column. Can you tell me how to do that?</p>

答:
What you are seeking is a Many-to-one mail merge.  Mail merge wizard by default performs one-to-one mail merge i.e. it creates one document for each row in Excel. In your case if an invoice has two items, it will create two documents.

If you are looking for an online many-to-one mail merge, try EDocGen. If your organization is less rigid with security, you may also try add-ins from Graham Mayor and Doug Robbins. Incidentally, I published a blog for many-to-one mail merge few weeks back with a similar use case.


问:
Return referenced sheet name within an formula in excel
Is there a way to check which spreadsheet is being referenced within a formula.

For example, I have the following reference =('2015'!A1) and I need to check which sheet I am using in the reference. In this example it's "2015". But sometimes I changes to "2016", sometimes to "2012"... Is there a way to check or return the referenced sheet within the formula? Preferably without VBA.

答:
If you have that specific format with brackets and your formulas are simple as your example, this will do the trick:</p>

```<code>=MID(FORMULATEXT(A1),FIND("(",FORMULATEXT(A1))+1,FIND("!",FORMULATEXT(A1))-FIND("(",FORMULATEXT(A1))-1)
</code>```

Body:
If you have that specific format with brackets and your formulas are simple as your example, this will do the trick:

=MID(FORMULATEXT(A1),FIND("(",FORMULATEXT(A1))+1,FIND("!",FORMULATEXT(A1))-FIND("(",FORMULATEXT(A1))-1)


问:
How do I automatically update the value of a variable when a data is changed in ionic 3?
I am trying to get total price of the orders made that I have stored in an array. The code looks something like this.

```<code>import { Component } from '@angular/core';
import { Config } from '../config';
var ordersArray = [

];
@Component({
  selector: 'orders-page',
  templateUrl : 'orders.html'
})

export class Orders{
  public orders = ordersArray;
  public config = new Config;
  public addOrder(item){
    ordersArray.push(item);
  }
  public clearOrders(){
    var length = this.orders.length;
    for(let i = 0; i < length; i++){
      ordersArray.pop();
    }
  }
  public total = this.getPrice();
  public getPrice(){
    let price = 0;
    for(let order of ordersArray){
      price = (parseInt(order.item.price) * parseInt(order.quantity) ) + price;
    }
    return price;
  }
  public clearOrder(order){
    for(let i = 0;i < this.orders.length;i++){
      if(order.title == this.orders[i].title){
        ordersArray.splice(i,1);
      }
    }
  }
}
</code>```

And the template, I have {{total}}.
Now, when I remove an element from the ordersArray, I want the {{total}} to automatically update. How do I do that ?

答:
You need to include getPrice() function every time price is concerned.
For example, when you add a new order, when you delete one order, when you delete them all...

I think you can improve some code:

```<code>  public clearOrders(){
    ordersArray = ordersArray[];
  }
</code>```

And I can't see why you wrote public orders = ordersArray; but afterwards you are using ordersArray.

Be careful because you are mixing ordersArray and orders within the ordersArray() function, and I think you should be only using one.

Regards.

Body:
I am trying to get total price of the orders made that I have stored in an array. The code looks something like this.

import { Component } from '@angular/core';
import { Config } from '../config';
var ordersArray = [

];
@Component({
  selector: 'orders-page',
  templateUrl : 'orders.html'
})

export class Orders{
  public orders = ordersArray;
  public config = new Config;
  public addOrder(item){
    ordersArray.push(item);
  }
  public clearOrders(){
    var length = this.orders.length;
    for(let i = 0; i < length; i++){
      ordersArray.pop();
    }
  }
  public total = this.getPrice();
  public getPrice(){
    let price = 0;
    for(let order of ordersArray){
      price = (parseInt(order.item.price) * parseInt(order.quantity) ) + price;
    }
    return price;
  }
  public clearOrder(order){
    for(let i = 0;i < this.orders.length;i++){
      if(order.title == this.orders[i].title){
        ordersArray.splice(i,1);
      }
    }
  }
}

And the template, I have {{total}}.
Now, when I remove an element from the ordersArray, I want the {{total}} to automatically update. How do I do that ?

Body:
You need to include getPrice() function every time price is concerned.
For example, when you add a new order, when you delete one order, when you delete them all...

I think you can improve some code:

  public clearOrders(){
    ordersArray = ordersArray[];
  }

And I can't see why you wrote public orders = ordersArray; but afterwards you are using ordersArray.

Be careful because you are mixing ordersArray and orders within the ordersArray() function, and I think you should be only using one.

Regards.


问:
Two array combine or flipped
I have this two arrays:

```<code>array:4 [▼
  0 => 518
  1 => 519
  2 => 520
  3 => 521
]
</code>```

and this one:

```<code>array:4 [▼
  0 => "1"
  1 => "2"
  2 => "3"
  3 => "3"
]
</code>```

Can someone please help me how to achieve like this..

```<code>array:4 [▼
 518=>1
  519=> 2
 520 => 3
  521 => 3
]
</code>```

I do not know if it is possible or not like

答:
You can use built in function array_combine to achieve this:

```<code>$arr1 =array(
  0 => 518,
  1 => 519,
  2 => 520,
  3 => 521,
);

$arr2 =array(
  0 => "1",
  1 => "2",
  2 => "3",
  3 => "3",
);
$new_array = array_combine($arr1,$arr2);
print_r($new_array);
</code>```

DEMO

Title: Two array combine or flipped

Body:
I have this two arrays:

array:4 [▼
  0 => 518
  1 => 519
  2 => 520
  3 => 521
]

and this one:

array:4 [▼
  0 => "1"
  1 => "2"
  2 => "3"
  3 => "3"
]

Can someone please help me how to achieve like this..

array:4 [▼
 518=>1
  519=> 2
 520 => 3
  521 => 3
]

I do not know if it is possible or not like

Body:
You can use built in function array_combine to achieve this:

$arr1 =array(
  0 => 518,
  1 => 519,
  2 => 520,
  3 => 521,
);

$arr2 =array(
  0 => "1",
  1 => "2",
  2 => "3",
  3 => "3",
);
$new_array = array_combine($arr1,$arr2);
print_r($new_array);

DEMO


问:
Spring transaction Manager:cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'
I am trying to use spring transaction in my project.I have following xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-4.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-4.1.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
    <tx:annotation-driven />
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@xyz:1521:orcl" />
        <property name="username" value="TESTSPRING" />
        <property name="password" value="TESTSPRING" />
    </bean>
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>
</code>```

but getting following error on server start-up

```<code>Caused by: org.xml.sax.SAXParseException; lineNumber: 15; columnNumber: 29; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'.
</code>```

答:
Add dependency for spring-tx. Add below dependency to your pom.xml

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.1.1.RELEASE</version>
</dependency>
</code>```

Body:
I am trying to use spring transaction in my project.I have following xml

    <?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-4.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-4.1.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
    <tx:annotation-driven />
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@xyz:1521:orcl" />
        <property name="username" value="TESTSPRING" />
        <property name="password" value="TESTSPRING" />
    </bean>
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

but getting following error on server start-up

Caused by: org.xml.sax.SAXParseException; lineNumber: 15; columnNumber: 29; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'.

Body:
Add dependency for spring-tx. Add below dependency to your pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.1.1.RELEASE</version>
</dependency>


答: Take a closer look at stringstream's str method.  It returns a copy of the string, not a reference to a string object.  So in theory, as long as you, yourself do not change the string your iterators won't be invalidated.</p>

Title: Accessing the associated string of a stringstream object

Body:
I am trying to access the associated string of a stringstream object and keep iterators to it, but am not able to know whether this would be safe. Here is the code :

  stringstream HTMLss;   // string stream of HTML document

  // ... (load up HTMLss with HTML)

  const string & HTMLstr = HTMLss.str();   // grab reference to associated string
  string::const_iterator begin,end;
  begin = HTMLstr.begin();                 // grab iterators to that string as well
  end = HTMLstr.end();
  boost::match_results<std::string::const_iterator> matches;

  // do some processing, updating the iterators along the way
  while( boost::regex_search(begin, end, matches, metaexp) )
    {
      string key( matches[1].first, matches[1].second );
      string raw_val( matches[2].first, matches[2].second );

      // ... some processing which does NOT manipulate HTMLss stringstream in any way

      begin = matches[2].second;   // updating the iterator
    }

My question is -- is the above safe to do ? Can it be assumed that one can keep/update iterators that point to the associated string of the stringstream object, and that the behavior is going to be correct? There are no other calls to any string stream function. How can one know whether this is safe or not?


答:
You can use :focus for this. check updated snippet below...

.num, button:focus .txt  {
  display: none;
}
button:focus .num {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" class="btn btn-primary"><span class="txt">Phone</span>
<span class="num">+971235051</span>
</button></code>```

Title: How to make click reveal in css/js?

Body:
You can use :focus for this. check updated snippet below...

.num, button:focus .txt  {
  display: none;
}
button:focus .num {
  display: block;
}

<button type="button" class="btn btn-primary"><span class="txt">Phone</span>
<span class="num">+971235051</span>
</button>


问:
How can I get those last XML items using xPath or anything else?
I've used the child elements of the first node PovprecnaPlaca before I noticed I need the child elements of the last one.

Picture of XML for reference:

Appreciate all the helpful answers!

XML looks like this:

<PovprecnaPlaca>
   <Datum>2017-07-01T00:00:00</Datum>
   <BrutoPlacaZadnje3Mesece>1603,00</BrutoPlacaZadnje3Mesece>
   <NetoPlacaZadnje3Mesece>1045,12</NetoPlacaZadnje3Mesece>
   <BrutoPlaca>1593,10</BrutoPlaca>
   <NetoPlaca>1039,55</NetoPlaca>
 </PovprecnaPlaca>
 <PovprecnaPlaca>
   <Datum>2017-08-01T00:00:00</Datum>
   <BrutoPlacaZadnje3Mesece>1602,98</BrutoPlacaZadnje3Mesece>
   <NetoPlacaZadnje3Mesece>1045,45</NetoPlacaZadnje3Mesece>
   <BrutoPlaca>1613,62</BrutoPlaca>
   <NetoPlaca>1051,73</NetoPlaca>
  </PovprecnaPlaca>
 </Place>
</PovprecnePlace>
```

答:
Get Datum node from the last PovprecnaPlaca of each Place.

```<code>var nodes = xdoc.XPathSelectElements("//PovprecnaPlaca[last()]/Datum");
</code>```

Get the text inside each node.

```<code>List<string> results = nodes.Select(d => d.Value).ToList();
</code>```

Two reasons why your attemp didn't work: 1) It starts from root node "/" of the document and there's no PovprecnaPlaca node at this level. 2) By calling text() it's getting XText which raises an exception in Linq as it expects nodes as a result when calling XPathSelectElements().

Body:
Get Datum node from the last PovprecnaPlaca of each Place.

var nodes = xdoc.XPathSelectElements("//PovprecnaPlaca[last()]/Datum");

Get the text inside each node.

List<string> results = nodes.Select(d => d.Value).ToList();

Two reasons why your attemp didn't work: 1) It starts from root node "/" of the document and there's no PovprecnaPlaca node at this level. 2) By calling text() it's getting XText which raises an exception in Linq as it expects nodes as a result when calling XPathSelectElements().


问:
Invalid Trigger Exception
I am a newcomer in ORACLE SQL, I am trying to create a trigger to generate auto_incement serial number as a primary key in my table but no idea what mistake I am making, due to which I am getting :

error while performing partial saving of event: error code=4098 ST=
  java.sql.BatchUpdateException: ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n, caused by : \"ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n\"

My SQL Statement is :

```<code>create global temporary table STAGING_ERROR_REASON (   STAGING_REASON_ID number(4) constraint STAGING_REASON_ID not null   ,REASON nvarchar2(1024) not null   ,constraint PK_STAGING_REASON_ID PRIMARY KEY(STAGING_REASON_ID) );

create sequence STAGING_SEQ_ERROR_REASON start with 1 increment by 1 minvalue 1 maxvalue 10000;

CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
   BEFORE INSERT ON STAGING_ERROR_REASON
   REFERENCING NEW AS NEW
   FOR EACH ROW
BEGIN
   if(:NEW.STAGING_REASON_ID is null) then
      SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL
          INTO :NEW.STAGING_REASON_ID
   END;

ALTER TRIGGER "STAGING_TRIGGER_ERROR_REASON" ENABLE;
</code>```

答:
You have two errors:

Your IF has no END IF

Your SELECT INTO has no FROM

But the select is not necessary to begin with, you can simply assign the sequence value:

```<code>CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
   BEFORE INSERT ON STAGING_ERROR_REASON
   REFERENCING NEW AS NEW
   FOR EACH ROW
BEGIN
   if :NEW.STAGING_REASON_ID is null then
      :NEW.STAGING_REASON_ID := STAGING_SEQ_ERROR_REASON.NEXTVAL;
   END IF; --<< missing
END;
/
</code>```

Not sure how and where you ran your PL/SQL, but you typically also need a / at the end of a PL/SQL block.

Title: Invalid Trigger Exception

Body:
I am a newcomer in ORACLE SQL, I am trying to create a trigger to generate auto_incement serial number as a primary key in my table but no idea what mistake I am making, due to which I am getting :

error while performing partial saving of event: error code=4098 ST=
  java.sql.BatchUpdateException: ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n, caused by : \"ORA-04098: trigger
  'TNTCA.STAGING_TRIGGER_ERROR_REASON' is invalid and failed
  re-validation\n\"

My SQL Statement is :

create global temporary table STAGING_ERROR_REASON (   STAGING_REASON_ID number(4) constraint STAGING_REASON_ID not null   ,REASON nvarchar2(1024) not null   ,constraint PK_STAGING_REASON_ID PRIMARY KEY(STAGING_REASON_ID) );

create sequence STAGING_SEQ_ERROR_REASON start with 1 increment by 1 minvalue 1 maxvalue 10000;

CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
   BEFORE INSERT ON STAGING_ERROR_REASON
   REFERENCING NEW AS NEW
   FOR EACH ROW
BEGIN
   if(:NEW.STAGING_REASON_ID is null) then
      SELECT STAGING_SEQ_ERROR_REASON.NEXTVAL
          INTO :NEW.STAGING_REASON_ID
   END;

ALTER TRIGGER "STAGING_TRIGGER_ERROR_REASON" ENABLE;

Body:
You have two errors:

Your IF has no END IF

Your SELECT INTO has no FROM

But the select is not necessary to begin with, you can simply assign the sequence value:

CREATE OR REPLACE TRIGGER "STAGING_TRIGGER_ERROR_REASON"
   BEFORE INSERT ON STAGING_ERROR_REASON
   REFERENCING NEW AS NEW
   FOR EACH ROW
BEGIN
   if :NEW.STAGING_REASON_ID is null then
      :NEW.STAGING_REASON_ID := STAGING_SEQ_ERROR_REASON.NEXTVAL;
   END IF; --<< missing
END;
/

Not sure how and where you ran your PL/SQL, but you typically also need a / at the end of a PL/SQL block.


问:
EventListener on Embedded of different Forms
I have created a form with a  collection of other forms in symfony 3. After Submitting I want to manipulate different Datas. How can I get access of it and how can I set them ?

This is how I tried it:

```<code>    public function registerAction(Request $request)
{
    $register = $this->createFormBuilder()
        ->add('user', 'AppBundle\Form\Type\UserType', array(
            'data_class' => User::class,
        ))
        ->add('userdata', 'AppBundle\Form\Type\UserdataType', array(
            'data_class' => Userdata::class,
        ))
        ->add('addresses', 'AppBundle\Form\Type\AddressesType', array(
            'data_class' => Addresses::class,
        ))
        ->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event){
            $user = $event->getForm()->get('user')->getData();
            $address = $event->getForm()->get('addresses')->getData();
            $address->setSalutation($user->getSalutation());
        })
        ->getForm();

    $register->handleRequest($request);

    if ($register->isSubmitted()) {

        // do stuff
    }
    return $this->render('form/login_index.html.twig', [
        'register' => $register->createView()
    ]);
}
</code>```

In this example:

```<code>$user = $event->getForm()->get('user')->getData();
$address = $event->getForm()->get('addresses')->getData();
$address->setSalutation($user->getSalutation());
</code>```

答:
You should integrate the object you are working on as a parameter for your createFormBuilder($object) method.
For example:

```<code>$user = new User();
$form = $formFactory
    ->createBuilder($user)
    ->add('username', TextType::class);
</code>```

And then you add your subscriber, in this case the $event->getData() is an object of the class User

```<code>$form->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        /** @var User $user */
        $user = $event->getData();
        $form = $event->getForm();

        // Your logic here ...
})->getForm();
</code>```

UPDATE:

If you have an embedded form (property in relation with the parent class), example UserInformations you can simply make a call with:

```<code>$form
     ->add('informations', UserInformationType::class)
     ->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {

        /** @var User $user */
        $user = $event->getData();
        /** @var UserInformation $userInformation */
        $userInformation = $user->getInformation();

        $form = $event->getForm();

        // Your logic here ...
})->getForm();
</code>```

Good luck.

Body:
I have created a form with a  collection of other forms in symfony 3. After Submitting I want to manipulate different Datas. How can I get access of it and how can I set them ?

This is how I tried it:

    public function registerAction(Request $request)
{
    $register = $this->createFormBuilder()
        ->add('user', 'AppBundle\Form\Type\UserType', array(
            'data_class' => User::class,
        ))
        ->add('userdata', 'AppBundle\Form\Type\UserdataType', array(
            'data_class' => Userdata::class,
        ))
        ->add('addresses', 'AppBundle\Form\Type\AddressesType', array(
            'data_class' => Addresses::class,
        ))
        ->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event){
            $user = $event->getForm()->get('user')->getData();
            $address = $event->getForm()->get('addresses')->getData();
            $address->setSalutation($user->getSalutation());
        })
        ->getForm();

    $register->handleRequest($request);

    if ($register->isSubmitted()) {

        // do stuff
    }
    return $this->render('form/login_index.html.twig', [
        'register' => $register->createView()
    ]);
}

In this example:

$user = $event->getForm()->get('user')->getData();
$address = $event->getForm()->get('addresses')->getData();
$address->setSalutation($user->getSalutation());

Body:
You should integrate the object you are working on as a parameter for your createFormBuilder($object) method.
For example:

$user = new User();
$form = $formFactory
    ->createBuilder($user)
    ->add('username', TextType::class);

And then you add your subscriber, in this case the $event->getData() is an object of the class User

$form->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        /** @var User $user */
        $user = $event->getData();
        $form = $event->getForm();

        // Your logic here ...
})->getForm();

UPDATE:

If you have an embedded form (property in relation with the parent class), example UserInformations you can simply make a call with:

$form
     ->add('informations', UserInformationType::class)
     ->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {

        /** @var User $user */
        $user = $event->getData();
        /** @var UserInformation $userInformation */
        $userInformation = $user->getInformation();

        $form = $event->getForm();

        // Your logic here ...
})->getForm();

Good luck.


问:
A puzzle about time complexity calculation and real time consumption
While learning the basic knowledge of algorithm, I find puzzle about the time complexity calculation and the real time consumption when run the codes.

The demo codes specify the problem.

```<code>function calcDemo1(){
    var init = 0;
    for(var i=0;i<40;i++){
        init += 0;
    }
    return init;
}

function calcDemo2(){
    var init = 0;
    init += (0+1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39);
    return init;
}
</code>```

Does calcDemo1's time complexity is O(1) even if it's a "for loop"?

In case their time complexity were both O(1), do they take the same amount of time in the worst-case scenario when run the code?

The relative question is here

答:
Both of them have constant time complexity. O(1) time complexity.

For case-1 there is an for loop but it runs 40 times. So it will be of constant time complexity.

In the second case, no for loop is there, but it is still contant time addition. So it is O(1) again.

It doesn't mean that if there is for loop it's complexity can't be constant.

As reply to the comment, yes even if we increase the hardcoded value then the time complexity won't change. It will be still O(1).

ContentLicense: CC BY-SA 4.0

Body:
While learning the basic knowledge of algorithm, I find puzzle about the time complexity calculation and the real time consumption when run the codes.

The demo codes specify the problem.

function calcDemo1(){
    var init = 0;
    for(var i=0;i<40;i++){
        init += 0;
    }
    return init;
}

function calcDemo2(){
    var init = 0;
    init += (0+1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39);
    return init;
}

Does calcDemo1's time complexity is O(1) even if it's a "for loop"?

In case their time complexity were both O(1), do they take the same amount of time in the worst-case scenario when run the code?

The relative question is here


问:
AnimateLayoutChanges doesn't work with RecyclerView
I have a screen with a Recyclerview and others Elements inside of LinearLayout. The problem is when I remove a item of the RecyclerView, animateLayoutChanges doesn't work in this case. Does anayone know why this happen??

XML

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alvaro.resizetest.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:animateLayoutChanges="true"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:id="@+id/test1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorAccent"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LinearLayout"
            android:textColor="#FFFFFF"
            android:textSize="22sp"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/test2"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimaryDark"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LinearLayout"
            android:textColor="#FFFFFF"
            android:textSize="22sp"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/test3"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorAccent"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LinearLayout"
            android:textColor="#FFFFFF"
            android:textSize="22sp"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/test4"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimaryDark"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LinearLayout"
            android:textColor="#FFFFFF"
            android:textSize="22sp"/>
    </LinearLayout>

</LinearLayout>
</code>```

JAVA

```<code>public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);

    Adapter adapter = new Adapter();

    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);
    recyclerView.setNestedScrollingEnabled(true);

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            view.setVisibility(View.GONE);
        }
    };

    findViewById(R.id.test1).setOnClickListener(listener);
    findViewById(R.id.test2).setOnClickListener(listener);
    findViewById(R.id.test3).setOnClickListener(listener);
    findViewById(R.id.test4).setOnClickListener(listener);

}

class Adapter extends RecyclerView.Adapter<Adapter.Holder>{

    int size = 3;

    public Adapter() {
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = getLayoutInflater().inflate(R.layout.item, parent, false);

        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(Holder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return size;
    }

    class Holder extends RecyclerView.ViewHolder {

        public Holder(final View itemView) {
            super(itemView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    size --;
                    notifyItemRemoved(getAdapterPosition());
                }
            });

        }
    }
}
</code>```

答:
What worked for me was simply adding the following code to onCreate:

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    ((ViewGroup) findViewById(R.id.llRoot)).getLayoutTransition()
        .enableTransitionType(LayoutTransition.CHANGING);
}
</code>```

where llRoot is your LinearLayout containing RecyclerView.

You do need to keep android:animateLayoutChanges="true" on your LinearLayout, otherwise it crashes.

I believe if you want to support this below JellyBean, you would need your custom solution.

Explanation on the solution is here: https://proandroiddev.com/the-little-secret-of-android-animatelayoutchanges-e4caab2fddec

Body:
I have a screen with a Recyclerview and others Elements inside of LinearLayout. The problem is when I remove a item of the RecyclerView, animateLayoutChanges doesn't work in this case. Does anayone know why this happen??

XML

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alvaro.resizetest.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:animateLayoutChanges="true"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:id="@+id/test1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorAccent"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LinearLayout"
            android:textColor="#FFFFFF"
            android:textSize="22sp"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/test2"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimaryDark"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LinearLayout"
            android:textColor="#FFFFFF"
            android:textSize="22sp"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/test3"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorAccent"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LinearLayout"
            android:textColor="#FFFFFF"
            android:textSize="22sp"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/test4"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimaryDark"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LinearLayout"
            android:textColor="#FFFFFF"
            android:textSize="22sp"/>
    </LinearLayout>

</LinearLayout>

JAVA

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);

    Adapter adapter = new Adapter();

    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);
    recyclerView.setNestedScrollingEnabled(true);

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            view.setVisibility(View.GONE);
        }
    };

    findViewById(R.id.test1).setOnClickListener(listener);
    findViewById(R.id.test2).setOnClickListener(listener);
    findViewById(R.id.test3).setOnClickListener(listener);
    findViewById(R.id.test4).setOnClickListener(listener);

}

class Adapter extends RecyclerView.Adapter<Adapter.Holder>{

    int size = 3;

    public Adapter() {
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = getLayoutInflater().inflate(R.layout.item, parent, false);

        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(Holder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return size;
    }

    class Holder extends RecyclerView.ViewHolder {

        public Holder(final View itemView) {
            super(itemView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    size --;
                    notifyItemRemoved(getAdapterPosition());
                }
            });

        }
    }
}

Body:
What worked for me was simply adding the following code to onCreate:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    ((ViewGroup) findViewById(R.id.llRoot)).getLayoutTransition()
        .enableTransitionType(LayoutTransition.CHANGING);
}

where llRoot is your LinearLayout containing RecyclerView.

You do need to keep android:animateLayoutChanges="true" on your LinearLayout, otherwise it crashes.

I believe if you want to support this below JellyBean, you would need your custom solution.

Explanation on the solution is here: https://proandroiddev.com/the-little-secret-of-android-animatelayoutchanges-e4caab2fddec


问:
Teradata Studio Express: new install on Mac, not working
I just installed Teradata Express Studio (16.10.01) on MacOS Sierra 10.12.6, but when I try to open it I get the message 'An error has occurred'. The log file shows this (just first lines):

```<code>    !SESSION 2017-09-28 15:55:21.661 -----------------------------------------------
    eclipse.buildId=unknown
    java.version=9
java.vendor=Oracle Corporation
BootLoader constants: OS=macosx, ARCH=x86_64, WS=cocoa, NL=en_GB
Framework arguments:  -keyring /Users/KULMAK/.eclipse_keyring
Command-line arguments:  -os macosx -ws cocoa -arch x86_64 -keyring /Users/KULMAK/.eclipse_keyring

!ENTRY org.eclipse.equinox.ds 4 0 2017-09-28 15:55:26.460
!MESSAGE Exception occurred while creating new instance of component Component[
    name = ConnectionService
    activate = activate
    deactivate = deactivate
    modified =
    configuration-policy = optional
    factory = null
    autoenable = true
    immediate = false
    implementation = com.teradata.datatools.connection.services.impl.ConnectionService
    state = Unsatisfied
    properties =
    serviceFactory = false
    serviceInterface = [com.teradata.datatools.connection.services.interfaces.IConnectionService]
    references = null
    located in bundle = com.teradata.datatools.connection.services.definition_15.11.0.201708101349 [29]
]
!STACK 0
java.lang.NoClassDefFoundError: java/sql/SQLException
    at java.base/java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredConstructors(Class.java:3110)
    at java.base/java.lang.Class.getConstructor0(Class.java:3315)
    at java.base/java.lang.Class.newInstance(Class.java:530)
    at org.eclipse.equinox.internal.ds.model.ServiceComponent.createInstance(ServiceComponent.java:493)
</code>```

Prior to that I installed not-the-latest version of Java JDK 8 (Java 1.8), for compatibility reasons with other pieces of software - not that it matters, even if I install JDK 9, the issues remain the same.

Any ideas what could be causing issues?
Thanks for help!

答: Problem solved - it turns out there was a 'hidden' Java version 9 installed on my Mac that didn't appear in System Preferences (where you could see only Java 8), but became apparent after checking java --version in the terminal. After uninstalling Java 9 all my problems were solved.

Body:
I just installed Teradata Express Studio (16.10.01) on MacOS Sierra 10.12.6, but when I try to open it I get the message 'An error has occurred'. The log file shows this (just first lines):

    !SESSION 2017-09-28 15:55:21.661 -----------------------------------------------
    eclipse.buildId=unknown
    java.version=9
java.vendor=Oracle Corporation
BootLoader constants: OS=macosx, ARCH=x86_64, WS=cocoa, NL=en_GB
Framework arguments:  -keyring /Users/KULMAK/.eclipse_keyring
Command-line arguments:  -os macosx -ws cocoa -arch x86_64 -keyring /Users/KULMAK/.eclipse_keyring

!ENTRY org.eclipse.equinox.ds 4 0 2017-09-28 15:55:26.460
!MESSAGE Exception occurred while creating new instance of component Component[
    name = ConnectionService
    activate = activate
    deactivate = deactivate
    modified =
    configuration-policy = optional
    factory = null
    autoenable = true
    immediate = false
    implementation = com.teradata.datatools.connection.services.impl.ConnectionService
    state = Unsatisfied
    properties =
    serviceFactory = false
    serviceInterface = [com.teradata.datatools.connection.services.interfaces.IConnectionService]
    references = null
    located in bundle = com.teradata.datatools.connection.services.definition_15.11.0.201708101349 [29]
]
!STACK 0
java.lang.NoClassDefFoundError: java/sql/SQLException
    at java.base/java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredConstructors(Class.java:3110)
    at java.base/java.lang.Class.getConstructor0(Class.java:3315)
    at java.base/java.lang.Class.newInstance(Class.java:530)
    at org.eclipse.equinox.internal.ds.model.ServiceComponent.createInstance(ServiceComponent.java:493)

Prior to that I installed not-the-latest version of Java JDK 8 (Java 1.8), for compatibility reasons with other pieces of software - not that it matters, even if I install JDK 9, the issues remain the same.

Any ideas what could be causing issues?
Thanks for help!


问:
Mixing named parameters with regular parameters
When I try to call a function such as this:

```<code>Columns.AddColumn("Caption", "U_Fam_ItmsGrpCod", 20, False)
</code>```

But using named arguments like so:

```<code>Columns.AddColumn(Caption := "Caption", Field := "U_Fam_ItmsGrpCod", 20, False)
</code>```

The compiler pops an error, expecting all parameters to be named. In other words, it forces me to either name ALL the paramenters, or name none of them. Is there a way to mix these two ways of using function parameters? For example, naming 2 parameters out of 6.

Additionally, is there a way to automatically name VB.NET parameters that is compatible with Visual Studio?

Thank you.

答:
You should take note for this explanation when mixing arguments by name and position as given in Passing Arguments by Position and by Name in VB.NET:

When you supply arguments by a mixture of position and name, the
  positional arguments must all come first. Once you supply an argument
  by name, the remaining arguments must all be by name.

Hence, this assignment is incorrect:

```<code>Columns.AddColumn(Caption := "Caption", Field := "U_Fam_ItmsGrpCod", 20, False)
</code>```

The correct way is providing all arguments as named arguments from first place, like this example:

```<code>Columns.AddColumn(Caption := "Caption", Field := "U_Fam_ItmsGrpCod", OtherArgument1 := 20, OtherArgument2 := False)
</code>```

Or you can omit named arguments for two first arguments and assign named arguments for remaining ones:

```<code>Columns.AddColumn("Caption", "U_Fam_ItmsGrpCod", OtherArgument1 := 20, OtherArgument2 := False)
</code>```

Body:
When I try to call a function such as this:

Columns.AddColumn("Caption", "U_Fam_ItmsGrpCod", 20, False)

But using named arguments like so:

Columns.AddColumn(Caption := "Caption", Field := "U_Fam_ItmsGrpCod", 20, False)

The compiler pops an error, expecting all parameters to be named. In other words, it forces me to either name ALL the paramenters, or name none of them. Is there a way to mix these two ways of using function parameters? For example, naming 2 parameters out of 6.

Additionally, is there a way to automatically name VB.NET parameters that is compatible with Visual Studio?

Thank you.

Body:
You should take note for this explanation when mixing arguments by name and position as given in Passing Arguments by Position and by Name in VB.NET:

When you supply arguments by a mixture of position and name, the
  positional arguments must all come first. Once you supply an argument
  by name, the remaining arguments must all be by name.

Hence, this assignment is incorrect:

Columns.AddColumn(Caption := "Caption", Field := "U_Fam_ItmsGrpCod", 20, False)

The correct way is providing all arguments as named arguments from first place, like this example:

Columns.AddColumn(Caption := "Caption", Field := "U_Fam_ItmsGrpCod", OtherArgument1 := 20, OtherArgument2 := False)

Or you can omit named arguments for two first arguments and assign named arguments for remaining ones:

Columns.AddColumn("Caption", "U_Fam_ItmsGrpCod", OtherArgument1 := 20, OtherArgument2 := False)


问:
Active mq consumers count decreasing to 0
We are facing a weird problem in which the activemq consumers for some random queues are decreasing till they become 0 after which they are not able to recover.
Once this happens we have to redeploy the consumer application again to start processing.
We have been struggling with this issue for some time but could not figure out the root cause.

activemq broker version 5.14.5

following is the connection configuration.

```<code><bean id="activeMQIconnectConnectionFactory" class="test.ActiveMQIconnectConnectionFactory">
        <property name="brokerURL" value="failover:(tcp://localhost:61616)"/>
        <property name="prefetchPolicy" ref="prefetchPolicy"/>
        <property name="redeliveryPolicy" ref="redeliveryPolicy"/>
        <property name="trustAllPackages" value="true"/>
        <!-- http://activemq.apache.org/consumer-dispatch-async.html
        The default setting is dispatchAsync=true
         If you want better thoughput and the chances of having a slow consumer are low, you may want to change this to false.
         -->
        <property name="dispatchAsync" value="true"/>
        <!--
        whether or not timestamps on messages should be disabled or not. If you disable them it adds a small performance boost.
         Default is false
         -->
        <property name="disableTimeStampsByDefault" value="true"/>

        <!-- http://activemq.apache.org/optimized-acknowledgement.html
        This option is disabled by default but can be used to improve throughput in some circumstances as it decreases load on the broker.
         -->
        <property name="optimizeAcknowledge" value="true"/>
        <!-- Default 300ms
        For us, 5 sec.
         -->
        <property name="optimizeAcknowledgeTimeOut" value="5000"/>
        <property name="useAsyncSend" value="true"/>
        <property name="exceptionListener" ref="jmsExceptionListener"/>
    </bean>

 <bean id="testQueue" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg index="0" value="test.queue"/>
    </bean>

    <bean id="jmsProducerFactoryPool" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop"
          init-method="start">
        <property name="connectionFactory" ref="activeMQIconnectConnectionFactory"/>
        <property name="maxConnections" value="10"/>
        <property name="maximumActiveSessionPerConnection"
                  value="1000"/>
        <property name="createConnectionOnStartup" value="true"/>
    </bean>

    <bean id="jmsConsumerFactoryPool" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop"
          init-method="start">
        <property name="connectionFactory" ref="activeMQIconnectConnectionFactory"/>
        <property name="maxConnections" value="10"/>
        <property name="maximumActiveSessionPerConnection"               value="1000"/>
        <property name="createConnectionOnStartup" value="true"/>
        <property name="reconnectOnException" value="true"/>
        <property name="idleTimeout" value="86400000"/>
    </bean>

    <bean id="redeliveryPolicy" class="org.apache.activemq.RedeliveryPolicy">
        <property name="maximumRedeliveries" value="1"/>
        <property name="queue" value="*"/>
    </bean>

    <bean id="prefetchPolicy" class="org.apache.activemq.ActiveMQPrefetchPolicy">
        <property name="queuePrefetch" value="500"/>
    </bean>

    <bean id="jmsTemplate" class="com.minda.iconnect.jms.impl.TimedJmsTemplate">
        <property name="connectionFactory" ref="jmsProducerFactoryPool"/>
        <property name="defaultDestinationName" value="iconnect.queue"/>
        <property name="deliveryPersistent" value="true"/>
        <!-- I think this is ingored if explicitQosEnabled is not set -->
    </bean>

    <bean id="simpleMessageConverter" class="org.springframework.jms.support.converter.SimpleMessageConverter"/>

<bean id="testProducer"
          class="com.test.TestProducer">
        <property name="consumerDestination" ref="testQueu"/>
        <property name="jmsTemplate" ref="jmsTemplate"/>
        <property name="messageConverter" ref="simpleMessageConverter"/>
    </bean>

    <bean id="testContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="jmsConsumerFactoryPool"/>
        <property name="destination" ref="testS"/>
        <property name="messageListener">
            <bean class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
                <property name="delegate" ref="testConsumer"/>
                <property name="defaultListenerMethod" value="process"/>
                <property name="messageConverter" ref="simpleMessageConverter"/>
            </bean>
        </property>
        <property name="concurrentConsumers" value="50"/>
        <property name="maxConcurrentConsumers" value="100"/>
        <property name="sessionTransacted" value="false"/>
        <property name="autoStartup" value="true"/>
    </bean>
</beans>
</code>```

class for connectionFactory

```<code>public class ActiveMQIconnectConnectionFactory extends org.apache.activemq.ActiveMQConnectionFactory
{
    private static final Logger LOG = LoggerFactory.getLogger(ActiveMQIconnectConnectionFactory.class);

    @Override
    public void setBrokerURL(String brokerURL)
    {
        // LOG when connecting to activemq
        // using this setter to be sure it's only logged once
        // See DJ-5780
        LOG.info("ActiveMQ configured is: " + (DEFAULT_BROKER_URL.equals(brokerURL) ? "(default init setting) " : "") + brokerURL);
        LOG.info("Connecting to ActiveMQ");
        super.setBrokerURL(brokerURL);
    }
}
</code>```

Till now we have been playing around the parameters for timeouts etc but not luck.
We suspect that the issue is occurring due to some connection issue or handling of connections via DMLC, but could not identify the problem. Help is highly appreciated!

答:
I think that your problem is a mix of Spring DMLC and AMQ behaviors based on your configurations affecting each other.

try by changing :

```<code><property name="optimizeAcknowledgeTimeOut" value="500"/>
</code>```

AND

org.springframework.jms.listener.DefaultMessageListenerContainer.setReceiveTimeout(0);

Or

```<code>org.springframework.jms.listener.DefaultMessageListenerContainer.setReceiveTimeout(10000);
org.springframework.jms.listener.DefaultMessageListenerContainer.setIdleTaskExecutionLimit(100);
</code>```

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jms/listener/AbstractPollingMessageListenerContainer.html#setReceiveTimeout-long-

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jms/listener/DefaultMessageListenerContainer.html#setIdleTaskExecutionLimit-int-

public void setIdleTaskExecutionLimit(int
  idleTaskExecutionLimit) Specify the limit for idle executions of a
  consumer task, not having received any message within its execution.
  If this limit is reached, the task will shut down and leave receiving
  to other executing tasks. The default is 1, closing idle resources
  early once a task didn't receive a message. This applies to dynamic
  scheduling only; see the "maxConcurrentConsumers" setting. The minimum
  number of consumers (see "concurrentConsumers") will be kept around
  until shutdown in any case.

Within each task execution, a number of message reception attempts
  (according to the "maxMessagesPerTask" setting) will each wait for an
  incoming message (according to the "receiveTimeout" setting). If all
  of those receive attempts in a given task return without a message,
  the task is considered idle with respect to received messages. Such a
  task may still be rescheduled; however, once it reached the specified
  "idleTaskExecutionLimit", it will shut down (in case of dynamic
  scaling).

Raise this limit if you encounter too frequent scaling up and down.
  With this limit being higher, an idle consumer will be kept around
  longer, avoiding the restart of a consumer once a new load of messages
  comes in. Alternatively, specify a higher "maxMessagesPerTask" and/or
  "receiveTimeout" value, which will also lead to idle consumers being
  kept around for a longer time (while also increasing the average
  execution time of each scheduled task).

http://activemq.apache.org/performance-tuning.html

Optimized Acknowledge When consuming messages in auto acknowledge mode
  (set when creating the consumers' session), ActiveMQ can acknowledge
  receipt of messages back to the broker in batches (to improve
  performance). The batch size is 65% of the prefetch limit for the
  Consumer. Also if message consumption is slow the batch will be sent
  every 300ms. You switch batch acknowledgment on by setting
  optimizeAcknowledge=true on the ActiveMQ ConnectionFactory.

http://activemq.apache.org/what-is-the-prefetch-limit-for.html

Once the broker has dispatched a prefetch limit number of messages to
  a consumer it will not dispatch any more messages to that consumer
  until the consumer has acknowledged at least 50% of the prefetched
  messages, e.g., prefetch/2, that it received. When the broker has
  received said acknowledgements it will dispatch a further prefetch/2
  number of messages to the consumer to 'top-up', as it were, its
  prefetch buffer. Note that it's possible to specify a prefetch limit
  on a per consumer basis (see below).

Body:
We are facing a weird problem in which the activemq consumers for some random queues are decreasing till they become 0 after which they are not able to recover.
Once this happens we have to redeploy the consumer application again to start processing.
We have been struggling with this issue for some time but could not figure out the root cause.

activemq broker version 5.14.5

following is the connection configuration.

<bean id="activeMQIconnectConnectionFactory" class="test.ActiveMQIconnectConnectionFactory">
        <property name="brokerURL" value="failover:(tcp://localhost:61616)"/>
        <property name="prefetchPolicy" ref="prefetchPolicy"/>
        <property name="redeliveryPolicy" ref="redeliveryPolicy"/>
        <property name="trustAllPackages" value="true"/>

        <property name="dispatchAsync" value="true"/>

        <property name="disableTimeStampsByDefault" value="true"/>

        <property name="optimizeAcknowledge" value="true"/>

        <property name="optimizeAcknowledgeTimeOut" value="5000"/>
        <property name="useAsyncSend" value="true"/>
        <property name="exceptionListener" ref="jmsExceptionListener"/>
    </bean>

 <bean id="testQueue" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg index="0" value="test.queue"/>
    </bean>

    <bean id="jmsProducerFactoryPool" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop"
          init-method="start">
        <property name="connectionFactory" ref="activeMQIconnectConnectionFactory"/>
        <property name="maxConnections" value="10"/>
        <property name="maximumActiveSessionPerConnection"
                  value="1000"/>
        <property name="createConnectionOnStartup" value="true"/>
    </bean>

    <bean id="jmsConsumerFactoryPool" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop"
          init-method="start">
        <property name="connectionFactory" ref="activeMQIconnectConnectionFactory"/>
        <property name="maxConnections" value="10"/>
        <property name="maximumActiveSessionPerConnection"               value="1000"/>
        <property name="createConnectionOnStartup" value="true"/>
        <property name="reconnectOnException" value="true"/>
        <property name="idleTimeout" value="86400000"/>
    </bean>

    <bean id="redeliveryPolicy" class="org.apache.activemq.RedeliveryPolicy">
        <property name="maximumRedeliveries" value="1"/>
        <property name="queue" value="*"/>
    </bean>

    <bean id="prefetchPolicy" class="org.apache.activemq.ActiveMQPrefetchPolicy">
        <property name="queuePrefetch" value="500"/>
    </bean>

    <bean id="jmsTemplate" class="com.minda.iconnect.jms.impl.TimedJmsTemplate">
        <property name="connectionFactory" ref="jmsProducerFactoryPool"/>
        <property name="defaultDestinationName" value="iconnect.queue"/>
        <property name="deliveryPersistent" value="true"/>

    </bean>

    <bean id="simpleMessageConverter" class="org.springframework.jms.support.converter.SimpleMessageConverter"/>

<bean id="testProducer"
          class="com.test.TestProducer">
        <property name="consumerDestination" ref="testQueu"/>
        <property name="jmsTemplate" ref="jmsTemplate"/>
        <property name="messageConverter" ref="simpleMessageConverter"/>
    </bean>

    <bean id="testContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="jmsConsumerFactoryPool"/>
        <property name="destination" ref="testS"/>
        <property name="messageListener">
            <bean class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
                <property name="delegate" ref="testConsumer"/>
                <property name="defaultListenerMethod" value="process"/>
                <property name="messageConverter" ref="simpleMessageConverter"/>
            </bean>
        </property>
        <property name="concurrentConsumers" value="50"/>
        <property name="maxConcurrentConsumers" value="100"/>
        <property name="sessionTransacted" value="false"/>
        <property name="autoStartup" value="true"/>
    </bean>
</beans>

class for connectionFactory

public class ActiveMQIconnectConnectionFactory extends org.apache.activemq.ActiveMQConnectionFactory
{
    private static final Logger LOG = LoggerFactory.getLogger(ActiveMQIconnectConnectionFactory.class);

    @Override
    public void setBrokerURL(String brokerURL)
    {
        // LOG when connecting to activemq
        // using this setter to be sure it's only logged once
        // See DJ-5780
        LOG.info("ActiveMQ configured is: " + (DEFAULT_BROKER_URL.equals(brokerURL) ? "(default init setting) " : "") + brokerURL);
        LOG.info("Connecting to ActiveMQ");
        super.setBrokerURL(brokerURL);
    }
}

Till now we have been playing around the parameters for timeouts etc but not luck.
We suspect that the issue is occurring due to some connection issue or handling of connections via DMLC, but could not identify the problem. Help is highly appreciated!

Body:
I think that your problem is a mix of Spring DMLC and AMQ behaviors based on your configurations affecting each other.

try by changing :

<property name="optimizeAcknowledgeTimeOut" value="500"/>

AND

org.springframework.jms.listener.DefaultMessageListenerContainer.setReceiveTimeout(0);

Or

org.springframework.jms.listener.DefaultMessageListenerContainer.setReceiveTimeout(10000);
org.springframework.jms.listener.DefaultMessageListenerContainer.setIdleTaskExecutionLimit(100);

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jms/listener/AbstractPollingMessageListenerContainer.html#setReceiveTimeout-long-

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jms/listener/DefaultMessageListenerContainer.html#setIdleTaskExecutionLimit-int-

public void setIdleTaskExecutionLimit(int
  idleTaskExecutionLimit) Specify the limit for idle executions of a
  consumer task, not having received any message within its execution.
  If this limit is reached, the task will shut down and leave receiving
  to other executing tasks. The default is 1, closing idle resources
  early once a task didn't receive a message. This applies to dynamic
  scheduling only; see the "maxConcurrentConsumers" setting. The minimum
  number of consumers (see "concurrentConsumers") will be kept around
  until shutdown in any case.

Within each task execution, a number of message reception attempts
  (according to the "maxMessagesPerTask" setting) will each wait for an
  incoming message (according to the "receiveTimeout" setting). If all
  of those receive attempts in a given task return without a message,
  the task is considered idle with respect to received messages. Such a
  task may still be rescheduled; however, once it reached the specified
  "idleTaskExecutionLimit", it will shut down (in case of dynamic
  scaling).

Raise this limit if you encounter too frequent scaling up and down.
  With this limit being higher, an idle consumer will be kept around
  longer, avoiding the restart of a consumer once a new load of messages
  comes in. Alternatively, specify a higher "maxMessagesPerTask" and/or
  "receiveTimeout" value, which will also lead to idle consumers being
  kept around for a longer time (while also increasing the average
  execution time of each scheduled task).

http://activemq.apache.org/performance-tuning.html

Optimized Acknowledge When consuming messages in auto acknowledge mode
  (set when creating the consumers' session), ActiveMQ can acknowledge
  receipt of messages back to the broker in batches (to improve
  performance). The batch size is 65% of the prefetch limit for the
  Consumer. Also if message consumption is slow the batch will be sent
  every 300ms. You switch batch acknowledgment on by setting
  optimizeAcknowledge=true on the ActiveMQ ConnectionFactory.

http://activemq.apache.org/what-is-the-prefetch-limit-for.html

Once the broker has dispatched a prefetch limit number of messages to
  a consumer it will not dispatch any more messages to that consumer
  until the consumer has acknowledged at least 50% of the prefetched
  messages, e.g., prefetch/2, that it received. When the broker has
  received said acknowledgements it will dispatch a further prefetch/2
  number of messages to the consumer to 'top-up', as it were, its
  prefetch buffer. Note that it's possible to specify a prefetch limit
  on a per consumer basis (see below).


问:
PowerPoint VBA: How to save a pic in a particular file format & not the whole presentation?
I'm using vba in PowerPoint.  I'm trying to compress orginal picture files from a specified folder to a smaller size.  I was able to achieve that.  However, I want to save the new compressed picture into a destination folder.

The following code will save the presenation or slide with the picture.  But I only want the picture.  I'm pretty sure I have to use ActivePresentation.SaveAs.  But it will only let me save the slide.  How can I save the pic alone & not the slide?

Also, I seem to have another problem when I try to save the modified pic.  It saves the presentation into a folder in the destination with a filename of "Slide1.bmp".  Any idea why & how can I change this?

```<code>Dim strSrcPath As String, strDestPath As String
Dim strSrcPic As String
Dim objPic As Shape
Dim x as Integer

strSrcPath = "C:\Temp\Pics\In\"
strDestPath = "C:\Temp\Pics\Out\"

strSrcPic = Dir(strSrcPath)

Do While strSrcPic <> ""
    x = x + 1
    Set objPic = ActiveWindow.Selection.SlideRange.Shapes.AddPicture(FileName:=strSrcPath & strSrcPic, _
        LinkToFile:=msoFalse, SaveWithDocument:=msoTrue, Left:=0, Top:=0, Width:=100, _
        Height:=100)
    With objPic
        .ScaleHeight 1, msoTrue
        .ScaleWidth 1, msoTrue
    End With

    objPic.Select

    ActivePresentation.SaveAs _
        FileName:=strDestPath & "ModPicture(" & x & ").bmp", _
        FileFormat:=ppSaveAsBMP, EmbedTrueTypeFonts:=msoFalse
    objPic.Delete
    strSrcPic = Dir    'Get next entry.
Loop
</code>```

答:
Thanks @JSRWilson for the following response:

"You do have to right click in View >Object Browser >> Show Hidden Members
Assuming objPic is still a reference to the compressed pic

objPic.Export(strDestPath & "& "ModPicture(" & x & ").bmp", ppSaveAsBMP)"

Body:
I'm using vba in PowerPoint.  I'm trying to compress orginal picture files from a specified folder to a smaller size.  I was able to achieve that.  However, I want to save the new compressed picture into a destination folder.

The following code will save the presenation or slide with the picture.  But I only want the picture.  I'm pretty sure I have to use ActivePresentation.SaveAs.  But it will only let me save the slide.  How can I save the pic alone & not the slide?

Also, I seem to have another problem when I try to save the modified pic.  It saves the presentation into a folder in the destination with a filename of "Slide1.bmp".  Any idea why & how can I change this?

Dim strSrcPath As String, strDestPath As String
Dim strSrcPic As String
Dim objPic As Shape
Dim x as Integer

strSrcPath = "C:\Temp\Pics\In\"
strDestPath = "C:\Temp\Pics\Out\"

strSrcPic = Dir(strSrcPath)

Do While strSrcPic <> ""
    x = x + 1
    Set objPic = ActiveWindow.Selection.SlideRange.Shapes.AddPicture(FileName:=strSrcPath & strSrcPic, _
        LinkToFile:=msoFalse, SaveWithDocument:=msoTrue, Left:=0, Top:=0, Width:=100, _
        Height:=100)
    With objPic
        .ScaleHeight 1, msoTrue
        .ScaleWidth 1, msoTrue
    End With

    objPic.Select

    ActivePresentation.SaveAs _
        FileName:=strDestPath & "ModPicture(" & x & ").bmp", _
        FileFormat:=ppSaveAsBMP, EmbedTrueTypeFonts:=msoFalse
    objPic.Delete
    strSrcPic = Dir    'Get next entry.
Loop


问:
How do I allow cross origin request
I am a backend developer and i am providing a spring boot rest API with JWT security to consume for a front end developer who calls the api from local host.So when he calls a POST request he says he gets an CORS error.So I added the part

```<code> @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(request, response);
    }
</code>```

But still he gets the error.What may be the cause.Any help is appreciated

```<code>OPTIONS https:my.domain/url 401 (Unauthorized)
</code>```

when it is a POST request.

Controller code:

```<code>@RestController
public class RegistrationController {

    @Autowired
    @Qualifier("restTemplateUserRegitration")
    private RestTemplate restTemplateUserRegitration;
@RequestMapping(value="${user.endpoint}",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.POST)
    public ResponseEntity<?> registerUser(@RequestBody Model ModelRequest){

                Map<String, Object> Status=new HashMap<String, Object>();
                FeedBackStatus = restTemplateUserRegitration.postForObject("http:serviceurl",registration/single",Model.class,Map.class );
                return ResponseEntity.ok(Status);
    }
}
</code>```

答:
Try this first, this should allow all origins, but it is security risk.</p>

```<code>response.setHeader("Access-Control-Allow-Origin", "*");
</code>```

Title: How do I allow cross origin request

Body:
I am a backend developer and i am providing a spring boot rest API with JWT security to consume for a front end developer who calls the api from local host.So when he calls a POST request he says he gets an CORS error.So I added the part

 @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(request, response);
    }

But still he gets the error.What may be the cause.Any help is appreciated

OPTIONS https:my.domain/url 401 (Unauthorized)

when it is a POST request.

Controller code:

@RestController
public class RegistrationController {

    @Autowired
    @Qualifier("restTemplateUserRegitration")
    private RestTemplate restTemplateUserRegitration;
@RequestMapping(value="${user.endpoint}",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.POST)
    public ResponseEntity<?> registerUser(@RequestBody Model ModelRequest){

                Map<String, Object> Status=new HashMap<String, Object>();
                FeedBackStatus = restTemplateUserRegitration.postForObject("http:serviceurl",registration/single",Model.class,Map.class );
                return ResponseEntity.ok(Status);
    }
}

Body:
Try this first, this should allow all origins, but it is security risk.

response.setHeader("Access-Control-Allow-Origin", "*");


问:
javascript - convert font element to span element using regex
I want to convert  element to  element like this using regex:

Input:

```<code>[some strings...]<span [something]></span><font ...>[sometext]</font>[some strings...]
</code>```

Output:

```<code>[some strings...]<span [something]>[sometext]</span>[some strings...]
</code>```

Note: The input/output is a string.

In shortly, I want to remove the  element and move the contents of that into  element keeping the attributes of the  element.

I've tried this:

```<code>const rx = /<span(.*?)><\/span>([^<\\s]+?|\\s*)<font(?:\\s+[^>]*)?>(.*?)<\/font>/gi;

inputStr.replace(rx, function(match, p1, p2, p3) { return `${p2}<span${p1}>${p3}</span>`; });
</code>```

However it doesn't work.

Can anyone help me?

答:
Use any ID or class selector if possible, I have used here tag name just for example, if you have a Id selector then remove [0] from code.
This or with some modification should work for you

```<code>document.getElementsByTagName("font")[0].replaceWith('<span>' + document.getElementsByTagName("font")[0].innerHTML +'</span>')
</code>```

Using Jquery,

```<code>$("YOUR_DOM_SELECTOR").replaceWith('<span>' + $("YOUR_DOM_SELECTOR").html() +'</span>')
</code>```

Body:
I want to convert  element to  element like this using regex:

Input:

[some strings...][sometext][some strings...]

Output:

[some strings...][sometext][some strings...]

Note: The input/output is a string.

In shortly, I want to remove the  element and move the contents of that into  element keeping the attributes of the  element.

I've tried this:

const rx = /<\/span>([^<\\s]+?|\\s*)]*)?>(.*?)<\/font>/gi;

inputStr.replace(rx, function(match, p1, p2, p3) { return `${p2}<span${p1}>${p3}</span>`; });

However it doesn't work.

Can anyone help me?

Body:
Use any ID or class selector if possible, I have used here tag name just for example, if you have a Id selector then remove [0] from code.
This or with some modification should work for you

document.getElementsByTagName("font")[0].replaceWith('<span>' + document.getElementsByTagName("font")[0].innerHTML +'</span>')

Using Jquery,

$("YOUR_DOM_SELECTOR").replaceWith('<span>' + $("YOUR_DOM_SELECTOR").html() +'</span>')