问:
How to delete a row from UITableView
I'm trying to delete a row from my table view and so far have been unsuccessful. I keep getting this error:

"Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of rows in section 0.  The number of rows contained in an
  existing section after the update (5) must be equal to the number of
  rows contained in that section before the update (5), plus or minus
  the number of rows inserted or deleted from that section (0 inserted,
  1 deleted).'" The array which i use to populate the table view is
  declared in that class, also i get my objects for my array from an
  sqlite db.

The code that i used to try deleting rows is as follows.

```<code>- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source

    [categoryArray objectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
</code>```

Now for the questions i hope to get answered:

-How can i delete rows properly?

-Will i face deleting the row if its the only one left in the tableView?

-Can i change the tableView that is used in the method to be the UITableView i declared in
my .h file?

Many Thanks.

Edit

-Full .m code

```<code>#import "DeleteCategoryTableView.h"
#import "KeyCryptAppAppDelegate.h"

@implementation DeleteCategoryTableView
@synthesize categoryArray;

#pragma mark -
#pragma mark Initialization

-(void) initializeCategoryArray {

sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection];
KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];

const char *sql = [[NSString stringWithFormat:(@"Select Category from Categories;")]cString];

sqlite3_stmt *compiledStatement;

if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK)
{
    while(sqlite3_step(compiledStatement) == SQLITE_ROW)
        [categoryArray addObject:[NSString stringWithUTF8String:(char*) sqlite3_column_text(compiledStatement, 0)]];

}
else {
    NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db));
}
sqlite3_finalize(compiledStatement);
}
/*
- (id)initWithStyle:(UITableViewStyle)style {
// Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
if ((self = [super initWithStyle:style])) {
}
return self;
}
*/
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
self.title = NSLocalizedString(@"Delete Categories",@"Delete your Categories");
categoryArray = [[NSMutableArray alloc]init];
[self initializeCategoryArray];
[super viewDidLoad];

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section    {
// Return the number of rows in the section.
return [self.categoryArray count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...
NSUInteger row = [indexPath row];
cell.text = [categoryArray objectAtIndex:row];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source

    [categoryArray removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    [deleteCategoryTable reloadData];

    NSString *selectedCategory = [categoryArray objectAtIndex:indexPath.row];

    sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection];
    KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];
    const char *sql = [[NSString stringWithFormat:@"Delete from Categories where Category = '%@';", selectedCategory]cString];

    sqlite3_stmt *compiledStatement;

    if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK)
    {
        sqlite3_exec(db,sql,NULL,NULL,NULL);

    }
    else {
        NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db));
    }
    sqlite3_finalize(compiledStatement);
}

else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
/*
 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
 // ...
 // Pass the selected object to the new view controller.
 [self.navigationController pushViewController:detailViewController animated:YES];
 [detailViewController release];
 */
}
#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}

- (void)dealloc {
[super dealloc];
}

@end
</code>```

答:
Read what the problem from the console is.

You have a method numberOfRowsInSection... lets say its set to return 5;.

When you delete a row from the table view you also need to update this method... so its looking for you to return 4; from that method.

Basically you need to make sure that the number of row in your table view is ONE LESS than before you deleted your row.

Title: How to delete a row from UITableView

Body:
I'm trying to delete a row from my table view and so far have been unsuccessful. I keep getting this error:

"Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of rows in section 0.  The number of rows contained in an
  existing section after the update (5) must be equal to the number of
  rows contained in that section before the update (5), plus or minus
  the number of rows inserted or deleted from that section (0 inserted,
  1 deleted).'" The array which i use to populate the table view is
  declared in that class, also i get my objects for my array from an
  sqlite db.

The code that i used to try deleting rows is as follows.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source

    [categoryArray objectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}

Now for the questions i hope to get answered:

-How can i delete rows properly?

-Will i face deleting the row if its the only one left in the tableView?

-Can i change the tableView that is used in the method to be the UITableView i declared in
my .h file?

Many Thanks.

Edit

-Full .m code

#import "DeleteCategoryTableView.h"
#import "KeyCryptAppAppDelegate.h"

@implementation DeleteCategoryTableView
@synthesize categoryArray;

#pragma mark -
#pragma mark Initialization

-(void) initializeCategoryArray {

sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection];
KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];

const char *sql = [[NSString stringWithFormat:(@"Select Category from Categories;")]cString];

sqlite3_stmt *compiledStatement;

if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK)
{
    while(sqlite3_step(compiledStatement) == SQLITE_ROW)
        [categoryArray addObject:[NSString stringWithUTF8String:(char*) sqlite3_column_text(compiledStatement, 0)]];

}
else {
    NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db));
}
sqlite3_finalize(compiledStatement);
}
/*
- (id)initWithStyle:(UITableViewStyle)style {
// Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
if ((self = [super initWithStyle:style])) {
}
return self;
}
*/
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
self.title = NSLocalizedString(@"Delete Categories",@"Delete your Categories");
categoryArray = [[NSMutableArray alloc]init];
[self initializeCategoryArray];
[super viewDidLoad];

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section    {
// Return the number of rows in the section.
return [self.categoryArray count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...
NSUInteger row = [indexPath row];
cell.text = [categoryArray objectAtIndex:row];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source

    [categoryArray removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    [deleteCategoryTable reloadData];

    NSString *selectedCategory = [categoryArray objectAtIndex:indexPath.row];

    sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection];
    KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];
    const char *sql = [[NSString stringWithFormat:@"Delete from Categories where Category = '%@';", selectedCategory]cString];

    sqlite3_stmt *compiledStatement;

    if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK)
    {
        sqlite3_exec(db,sql,NULL,NULL,NULL);

    }
    else {
        NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db));
    }
    sqlite3_finalize(compiledStatement);
}

else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
/*
 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
 // ...
 // Pass the selected object to the new view controller.
 [self.navigationController pushViewController:detailViewController animated:YES];
 [detailViewController release];
 */
}
#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}

- (void)dealloc {
[super dealloc];
}

@end


来源: stackexchange

问:
How do i convert the following xml based spring bean to java annotation based beans?
```<code> <bean id="string.message.service" class="com.ce.indiabringsService">
 <constructor-arg ref="com.ce.indiabrings.consumer" />
 <constructor-arg ref="com.ce.indiabrings.value.function" />
 </bean>
</code>```

I want to convert this to java annotation based bean (@Bean).

答:
```<code>@Configuration
public class MyConfigurationClass {
    @Bean
    public com.ce.indiabringsService getIndiaBringsService() {
        return new com.ce.indiabringsService(com.ce.indiabrings.consumer,com.ce.indiabrings.value.functioncom.ce.indiabrings.consumer);
    }
}
</code>```

And then you can autowire it as follows:

```<code>@Autowired
private com.ce.indiabringsService myIndiaBringsService;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
 <bean id="string.message.service" class="com.ce.indiabringsService">
 <constructor-arg ref="com.ce.indiabrings.consumer" />
 <constructor-arg ref="com.ce.indiabrings.value.function" />
 </bean>

I want to convert this to java annotation based bean (@Bean).

Body:
@Configuration
public class MyConfigurationClass {
    @Bean
    public com.ce.indiabringsService getIndiaBringsService() {
        return new com.ce.indiabringsService(com.ce.indiabrings.consumer,com.ce.indiabrings.value.functioncom.ce.indiabrings.consumer);
    }
}

And then you can autowire it as follows:

@Autowired
private com.ce.indiabringsService myIndiaBringsService;


问:
Failing at inserting company logo in doc header section
I'm trying to insert the logo of my company in the top left of a google doc. I'm trying to get the logo from an URL address. The error I get is a TypeError, it tells me "null is not a function, it is object". Thanks in advance.</p>

```<code>function createMeetingNotesNextTimePeriod() {

 var doc = DocumentApp.create("name of document");
 var header = doc.getHeader();
 var newImage = UrlFetchApp.fetch("URLofLogo").getBlob();
 var image = header().appendImage(newImage);
 image.setHeight(100);
 image.setWidth(100);

}  // functionCreateMeetingNotesNextTimePeriod
</code>```

答:
I see two things that will cause errors, change them both and you should have it.

First:

You haven't created a header yet, you are just trying to get one. Change doc.getHeader() to doc.addHeader(). Now, this would only be with this situation where you don't already have a header, if you had a header then you would use the getHeader().

Second

header is a var not a function. You need to get rid of the parentheses after  header. Like this var image = header.appendImage(newImage)

Suggestion:

Add content type to the urlFetch. Like this.

```<code>var newImage = UrlFetchApp.fetch(url).getBlob().getAs('image/png')
</code>```

You can find a list of acceptable content types here

I don't think it would cause an error without it, but I think it's better to add it.

Body:
I'm trying to insert the logo of my company in the top left of a google doc. I'm trying to get the logo from an URL address. The error I get is a TypeError, it tells me "null is not a function, it is object". Thanks in advance.

function createMeetingNotesNextTimePeriod() {

 var doc = DocumentApp.create("name of document");
 var header = doc.getHeader();
 var newImage = UrlFetchApp.fetch("URLofLogo").getBlob();
 var image = header().appendImage(newImage);
 image.setHeight(100);
 image.setWidth(100);

}  // functionCreateMeetingNotesNextTimePeriod

Body:
I see two things that will cause errors, change them both and you should have it.

First:

You haven't created a header yet, you are just trying to get one. Change doc.getHeader() to doc.addHeader(). Now, this would only be with this situation where you don't already have a header, if you had a header then you would use the getHeader().

Second

header is a var not a function. You need to get rid of the parentheses after  header. Like this var image = header.appendImage(newImage)

Suggestion:

Add content type to the urlFetch. Like this.

var newImage = UrlFetchApp.fetch(url).getBlob().getAs('image/png')

You can find a list of acceptable content types here

I don't think it would cause an error without it, but I think it's better to add it.


问:
Change style of parent element using ng-if directive in child element
I am new to angular js. Depending on the conditions, I change the background of the cells. But I'll be more than just happy if I can to change the background of the entire line.

Here is an example of the code:

```<code><table>
    <thead>
        <tr>
            <td>
                Status
            </td>
            <td>
                Time waiting
            </td>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="item in filteredAgentsDetailedArr">
            <td ng-if="item.name == 'Not Logged'">
                {{ item.name }}
            </td>
            <td ng-if="item.name == 'In Call'"
                ng-style="{backgroundColor: 'green'}">
                {{ item.name }}
            </td>
            <td ng-if="item.name == 'Waiting'"
                ng-style="{backgroundColor: 'red'}">
                {{ item.name }}
            </td>

           <td ng-if="item.time_waiting[6] < 3 && item.time_waiting[4] == 0"
               ng-style="{backgroundColor: 'yellow'}">
               {{ item.time_waiting }}
           </td>
           <td ng-if="item.time_waiting[6] >= 3 && item.time_waiting[4] < 2 ||
                      item.time_waiting[4] == 1 && item.time_waiting[3] == 0"
               ng-style="{backgroundColor: 'gold'}">
               {{ item.time_waiting }}
           <td>
       </tr>
    </tbody>
</table>
</code>```

That is, everything works. But I'd like to add a style(or maybe ng-class) to the entire string and not to one cell. Maybe someone knows how this can be implemented using the ng-if directive?

Thank you in advance!)

答:
Conditional styling is done using the ng-class or the ng-style directives.

Plase, take a look at the oficial documentation: ng-class, ng-style.

Body:
I am new to angular js. Depending on the conditions, I change the background of the cells. But I'll be more than just happy if I can to change the background of the entire line.

Here is an example of the code:

                Status

                Time waiting

                {{ item.name }}

                {{ item.name }}

                {{ item.name }}

           <td ng-if="item.time_waiting[6] < 3 && item.time_waiting[4] == 0"
               ng-style="{backgroundColor: 'yellow'}">
               {{ item.time_waiting }}

           = 3 && item.time_waiting[4] < 2 ||
                      item.time_waiting[4] == 1 && item.time_waiting[3] == 0"
               ng-style="{backgroundColor: 'gold'}">
               {{ item.time_waiting }}

That is, everything works. But I'd like to add a style(or maybe ng-class) to the entire string and not to one cell. Maybe someone knows how this can be implemented using the ng-if directive?

Thank you in advance!)


问:
exporting jupyter ipython notebook to pdf
I'm trying to export a ipython notebook from jupyter to pdf but it just dosen't want to work. First I had some trouble with pandoc, but after installing that and adding it to PATH I'm still getting a error I don't understand.

```<code>nbconvert failed: PDF creating failed, captured latex output:
This is XeTeX, Version 3.14159265-2.6-0.99998 (MiKTeX 2.9.6350 64-bit)
entering extended mode
(notebook.tex
LaTeX2e <2017-04-15>
Babel <3.10> and hyphenation patterns for 75 language(s) loaded.
("C:\Program Files\MiKTeX 2.9\tex\latex\base\article.cls"
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
("C:\Program Files\MiKTeX 2.9\tex\latex\base\size11.clo"))
("C:\Program Files\MiKTeX 2.9\tex\latex\base\fontenc.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\base\t1enc.def")
("C:\Program Files\MiKTeX 2.9\tex\latex\lm\t1lmr.fd"))
("C:\Program Files\MiKTeX 2.9\tex\latex\psnfss\mathpazo.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics\graphicx.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics\keyval.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics\graphics.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics\trig.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics-cfg\graphics.cfg")
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics-def\xetex.def")))
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\caption\caption.sty"
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\caption\caption3.sty"
))
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\adjustbox\adjustbox.s
ty" ("C:\Program Files\MiKTeX 2.9\tex\latex\xkeyval\xkeyval.sty"
("C:\Program Files\MiKTeX 2.9\tex\generic\xkeyval\xkeyval.tex"
("C:\Program Files\MiKTeX 2.9\tex\generic\xkeyval\xkvutils.tex")))
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\adjustbox\adjcalc.sty
")
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\adjustbox\trimclip.st
y"
======================================================================
starting package maintenance...
installation directory: "C:\Users\Sito\AppData\Roaming\MiKTeX\2.9"
package repository: http://mirror.switch.ch/ftp/mirror/tex/systems/win32/miktex/tm/packages/
visiting repository http://mirror.switch.ch/ftp/mirror/tex/systems/win32/miktex/tm/packages/...
repository type: remote package repository
loading lightweight database...
downloading http://mirror.switch.ch/ftp/mirror/tex/systems/win32/miktex/tm/packages/miktex-zzdb1-2.9.tar.lzma...
167630 bytes, 574.39 KB/Sec
lightweight database digest: d071dd32f4cea419134839a73013ff85
going to download 282583 bytes
going to install 5 file(s) (1 package(s))
downloading http://mirror.switch.ch/ftp/mirror/tex/systems/win32/miktex/tm/packages/collectbox.tar.lzma...
282583 bytes, 2603.40 KB/Sec
extracting files from collectbox.tar.lzma...

Unfortunately, the package collectbox could not be installed.Please check the log file:
C:/Users/Sito/AppData/Local/MiKTeX/2.9/miktex/log/xelatex.log
======================================================================

("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\collectbox\collectbox
.sty")
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\adjustbox\tc-xetex.de
f")) ("C:\Program Files\MiKTeX 2.9\tex\latex\ltxmisc\varwidth.sty"))

! LaTeX Error: File `xcolor.sty' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: sty)

Enter file name:
! Emergency stop.
<read *>

l.43     \usepackage
                    {enumerate} % Needed for markdown enumerations to work^^M
No pages of output.
Transcript written on notebook.log.
</code>```

To be honest, I'm still completly new to jupyter and in general not really experienced in coding so please can someone explain the error to me and what I need to do to solve the problem.

Thanks Sito!

答:
Jupyter uses a combination of pandoc and a TeX distribution to generate PDF files from notebooks.

Your TeX distribution (MiKTeX) is missing the LaTeX xcolor package.  Use the MiTeX package manager which is causing the collectbox package installation to fail.

Use the MiKTeX package manager to install xcolor, then collect box and try running your conversion again.

Body:
I'm trying to export a ipython notebook from jupyter to pdf but it just dosen't want to work. First I had some trouble with pandoc, but after installing that and adding it to PATH I'm still getting a error I don't understand.

nbconvert failed: PDF creating failed, captured latex output:
This is XeTeX, Version 3.14159265-2.6-0.99998 (MiKTeX 2.9.6350 64-bit)
entering extended mode
(notebook.tex
LaTeX2e <2017-04-15>
Babel <3.10> and hyphenation patterns for 75 language(s) loaded.
("C:\Program Files\MiKTeX 2.9\tex\latex\base\article.cls"
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
("C:\Program Files\MiKTeX 2.9\tex\latex\base\size11.clo"))
("C:\Program Files\MiKTeX 2.9\tex\latex\base\fontenc.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\base\t1enc.def")
("C:\Program Files\MiKTeX 2.9\tex\latex\lm\t1lmr.fd"))
("C:\Program Files\MiKTeX 2.9\tex\latex\psnfss\mathpazo.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics\graphicx.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics\keyval.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics\graphics.sty"
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics\trig.sty")
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics-cfg\graphics.cfg")
("C:\Program Files\MiKTeX 2.9\tex\latex\graphics-def\xetex.def")))
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\caption\caption.sty"
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\caption\caption3.sty"
))
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\adjustbox\adjustbox.s
ty" ("C:\Program Files\MiKTeX 2.9\tex\latex\xkeyval\xkeyval.sty"
("C:\Program Files\MiKTeX 2.9\tex\generic\xkeyval\xkeyval.tex"
("C:\Program Files\MiKTeX 2.9\tex\generic\xkeyval\xkvutils.tex")))
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\adjustbox\adjcalc.sty
")
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\adjustbox\trimclip.st
y"
======================================================================
starting package maintenance...
installation directory: "C:\Users\Sito\AppData\Roaming\MiKTeX\2.9"
package repository: http://mirror.switch.ch/ftp/mirror/tex/systems/win32/miktex/tm/packages/
visiting repository http://mirror.switch.ch/ftp/mirror/tex/systems/win32/miktex/tm/packages/...
repository type: remote package repository
loading lightweight database...
downloading http://mirror.switch.ch/ftp/mirror/tex/systems/win32/miktex/tm/packages/miktex-zzdb1-2.9.tar.lzma...
167630 bytes, 574.39 KB/Sec
lightweight database digest: d071dd32f4cea419134839a73013ff85
going to download 282583 bytes
going to install 5 file(s) (1 package(s))
downloading http://mirror.switch.ch/ftp/mirror/tex/systems/win32/miktex/tm/packages/collectbox.tar.lzma...
282583 bytes, 2603.40 KB/Sec
extracting files from collectbox.tar.lzma...

Unfortunately, the package collectbox could not be installed.Please check the log file:
C:/Users/Sito/AppData/Local/MiKTeX/2.9/miktex/log/xelatex.log
======================================================================

("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\collectbox\collectbox
.sty")
("C:\Users\Sito\AppData\Roaming\MiKTeX\2.9\tex\latex\adjustbox\tc-xetex.de
f")) ("C:\Program Files\MiKTeX 2.9\tex\latex\ltxmisc\varwidth.sty"))

! LaTeX Error: File `xcolor.sty' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: sty)

Enter file name:
! Emergency stop.
<read *>

l.43     \usepackage
                    {enumerate} % Needed for markdown enumerations to work^^M
No pages of output.
Transcript written on notebook.log.

To be honest, I'm still completly new to jupyter and in general not really experienced in coding so please can someone explain the error to me and what I need to do to solve the problem.

Thanks Sito!


问:
Change parent (div) height to the size of its child (p) after window resize
```<code>$(window).on("resize", function () {

    var totalHeight = 0

    var $p = $("#cwt-help").children();

    $p.each(function () {
        totalHeight += $("#cwt-help").outerHeight();
    });

    $("#cwt-help").css({ "height": totalHeight })
});
</code>```

I am trying to resize parent div to match the height of its child after windows resize. The problem I have is with this code that I get the height before the resize. How can I get the resulting height? Thanks!

答:
This seems to work, much easier. When resizing the window, you set the height to the scrollHeight of the element.

$(window).on("resize", function () {
    $("#cwt-help").css({ "height": $('#cwt-help').srollHeight });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#cwt-help{
  background-color: red;
}</code>```

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate.

Velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```

Body:
$(window).on("resize", function () {

    var totalHeight = 0

    var $p = $("#cwt-help").children();

    $p.each(function () {
        totalHeight += $("#cwt-help").outerHeight();
    });

    $("#cwt-help").css({ "height": totalHeight })
});

I am trying to resize parent div to match the height of its child after windows resize. The problem I have is with this code that I get the height before the resize. How can I get the resulting height? Thanks!

Body:
This seems to work, much easier. When resizing the window, you set the height to the scrollHeight of the element.

$(window).on("resize", function () {
    $("#cwt-help").css({ "height": $('#cwt-help').srollHeight });
});

#cwt-help{
  background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="cwt-help">
  <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate.</p>

  <p>Velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>


问:
How to monitor JMX metrics of Kafka broker on command line?
A Kafka cluster can be monitored in granular detail via the JMX metrics it exposes. Usually an external GUI or application like jconsole needs to be hooked up to a broker's exposed JMX_PORT in order to view these metrics.

Is there a way that I can view a broker's JMX metrics in an SSH session, via STDOUT?
Is there a native Kafka command that I can run to view these metrics?

答:
Use kafka.tools.JmxTool.

Assuming you have enabled JMX on your broker on the default port of 9999, you can simply run this example command to print out jmx metrics for BrokerTopics via STDOUT

```<code>$ ./bin/kafka-run-class.sh kafka.tools.JmxTool \
  --object-name kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec
Trying to connect to JMX url: service:jmx:rmi:///jndi/rmi://:9999/jmxrmi.
"time","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:Count","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:EventType","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:FifteenMinuteRate","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:FiveMinuteRate","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:MeanRate","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:OneMinuteRate","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:RateUnit"
1567587563143,0,messages,0.0,0.0,0.0,0.0,SECONDS
1567587565148,0,messages,0.0,0.0,0.0,0.0,SECONDS
1567587567150,0,messages,0.0,0.0,0.0,0.0,SECONDS
...
</code>```

JmxTool prints out JMX metrics every --reporting-interval option.

--reporting-interval <Integer: ms>

Interval (in millis) with which to poll jmx stats

Default: 2000 (2 seconds)

Value of -1 is equivalent to --one-time true

ContentLicense: CC BY-SA 4.0

Body:
Use kafka.tools.JmxTool.

Assuming you have enabled JMX on your broker on the default port of 9999, you can simply run this example command to print out jmx metrics for BrokerTopics via STDOUT

$ ./bin/kafka-run-class.sh kafka.tools.JmxTool \
  --object-name kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec
Trying to connect to JMX url: service:jmx:rmi:///jndi/rmi://:9999/jmxrmi.
"time","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:Count","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:EventType","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:FifteenMinuteRate","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:FiveMinuteRate","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:MeanRate","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:OneMinuteRate","kafka.server:type=BrokerTopicMetrics,name=MessagesInPerSec:RateUnit"
1567587563143,0,messages,0.0,0.0,0.0,0.0,SECONDS
1567587565148,0,messages,0.0,0.0,0.0,0.0,SECONDS
1567587567150,0,messages,0.0,0.0,0.0,0.0,SECONDS
...

JmxTool prints out JMX metrics every --reporting-interval option.

--reporting-interval <Integer: ms>

Interval (in millis) with which to poll jmx stats

Default: 2000 (2 seconds)

Value of -1 is equivalent to --one-time true


问:
secure login script from wikihow
Has anybody used this script from wikihow?

By default both the login in and registering pages redirect you to "protected_page.php" the protected page is supposed to validate your login with: `

```<code><?php

include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Secure Login: Protected Page</title>
        <link rel="stylesheet" href="styles/main.css" />
    </head>
    <body>
        <?php if (login_check($mysqli) == true) : ?>
        <p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p>
            <p>
</code>```

or

```<code><?php else : ?>
            <p>
                <span class="error">You are not authorized to access this page.</span> Please <a href="index.php">login</a>.
            </p>
        <?php endif; ?>
</code>```

The problem is that I always get the error msg, even though my db is configured and the registration info is sent to the db, Ive even edited the reg form to add more info without any problem on the DB side, but still I always get this error msg when trying to log in on the site. Anybody had this problem?

答:
I don't have the answer but I do know that the problem must be found in the sec_session_start function:
If you don't use $session_name = 'sec_session_id',
 session_name($session_name);
and session_regenerate_id(true);
the code works.

```<code>function sec_session_start() {

//  $session_name = 'sec_session_id';   // Set a custom session name

    /*Sets the session name.
     *This must come before session_set_cookie_params due to an undocumented bug/feature in PHP.
     */

//  session_name($session_name);

    $secure = true;
    // This stops JavaScript being able to access the session id.
    $httponly = true;
    // Forces sessions to only use cookies.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }
    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"],
            $cookieParams["path"],
            $cookieParams["domain"],
            $secure,
            $httponly);

    session_start();            // Start the PHP session
//  session_regenerate_id(true);    // regenerated the session, delete the old one.

}
</code>```

Title: secure login script from wikihow

Body:
Has anybody used this script from wikihow?

By default both the login in and registering pages redirect you to "protected_page.php" the protected page is supposed to validate your login with: `

<?php

include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

sec_session_start();
?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Secure Login: Protected Page</title>
        <link rel="stylesheet" href="styles/main.css" />

        <?php if (login_check($mysqli) == true) : ?>

Welcome <?php echo htmlentities($_SESSION['username']); ?>!

or

<?php else : ?>

                You are not authorized to access this page. Please login.

        <?php endif; ?>

The problem is that I always get the error msg, even though my db is configured and the registration info is sent to the db, Ive even edited the reg form to add more info without any problem on the DB side, but still I always get this error msg when trying to log in on the site. Anybody had this problem?

Body:
I don't have the answer but I do know that the problem must be found in the sec_session_start function:
If you don't use $session_name = 'sec_session_id',
 session_name($session_name);
and session_regenerate_id(true);
the code works.

function sec_session_start() {

//  $session_name = 'sec_session_id';   // Set a custom session name

    /*Sets the session name.
     *This must come before session_set_cookie_params due to an undocumented bug/feature in PHP.
     */

//  session_name($session_name);

    $secure = true;
    // This stops JavaScript being able to access the session id.
    $httponly = true;
    // Forces sessions to only use cookies.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }
    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"],
            $cookieParams["path"],
            $cookieParams["domain"],
            $secure,
            $httponly);

    session_start();            // Start the PHP session
//  session_regenerate_id(true);    // regenerated the session, delete the old one.

}


问:
jqgrid tree not showing like a list instead of a tree
I have the jqgrid configuration below that is supposed to supposed to show a Tree like structure. Instead I am getting a flat list structure displayed. Can somebody please tell me what I am missing?
Here are the versions I am using in the order listed in the html page:

```<code>jquery/3.2.1/jquery.min.js,
jqgrid/4.6.0/js/i18n/grid.locale-en.js,
jqueryui/1.12.1/jquery-ui.min.js
</code>```

From triand.com site:

```<code>jqgrid/js/i18n/grid.locale-en.js
jqgrid/js/jquery.jqGrid.min.js
</code>```

I am also using these CSS:

```<code>jqueryui/1.8.14/themes/redmond/jquery-ui.css,
jqgrid/themes/ui.jqgrid.css (from triand.com),
jqueryui/1.12.1/themes/smoothness/jquery-ui.css
</code>```

in that order. My grid looks gray as opposed to the nice blue. I can't figure why.

$(document).ready(function(){
    $("#list").jqGrid({
        url : "/reconcile",
        datatype : "json",
        mtype : 'GET',
        colModel : [
            {name: "id",width:1,hidden:true, key:true},
            {name : 'data.key.busnDate', label : 'Business Date', hidden:false, sorttype:"date", width : 80 },
            {name : 'data.product', label : 'Product', sorttype:"string", width : 50, editable : false},
            {name : 'data.quantityBought', label : 'Quantity Bought', sorttype:"int", width : 100, editable : false},
            {"name":"level","hidden":true},
            {"name":"parent","hidden":true},
            {"name":"isLeaf","hidden":true},
            {"name":"expanded","hidden":true},
            {"name":"uiicon","hidden":true}
        ],
        treeGrid: true,
        pager : '#pager',
        loadonce:false,
        rowNum : 25,
        height: 'auto',
        rowList : [ 25,50,100,200 ],
        sortname : 'key.positionId',
        sortorder : 'asc',
        viewrecords : true,
        gridview : true,
        multiselect: false,
        multiboxonly: false,
        autoencode: true,
        caption : 'ARC Reconciliation',
        emptyrecords: "No records to found for given date!",
        jsonReader : {
                repeatitems : true,
        },
        treeIcons : {
            "plus": "ui-icon-circlesmall-plus",
            "minus": "ui-icon-circlesmall-minus",
            "leaf" : "ui-icon-document"
        },
        ExpandColumn: 'key.positionId'
    });
    jQuery("#list").jqGrid('navGrid', '#pager', {
        edit : false,
        add : false,
        del : false,
        view : true,
        search : true
    });
    $('#datePick').datepicker({
        onSelect: function (dateText, inst) {
            var e = $("#list").data("events");
            if (typeof (e) !== "undefined" && typeof (e.reloadGrid) !== "undefined") {
                $("#list").trigger("reloadGrid");
            }
        }
    });
});
```

Thanks

答:
You can look at our new Guriddo jqGrid documentation here in order to get answer of your problem.

Additionally to this you may want to visit or tree grid demo here with a lot of new features

Body:
I have the jqgrid configuration below that is supposed to supposed to show a Tree like structure. Instead I am getting a flat list structure displayed. Can somebody please tell me what I am missing?
Here are the versions I am using in the order listed in the html page:

jquery/3.2.1/jquery.min.js,
jqgrid/4.6.0/js/i18n/grid.locale-en.js,
jqueryui/1.12.1/jquery-ui.min.js

From triand.com site:

jqgrid/js/i18n/grid.locale-en.js
jqgrid/js/jquery.jqGrid.min.js

I am also using these CSS:

jqueryui/1.8.14/themes/redmond/jquery-ui.css,
jqgrid/themes/ui.jqgrid.css (from triand.com),
jqueryui/1.12.1/themes/smoothness/jquery-ui.css

in that order. My grid looks gray as opposed to the nice blue. I can't figure why.

$(document).ready(function(){
    $("#list").jqGrid({
        url : "/reconcile",
        datatype : "json",
        mtype : 'GET',
        colModel : [
            {name: "id",width:1,hidden:true, key:true},
            {name : 'data.key.busnDate', label : 'Business Date', hidden:false, sorttype:"date", width : 80 },
            {name : 'data.product', label : 'Product', sorttype:"string", width : 50, editable : false},
            {name : 'data.quantityBought', label : 'Quantity Bought', sorttype:"int", width : 100, editable : false},
            {"name":"level","hidden":true},
            {"name":"parent","hidden":true},
            {"name":"isLeaf","hidden":true},
            {"name":"expanded","hidden":true},
            {"name":"uiicon","hidden":true}
        ],
        treeGrid: true,
        pager : '#pager',
        loadonce:false,
        rowNum : 25,
        height: 'auto',
        rowList : [ 25,50,100,200 ],
        sortname : 'key.positionId',
        sortorder : 'asc',
        viewrecords : true,
        gridview : true,
        multiselect: false,
        multiboxonly: false,
        autoencode: true,
        caption : 'ARC Reconciliation',
        emptyrecords: "No records to found for given date!",
        jsonReader : {
                repeatitems : true,
        },
        treeIcons : {
            "plus": "ui-icon-circlesmall-plus",
            "minus": "ui-icon-circlesmall-minus",
            "leaf" : "ui-icon-document"
        },
        ExpandColumn: 'key.positionId'
    });
    jQuery("#list").jqGrid('navGrid', '#pager', {
        edit : false,
        add : false,
        del : false,
        view : true,
        search : true
    });
    $('#datePick').datepicker({
        onSelect: function (dateText, inst) {
            var e = $("#list").data("events");
            if (typeof (e) !== "undefined" && typeof (e.reloadGrid) !== "undefined") {
                $("#list").trigger("reloadGrid");
            }
        }
    });
});

Thanks


问:
What the plus operator does with an array?
I found this code in one of Arduino libraries

```<code>u8 buf[6];
Host2SCS(buf+0, buf+1, Position);
Host2SCS(buf+2, buf+3, Time);
Host2SCS(buf+4, buf+5, Speed);
</code>```

What the plus operator does with the array?

答:
In the expression, buf + 1, where buf is an array;

buf is implicitly converted to a pointer equal to &buf[0] (the address of the first element of buf)  This is a standard conversion known (unsurprisingly) as an "array to pointer conversion", or as "decaying to a pointer".

Adding an integral value to a pointer is normal pointer arithmetic, so the result of buf+1 is equivalent to &buf[1].

In your code as shown, the pointers resulting from adding integral values to pointers are passed to the function.  A more explicit version of your code  would be

```<code>u8 buf[6];
Host2SCS(&buf[0], &buf[1], Position);
Host2SCS(&buf[2], &buf[3], Time);
Host2SCS(&buf[4], &buf[5], Speed);
</code>```

Which form is "better" is a stylistic concern - technically they are equivalent.

Body:
I found this code in one of Arduino libraries

u8 buf[6];
Host2SCS(buf+0, buf+1, Position);
Host2SCS(buf+2, buf+3, Time);
Host2SCS(buf+4, buf+5, Speed);

What the plus operator does with the array?

Body:
In the expression, buf + 1, where buf is an array;

buf is implicitly converted to a pointer equal to &buf[0] (the address of the first element of buf)  This is a standard conversion known (unsurprisingly) as an "array to pointer conversion", or as "decaying to a pointer".

Adding an integral value to a pointer is normal pointer arithmetic, so the result of buf+1 is equivalent to &buf[1].

In your code as shown, the pointers resulting from adding integral values to pointers are passed to the function.  A more explicit version of your code  would be

u8 buf[6];
Host2SCS(&buf[0], &buf[1], Position);
Host2SCS(&buf[2], &buf[3], Time);
Host2SCS(&buf[4], &buf[5], Speed);

Which form is "better" is a stylistic concern - technically they are equivalent.


问:
React Router V4 but on a different homepage in package.json... fix 404 not found?
package.json

```<code>"name": "debate",
"homepage": "/debate", // I THINK THIS IS THE PROBLEM
"version": "0.1.0",
"private": true,
"dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-router-dom": "^4.1.1"
}
</code>```

App.js

```<code><BrowserRouter>
    <div>
        <Route path='/thread/:pathParam?' component={Thread}/>
        <Route path='/post' component={Post}/>
    </div>
</BrowserRouter>
</code>```

When I test the app on... [ http://localhost:3000/thread ] everything works perfectly well.

When I build the app for production and upload my files to my server, the directory [ http://www.example.com/debate/thread ] gives a 404 error saying "The requested URL /debate/thread/ was not found on this server."

```<code>The requested URL /debate/thread/ was not found on this server.
</code>```

[ http://www.example.com/debate/ ] still works perfectly well.

I'm not sure how to get react-router-dom to recognize that we're actually on a sub-directory...

答:
You need to use the basename property of the BrowserRouter object.

The documentation —
BrowserRouter.md

So in production it should be:

```<code><BrowserRouter basename="/debate">
</code>```

Or more realisitcally:

```<code><BrowserRouter basename={ROUTE_BASENAME}>
</code>```

And that ROUTE_BASENAME should resolve to / locally and to /debate on the server. You can use the Webpack DefinePlugin to handle that kind of variables.

Body:
package.json

"name": "debate",
"homepage": "/debate", // I THINK THIS IS THE PROBLEM
"version": "0.1.0",
"private": true,
"dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-router-dom": "^4.1.1"
}

App.js

<BrowserRouter>

        <Route path='/thread/:pathParam?' component={Thread}/>
        <Route path='/post' component={Post}/>

</BrowserRouter>

When I test the app on... [ http://localhost:3000/thread ] everything works perfectly well.

When I build the app for production and upload my files to my server, the directory [ http://www.example.com/debate/thread ] gives a 404 error saying "The requested URL /debate/thread/ was not found on this server."

The requested URL /debate/thread/ was not found on this server.

[ http://www.example.com/debate/ ] still works perfectly well.

I'm not sure how to get react-router-dom to recognize that we're actually on a sub-directory...

Body:
You need to use the basename property of the BrowserRouter object.

The documentation —
BrowserRouter.md

So in production it should be:

<BrowserRouter basename="/debate">

Or more realisitcally:

<BrowserRouter basename={ROUTE_BASENAME}>

And that ROUTE_BASENAME should resolve to / locally and to /debate on the server. You can use the Webpack DefinePlugin to handle that kind of variables.


问:
jQuery autocomplete's options are in the wrong position
I have a jQuery UI autocomplete field. It works, but when the suggestions pop up, the all show up in the very upper left-hand corner. I've included what I believe to be all the necessary CSS files but it's not showing up in the right place.

In fact, even when I include ALL the CSS files that come with jQuery UI, the autocomplete field shows up in the upper left-hand corner.

答: I had the same problem and solved it by adding the jQuery UI Position script.</p>

ContentLicense: CC BY-SA 2.5


问:
How to make a single button appear active in android
I have been learning java for a little while and am working on an android app.  I am trying to implement a boolean logic for my image buttons nested in a linear layout whereby just one button should show active button while the others are not.
For now each button can toggle between active and inactive but i don't want two ore more buttons showing active at the same time. I want a single one showing an active button at a time. </p>

```<code> public void showAudio(View view) {
        if (!audioButtonClicked) {
            audioButtonClicked = true;
            audioWindowButton.setImageResource(R.drawable.audio_active);
        } else {
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            audioButtonClicked = false;
        }

        }

    public void showEvents(View view) {
       if(!eventButtonClicked ) {
eventWindowButton.setImageResource(R.drawable.event_active);
           eventButtonClicked = true;
       } else {
           eventWindowButton.setImageResource(R.drawable.event_inactive);
           eventButtonClicked = false;
       }
    }

    public void showMore(View view) {
        if(!moreButtonClicked) {
            moreWindowButton.setImageResource(R.drawable.event_active);
            moreButtonClicked = true;

        } else {
            moreWindowButton.setImageResource(R.drawable.event_inactive);
            moreButtonClicked = false;
        }
    }
</code>```

答:
You can change its visibility using button.setVisibility(). This is the pseudo code.

```<code>if() { // some condition when you want imageButton1 to be visibile and others invisible
    imageButton1.setVisibility(View.VISIBLE);
    imageButton2.setVisibility(View.INVISIBLE);
    imageButton3.setVisibility(View.INVISIBLE);
} else if() { // some other condition when you want imageButton2 to be visibile and others invisible
    imageButton1.setVisibility(View.INVISIBLE);
    imageButton2.setVisibility(View.VISIBLE);
    imageButton3.setVisibility(View.INVISIBLE);
} else { // when you want imageButton3 to be visibile and others invisible
    imageButton1.setVisibility(View.INVISIBLE);
    imageButton2.setVisibility(View.INVISIBLE);
    imageButton3.setVisibility(View.VISIBLE);
}
</code>```

Using the above logic:

```<code>public void showAudio(View view) {
        if (!audioButtonClicked) {
            audioButtonClicked = true;
            eventButtonClicked = false;
            moreButtonClicked = false;
            audioWindowButton.setImageResource(R.drawable.audio_active);
            eventWindowButton.setImageResource(R.drawable.event_inactive);
            moreWindowButton.setImageResource(R.drawable.event_inactive);
        } else {
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            audioButtonClicked = false;
        }
}

public void showEvents(View view) {
        if(!eventButtonClicked ) {
            audioButtonClicked = false;
            eventButtonClicked = true;
            moreButtonClicked = false;
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            eventWindowButton.setImageResource(R.drawable.event_active);
            moreWindowButton.setImageResource(R.drawable.event_inactive);
        } else {
           eventWindowButton.setImageResource(R.drawable.event_inactive);
           eventButtonClicked = false;
        }
}

public void showMore(View view) {
        if(!moreButtonClicked) {
            audioButtonClicked = false;
            eventButtonClicked = false;
            moreButtonClicked = true;
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            eventWindowButton.setImageResource(R.drawable.event_inactive);
            moreWindowButton.setImageResource(R.drawable.event_active);

        } else {
            moreWindowButton.setImageResource(R.drawable.event_inactive);
            moreButtonClicked = false;
        }
}
</code>```

This would show only when feature as enabled while other features as disabled. if any one of the features is enabled then the other two features get disabled but if only one feature is disabled then other are not changed.

Body:
I have been learning java for a little while and am working on an android app.  I am trying to implement a boolean logic for my image buttons nested in a linear layout whereby just one button should show active button while the others are not.
For now each button can toggle between active and inactive but i don't want two ore more buttons showing active at the same time. I want a single one showing an active button at a time.

 public void showAudio(View view) {
        if (!audioButtonClicked) {
            audioButtonClicked = true;
            audioWindowButton.setImageResource(R.drawable.audio_active);
        } else {
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            audioButtonClicked = false;
        }

        }

    public void showEvents(View view) {
       if(!eventButtonClicked ) {
eventWindowButton.setImageResource(R.drawable.event_active);
           eventButtonClicked = true;
       } else {
           eventWindowButton.setImageResource(R.drawable.event_inactive);
           eventButtonClicked = false;
       }
    }

    public void showMore(View view) {
        if(!moreButtonClicked) {
            moreWindowButton.setImageResource(R.drawable.event_active);
            moreButtonClicked = true;

        } else {
            moreWindowButton.setImageResource(R.drawable.event_inactive);
            moreButtonClicked = false;
        }
    }

Body:
You can change its visibility using button.setVisibility(). This is the pseudo code.

if() { // some condition when you want imageButton1 to be visibile and others invisible
    imageButton1.setVisibility(View.VISIBLE);
    imageButton2.setVisibility(View.INVISIBLE);
    imageButton3.setVisibility(View.INVISIBLE);
} else if() { // some other condition when you want imageButton2 to be visibile and others invisible
    imageButton1.setVisibility(View.INVISIBLE);
    imageButton2.setVisibility(View.VISIBLE);
    imageButton3.setVisibility(View.INVISIBLE);
} else { // when you want imageButton3 to be visibile and others invisible
    imageButton1.setVisibility(View.INVISIBLE);
    imageButton2.setVisibility(View.INVISIBLE);
    imageButton3.setVisibility(View.VISIBLE);
}

Using the above logic:

public void showAudio(View view) {
        if (!audioButtonClicked) {
            audioButtonClicked = true;
            eventButtonClicked = false;
            moreButtonClicked = false;
            audioWindowButton.setImageResource(R.drawable.audio_active);
            eventWindowButton.setImageResource(R.drawable.event_inactive);
            moreWindowButton.setImageResource(R.drawable.event_inactive);
        } else {
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            audioButtonClicked = false;
        }
}

public void showEvents(View view) {
        if(!eventButtonClicked ) {
            audioButtonClicked = false;
            eventButtonClicked = true;
            moreButtonClicked = false;
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            eventWindowButton.setImageResource(R.drawable.event_active);
            moreWindowButton.setImageResource(R.drawable.event_inactive);
        } else {
           eventWindowButton.setImageResource(R.drawable.event_inactive);
           eventButtonClicked = false;
        }
}

public void showMore(View view) {
        if(!moreButtonClicked) {
            audioButtonClicked = false;
            eventButtonClicked = false;
            moreButtonClicked = true;
            audioWindowButton.setImageResource(R.drawable.audio_inactive);
            eventWindowButton.setImageResource(R.drawable.event_inactive);
            moreWindowButton.setImageResource(R.drawable.event_active);

        } else {
            moreWindowButton.setImageResource(R.drawable.event_inactive);
            moreButtonClicked = false;
        }
}

This would show only when feature as enabled while other features as disabled. if any one of the features is enabled then the other two features get disabled but if only one feature is disabled then other are not changed.


问:
Angular 4 Lazy Load Module with canLoad or canActivate guard direct url/
I have tried using canActivate and canLoad in two different module levels, and I am still unable to directly access the lazy loaded module.

In app.routing.module.ts

```<code>   import { AuthGuardImpl } from './lazy-load/auth-guard.service';
import {AuthGuard} from './lazy-load/auth.service';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'lazy', canLoad: [AuthGuardImpl], loadChildren: 'app/lazy-load/lazy-load.module#LazyLoadModule'},
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule],
  declarations: [],
  providers: [AuthGuardImpl, AuthGuardService]
})
</code>```

Where the above code works if you don't navigate to http://url.com/lazy directly. But go to http://url.com/ then follow a router link to the lazy module.

Similarly I tried:

```<code>import { AuthGuard } from './auth.service';
import { AuthGuardImpl } from './auth-guard.service';

const lazyRoutes: Routes = [
  { path: '', component: LazyLoadComponent, canActivate: [AuthGuardImpl],
    children: [
    { path: 'dashboard',  loadChildren: 'app/lazy-load/dashboard/dashboard.module#DashboardModule' },
    { path: '', redirectTo: 'dashboard', pathMatch: 'full'},
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(lazyRoutes)],
  exports: [RouterModule],
  declarations: [],
  providers: [AuthGuardImpl, AuthGuard]
})
</code>```

Which again, does not work going directly to http://url.com/lazy, but will work if the app loads, and then the user navigates to /lazy by routerlink.

Is it possible to navigate to a direct url for a lazy loaded module that uses a guard?

答:
I just tried this in my application and it seems to work fine. Are you referring to running at development time? Or after deploying to production?

You can download my sample code here if you want to take a look and compare: https://github.com/DeborahK/Angular-Routing/tree/master/APM-Final

Oh ... I just looked closer at the URL you posted and it looks like you are referring to production. You need to implement URL rewriting on your server in order to handle those "deep links". How you do that depends on the type of server you are using.

Body:
I have tried using canActivate and canLoad in two different module levels, and I am still unable to directly access the lazy loaded module.

In app.routing.module.ts

   import { AuthGuardImpl } from './lazy-load/auth-guard.service';
import {AuthGuard} from './lazy-load/auth.service';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'lazy', canLoad: [AuthGuardImpl], loadChildren: 'app/lazy-load/lazy-load.module#LazyLoadModule'},
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule],
  declarations: [],
  providers: [AuthGuardImpl, AuthGuardService]
})

Where the above code works if you don't navigate to http://url.com/lazy directly. But go to http://url.com/ then follow a router link to the lazy module.

Similarly I tried:

import { AuthGuard } from './auth.service';
import { AuthGuardImpl } from './auth-guard.service';

const lazyRoutes: Routes = [
  { path: '', component: LazyLoadComponent, canActivate: [AuthGuardImpl],
    children: [
    { path: 'dashboard',  loadChildren: 'app/lazy-load/dashboard/dashboard.module#DashboardModule' },
    { path: '', redirectTo: 'dashboard', pathMatch: 'full'},
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(lazyRoutes)],
  exports: [RouterModule],
  declarations: [],
  providers: [AuthGuardImpl, AuthGuard]
})

Which again, does not work going directly to http://url.com/lazy, but will work if the app loads, and then the user navigates to /lazy by routerlink.

Is it possible to navigate to a direct url for a lazy loaded module that uses a guard?


问:
lots of unwanted spacing,or whatever it is as soon as i added css script
```<code><!DOCTYPE html>
<html>
<head>
<title>Satyam</title>
<style>
ul,li{background-image:-webkit-linear-gradient(#0CE840,#EFFFE5);
display:inline-block;}
*{margin=0px;padding=0px;border:3px solid #000;background-attachment:fixed;
background-image: url("http://cdn.sploder.com/images/hp3/hp_multiplayer_sploderheads2.gif");
background-size:cover;}

#main{font-size:100px;box-sizing:border-
box;position:relative;bottom:90px;background-image:-webkit-linear-
gradient(#FFE259,#EFFFE5)}</style>
</head>
<body>
<h2 align="center" id="main">Gamerz!</h2>
<ul><h4>
<li>Home
<li>Courses
<li>Support
<li>Contact us</h4>
</ul>
</html>
</code>```

答:
With my comments before in the back of my mind, I think something like this is what you are looking for:

/* Use the body for a nice background */
body {
  background-image: url("http://cdn.sploder.com/images/hp3/hp_multiplayer_sploderheads2.gif");
  background-attachment: fixed;
  background-size: cover
}

h2 { margin: 0 }

/* Is a container, only holding
's */
ul {
  display: inline-block;
  margin: 0;
  padding: 0
}

/* Fontsize of H4 is actually 1rem/16px which generally is the default browser fontsize */
li {
  background: linear-gradient(#0CE840, #EFFFE5);
  display: inline-block;
  font-weight: bold /* is actually what you wanted from the
 */
}

/* We really didn't want add an image to ALL elements (which * actually means) */
* {
  border: 3px solid #000
}

#main {
  font-size: 100px;
  box-sizing: border- box;
  /* bottom: 90px; HUH? */
  background-image: linear-gradient(#FFE259, #EFFFE5)
}
/* linear- gradient (notice space) does nothing */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2 align="center" id="main">Gamerz!</h2>
<ul>
  <!-- NO! H4 inside ul -->
  <li>Home
    <li>Courses
      <li>Support
        <li>Contact us
</ul></code>```

Body:
<!DOCTYPE html>

<title>Satyam</title>

Gamerz!

Home

Courses

Support

Contact us

Body:
With my comments before in the back of my mind, I think something like this is what you are looking for:

/* Use the body for a nice background */
body {
  background-image: url("http://cdn.sploder.com/images/hp3/hp_multiplayer_sploderheads2.gif");
  background-attachment: fixed;
  background-size: cover
}

h2 { margin: 0 }

/* Is a container, only holding <li>'s */
ul {
  display: inline-block;
  margin: 0;
  padding: 0
}

/* Fontsize of H4 is actually 1rem/16px which generally is the default browser fontsize */
li {
  background: linear-gradient(#0CE840, #EFFFE5);
  display: inline-block;
  font-weight: bold /* is actually what you wanted from the <H4> */
}

/* We really didn't want add an image to ALL elements (which * actually means) */
* {
  border: 3px solid #000
}

#main {
  font-size: 100px;
  box-sizing: border- box;
  /* bottom: 90px; HUH? */
  background-image: linear-gradient(#FFE259, #EFFFE5)
}
/* linear- gradient (notice space) does nothing */

<h2 align="center" id="main">Gamerz!</h2>
<ul>
  <!-- NO! H4 inside ul -->
  <li>Home
    <li>Courses
      <li>Support
        <li>Contact us
</ul>


问:
How to obtain an existing reference to an object when deserializing the same object from disk
Sorry for the title of the post, don't know how to express it better..

I have an object unit which I save to the filesystem using MemoryStream and BinaryFormatter.

Now I have to run an NUNIT test that checks if both objects car and carloadedFromDisk are equal. This test fails, because it looks like they have different references on the heap.

Is it possible to have the deserialized object carloadedFromDisk to point to the existing reference of object car?
What can I do to make the test pass?

Example:

```<code>var car = new Car("Audi");
var unit = new Unit("GoldSmith", car);

unit.save();
var carloadedFromDisk = Car.get(carId); // deserialized

Assert.AreEqual(unit.Car, carloadedFromDisk); // <-- fails
</code>```

答:
Is it possible to have the deserialized object carloadedFromDisk to
  point to the existing reference of object car?

It is not possible. The new instance is created during deserialization. Even if you could pass existing instance to be filled by deserializer, then you would end up with single car instance compared to itself (always true).

Now I have to run an NUNIT test that checks if both objects car and
  carloadedFromDisk are equal. This test fails, because it looks like
  they have different references on the heap.

Instead of comparing references, you should compare values. Implement Equals and GetHashCode methods in your Car class so that fields of Car instances would be used for comparison and hash generation. Equals will be called by Assert.AreEqual assertion. E.g. if your Car has two properties:

```<code>public int Id { get; set; }
public string Name { get; set; }

public override bool Equals(object obj)
{
   if (obj == null || GetType() != obj.GetType())
      return false;

   Car other = (Car)obj;
   return (Id == other.Id) && (Name == other.Name);
}

public override int GetHashCode()
{
   unchecked
   {
       int hash = 19;
       hash = hash * 23 + Id;
       hash = hash * 23 + Name == null ? 0 : Name.GetHashCode();
       return hash;
   }
}
</code>```

Further reading: Implementing the Equals Method

Body:
Sorry for the title of the post, don't know how to express it better..

I have an object unit which I save to the filesystem using MemoryStream and BinaryFormatter.

Now I have to run an NUNIT test that checks if both objects car and carloadedFromDisk are equal. This test fails, because it looks like they have different references on the heap.

Is it possible to have the deserialized object carloadedFromDisk to point to the existing reference of object car?
What can I do to make the test pass?

Example:

var car = new Car("Audi");
var unit = new Unit("GoldSmith", car);

unit.save();
var carloadedFromDisk = Car.get(carId); // deserialized

Assert.AreEqual(unit.Car, carloadedFromDisk); // <-- fails

Body:
Is it possible to have the deserialized object carloadedFromDisk to
  point to the existing reference of object car?

It is not possible. The new instance is created during deserialization. Even if you could pass existing instance to be filled by deserializer, then you would end up with single car instance compared to itself (always true).

Now I have to run an NUNIT test that checks if both objects car and
  carloadedFromDisk are equal. This test fails, because it looks like
  they have different references on the heap.

Instead of comparing references, you should compare values. Implement Equals and GetHashCode methods in your Car class so that fields of Car instances would be used for comparison and hash generation. Equals will be called by Assert.AreEqual assertion. E.g. if your Car has two properties:

public int Id { get; set; }
public string Name { get; set; }

public override bool Equals(object obj)
{
   if (obj == null || GetType() != obj.GetType())
      return false;

   Car other = (Car)obj;
   return (Id == other.Id) && (Name == other.Name);
}

public override int GetHashCode()
{
   unchecked
   {
       int hash = 19;
       hash = hash * 23 + Id;
       hash = hash * 23 + Name == null ? 0 : Name.GetHashCode();
       return hash;
   }
}

Further reading: Implementing the Equals Method


问:
Ways to make it easier to work with shared pointers in C++
I am busy designing a new C++ application.  In this application I want to minimize potential errors with pointers, and since the application should be plain C++ (no .Net or other fancy things), I am investigating shared pointers and I am considering using shared pointers everywhere (instead of normal pointers).

I worked out some tricks to make it easier to work with shared pointers, e.g.: using a typedef within the class, like this:

```<code>class X
   {
   public:
      ...
      typedef std::shared_ptr<X> Ptr;
   };
</code>```

That way you can easily write X::Ptr, which is easier to write than "std::shared_ptr" everywhere.

I also noticed some disadvantages to shared pointers:

Everywhere I use a shared pointer I need to include <memory>

I can't use forward declaration anymore if I just want to use the pointer

Are there any other tricks to make shared pointers easier to work with?

答:
DON'T!

The only way to minimize pointer errors is to use the right pointer types. And that's types, plural.

Shared pointers are not a silver bullet. They become memory leaks as soon when you have cyclical references (and if plan to use them everywhere, those will show up pretty quickly)

If you want error-free C++ applications, you have to work for it. You have to understand your application. You have to understand the ownership semantics of different objects. Shared pointers just give you shared ownership, which is generally a decent lowest denominator. Everything else can be replaced by shared ownership and it'll work, sort of.

But the default case is that an object is owned by one other entity. It is owned by a function, and should be destroyed when that function returns, or it is owned by a class, or whatever else. Often, you don't need pointers at all. the object is stored by value in a std::vector, perhaps. Or it is just a local variable or a class member. If it is a pointer, it'll often be better expressed by a scoped_ptr or perhaps one which allows transfer of ownership (unique_ptr or auto_ptr).

shared_ptr is what you might fall back to when you can give no guarantees about the lifetime or ownership of an object. But when you use that, you also need to use weak_ptr to break cycles.

Really, a better approach is to avoid pointers as much as at all possible. When you do need a pointer, use one which has the most specific ownership semantics possible (prefer scoped_ptr, which doesn't allow transfer of ownership at all, then if you need it, fall back to one which allows you to move ownership, such as unique_ptr, and only as a last resort should you use shared_ptr, which allows you to share ownership freely among any number of clients.

There's no magic wand you can wave to make your C++ code "just work". The only way to achieve that is to write good solid C++ code. And you do that by knowing, and using, the tools at your disposal, not by pretending that "hey, shared_ptr is just like a garbage collector, isn't it? I can just ignore all questions of object lifetime or memory leaks if I use it".

Body:
I am busy designing a new C++ application.  In this application I want to minimize potential errors with pointers, and since the application should be plain C++ (no .Net or other fancy things), I am investigating shared pointers and I am considering using shared pointers everywhere (instead of normal pointers).

I worked out some tricks to make it easier to work with shared pointers, e.g.: using a typedef within the class, like this:

class X
   {
   public:
      ...
      typedef std::shared_ptr<X> Ptr;
   };

That way you can easily write X::Ptr, which is easier to write than "std::shared_ptr" everywhere.

I also noticed some disadvantages to shared pointers:

Everywhere I use a shared pointer I need to include <memory>

I can't use forward declaration anymore if I just want to use the pointer

Are there any other tricks to make shared pointers easier to work with?


问:
How to create a dictionary of closure variable name to value for a closure function. Python3.x
With a python module like:

```<code>def mult(n):
    a = n-1
    def multn(x):
        b = a
        print (n*x)
    return multn

f = mult(3)
f(4)

print (f.__closure__)
for c in f.__closure__:
    print (c.cell_contents)

print (f.__code__.co_freevars)
</code>```

The output is:

```<code>12
(<cell at 0x10fd20360: int object at 0x7f8f9bc0b760>, <cell at 0x10fd20398: int object at 0x7f8f9bc0b748>)
2
3
('a', 'n')
</code>```

Is there an easier way or package existing out there, where it creates a dictionary of clo_var_name to clo_val?

So {'a': 2, 'n': 3}

Thank you all in advanced.

答:
inspect.getclosurevars will give you a dict of closure-referenced variables.</p>

```<code>import inspect

inspect.getclosurevars(f)

# returns:

ClosureVars(nonlocals={'a': 2, 'n': 3}, globals={}, builtins={'print': <built-in function print>}, unbound=set())
</code>```

Body:
With a python module like:

def mult(n):
    a = n-1
    def multn(x):
        b = a
        print (n*x)
    return multn

f = mult(3)
f(4)

print (f.__closure__)
for c in f.__closure__:
    print (c.cell_contents)

print (f.__code__.co_freevars)

The output is:

12
(<cell at 0x10fd20360: int object at 0x7f8f9bc0b760>, <cell at 0x10fd20398: int object at 0x7f8f9bc0b748>)
2
3
('a', 'n')

Is there an easier way or package existing out there, where it creates a dictionary of clo_var_name to clo_val?

So {'a': 2, 'n': 3}

Thank you all in advanced.

Body:
inspect.getclosurevars will give you a dict of closure-referenced variables.

import inspect

inspect.getclosurevars(f)

# returns:

ClosureVars(nonlocals={'a': 2, 'n': 3}, globals={}, builtins={'print': <built-in function print>}, unbound=set())


问:
Can't get bind parameter name in sqlite3
I'm trying to get the names of parameters but something is going wrong.

Code: (minimal code to re-produce the problem)

```<code>var db: OpaquePointer? = nil
var rc: Int32 = 0
rc = sqlite3_open("test.db", &self.db)
if rc != SQLITE_OK
{
    print("cant open")
}
var statement: OpaquePointer? = nil
let sql = "insert into testtable values(?123);"
rc = sqlite3_prepare_v2(db, sql, -1, &statement, nil)
if rc != SQLITE_OK
{
    print("cant prepare")
}
print(String(cString: sqlite3_bind_parameter_name(statement, 1))) // returns nil
sqlite3_finalize(statement)
sqlite3_close(db)
</code>```

I get parameter names if I use @AAA, :AAA, $AAA but I get nil if I use ?123( ?NNN format). But according to website I should get ?123 as String.

What am I doing wrong?

Thank you.

答:
When you specify ?123, the 123 is the index. So you need to pass 123, not 1, to the call to sqlite3_bind_parameter_name.

You can see more in the documentation for the sqlite3_bind_xxx functions.

Body:
I'm trying to get the names of parameters but something is going wrong.

Code: (minimal code to re-produce the problem)

var db: OpaquePointer? = nil
var rc: Int32 = 0
rc = sqlite3_open("test.db", &self.db)
if rc != SQLITE_OK
{
    print("cant open")
}
var statement: OpaquePointer? = nil
let sql = "insert into testtable values(?123);"
rc = sqlite3_prepare_v2(db, sql, -1, &statement, nil)
if rc != SQLITE_OK
{
    print("cant prepare")
}
print(String(cString: sqlite3_bind_parameter_name(statement, 1))) // returns nil
sqlite3_finalize(statement)
sqlite3_close(db)

I get parameter names if I use @AAA, :AAA, $AAA but I get nil if I use ?123( ?NNN format). But according to website I should get ?123 as String.

What am I doing wrong?

Thank you.


问:
Can a parent class check if child class has such field?
I know that we can reference the parent's model from a child but is there a way to have it the other way?

sorry for any typo here.

Let's say if parent is

```<code>class Parent(Model):
    has_this = models.Charfield(max_length=128)

class Child(Parent):
    has_that = models.Boolean(default=True)

ch = Child.objects.filter(id=1).first()  // this will be instance of both Parent and Child as expected

pa = Parent.objects.filter(id=1).first() // is actually return the same as above but does not has the `Child` field `has_that`
</code>```

What my question is, is there a way for pa to differential from a regular Parent if a query is called using Parent.objects.filter

I tried using isisntance but for pa, it's only true if it's Parent for ch it's true for both.  I cannot think of another way to differential this.

Also, Parent will not be abstract.

P.S. I thought of using hasattr but this would not work too.

Thanks in advance.

答:
You can reference subclass properties by using the subclass as a field name:

```<code>Parent.objects.filter(child__isnull=True)
</code>```

yields all bare Parent instances (that are not children).

This gets slightly unwieldy when you have multiple derived classes, though.

Obviously, you can also query for child fields via the parent class this way:

```<code>Parent.objects.filter(child__has_that=True)
</code>```

yields instances of Parent that are also Children with has_that set to True.

Body:
I know that we can reference the parent's model from a child but is there a way to have it the other way?

sorry for any typo here.

Let's say if parent is

class Parent(Model):
    has_this = models.Charfield(max_length=128)

class Child(Parent):
    has_that = models.Boolean(default=True)

ch = Child.objects.filter(id=1).first()  // this will be instance of both Parent and Child as expected

pa = Parent.objects.filter(id=1).first() // is actually return the same as above but does not has the `Child` field `has_that`

What my question is, is there a way for pa to differential from a regular Parent if a query is called using Parent.objects.filter

I tried using isisntance but for pa, it's only true if it's Parent for ch it's true for both.  I cannot think of another way to differential this.

Also, Parent will not be abstract.

P.S. I thought of using hasattr but this would not work too.

Thanks in advance.

Body:
You can reference subclass properties by using the subclass as a field name:

Parent.objects.filter(child__isnull=True)

yields all bare Parent instances (that are not children).

This gets slightly unwieldy when you have multiple derived classes, though.

Obviously, you can also query for child fields via the parent class this way:

Parent.objects.filter(child__has_that=True)

yields instances of Parent that are also Children with has_that set to True.


问:
running time of add(i, x) for dual array deque
A DualArrayDeque represents a list using two ArrayStacks.

```<code>List<T> front;
List<T> back;

void add(int i, T x) {

    if (i < front.size()) {
        front.add(front.size()-i, x);
    } else {
        back.add(i-front.size(), x);
    }

    balance();

}
</code>```

Ignore the running time of balance(). If i < front.size(), add(i,x) running time is O(i+1). Shift 0-i elements to the left [O(i)] and assign ith element to x [O(1)]. Similarly, when i > front.size(), it is O(n-i+1);

front.size() and back.size() do not differ by more than a factor of 3. In particular, 3 · front.size() ≥ back.size() and 3 · back.size() ≥ front.size(). Therefore, The running time is O(1 + i) if i < n/4, and O(1 + n − i) if i ≥ 3n/4;

My question is when n/4 <= i < 3n/4, why the running time of add(i,x) is O(n)?

PS: I am reading Open Data Structure http://opendatastructures.org/ods-java/2_5_DualArrayDeque_Building.html. I am very confused why it is O(n).

答:
Consider the case where the split between the two backing arrays occurs at position 3n/4. So there are 3n/4 elements in the front array, and n/4 elements in the back array. Now what happens when someone calls add(i) where i=3n/4-1. That is, what happens when someone adds to the last element in the front array. Since the front arraystack is actually in reverse that's the same as adding to index 0 in an array stack: everything in that stack must be shifted by one to make room.

So worst case, if n/4 < i < 3n/4 we could be shifting 3n/4 elements which is O(n).

Body:
A DualArrayDeque represents a list using two ArrayStacks.

List<T> front;
List<T> back;

void add(int i, T x) {

    if (i < front.size()) {
        front.add(front.size()-i, x);
    } else {
        back.add(i-front.size(), x);
    }

    balance();

}

Ignore the running time of balance(). If i < front.size(), add(i,x) running time is O(i+1). Shift 0-i elements to the left [O(i)] and assign ith element to x [O(1)]. Similarly, when i > front.size(), it is O(n-i+1);

front.size() and back.size() do not differ by more than a factor of 3. In particular, 3 · front.size() ≥ back.size() and 3 · back.size() ≥ front.size(). Therefore, The running time is O(1 + i) if i < n/4, and O(1 + n − i) if i ≥ 3n/4;

My question is when n/4 <= i < 3n/4, why the running time of add(i,x) is O(n)?

PS: I am reading Open Data Structure http://opendatastructures.org/ods-java/2_5_DualArrayDeque_Building.html. I am very confused why it is O(n).


问:
Python data type, what kind of data structure it is?
```<code>reshape, crop = {
1: ((1952, 3264), (1944, 3240)),
2: ((2480, 4128), (2464, 4100)),
}

offset = {1: 6404096, 2: 10270208,}[ver]

#where ver is defined as a dictionary

ver = {
    'RP_ov5647': 1,
    'RP_imx219': 2,
    }[camera.exif_tags['IFD0.Model']]
</code>```

What kind of structures are these? ver reported as type int. I'm confused.
How did [ver] work in the assignment to offset?

答:
First of all, your initial statement isn't going to do what (I think) you want: you have two variables on the left of the assignment, but only a single value -- a dictionary -- on the right.  I think you're missing [ver] at the end.  As given, the statement will build the dictionary, extract the keys (1, 2), and assign those to the variables, ignoring the dimensional tuples.

The variable ver above is an integer that you looked up in a dictionary.

This code seems designed to start with a model name and look up appropriate parameters based on that model.  Let's look at the code in its proper order, and with a couple of intermediate variables.

```<code># Dictionary to look up version number (1 or 2),
#   given the model name.
model_to_version = {
    'RP_ov5647': 1,
    'RP_imx219': 2,
    }

# Get the model name from the camera info object.
# Here on Stack Overflow, we have no idea of the structure,
#   but merely have to trust that this works.
model_name = camera.exif_tags['IFD0.Model']

# Now, get the version number we're using as an internal key.
# This will return 1 or 2.
version = model_to_version[model_name]

# The offset look-up is unchanged.
offset = {1: 6404096, 2: 10270208}[version]

# Dictionary to look up sizing information (shape & crop).
# Each entry is a pair of x-y dimension pairs.
size_info = {
    1: ((1952, 3264), (1944, 3240)),
    2: ((2480, 4128), (2464, 4100)),
}

# Finally, look up the proper set of sizes:
shaping, crop = size_info[ver]
</code>```

After all of this, we have shaping and crop with the appropriate dimensions for this camera model, and offset has the appropriate pixel offset (I assume) in a stream of input.

Is that what you needed?

Body:
reshape, crop = {
1: ((1952, 3264), (1944, 3240)),
2: ((2480, 4128), (2464, 4100)),
}

offset = {1: 6404096, 2: 10270208,}[ver]

#where ver is defined as a dictionary

ver = {
    'RP_ov5647': 1,
    'RP_imx219': 2,
    }[camera.exif_tags['IFD0.Model']]

What kind of structures are these? ver reported as type int. I'm confused.
How did [ver] work in the assignment to offset?

Body:
First of all, your initial statement isn't going to do what (I think) you want: you have two variables on the left of the assignment, but only a single value -- a dictionary -- on the right.  I think you're missing [ver] at the end.  As given, the statement will build the dictionary, extract the keys (1, 2), and assign those to the variables, ignoring the dimensional tuples.

The variable ver above is an integer that you looked up in a dictionary.

This code seems designed to start with a model name and look up appropriate parameters based on that model.  Let's look at the code in its proper order, and with a couple of intermediate variables.

# Dictionary to look up version number (1 or 2),
#   given the model name.
model_to_version = {
    'RP_ov5647': 1,
    'RP_imx219': 2,
    }

# Get the model name from the camera info object.
# Here on Stack Overflow, we have no idea of the structure,
#   but merely have to trust that this works.
model_name = camera.exif_tags['IFD0.Model']

# Now, get the version number we're using as an internal key.
# This will return 1 or 2.
version = model_to_version[model_name]

# The offset look-up is unchanged.
offset = {1: 6404096, 2: 10270208}[version]

# Dictionary to look up sizing information (shape & crop).
# Each entry is a pair of x-y dimension pairs.
size_info = {
    1: ((1952, 3264), (1944, 3240)),
    2: ((2480, 4128), (2464, 4100)),
}

# Finally, look up the proper set of sizes:
shaping, crop = size_info[ver]

After all of this, we have shaping and crop with the appropriate dimensions for this camera model, and offset has the appropriate pixel offset (I assume) in a stream of input.

Is that what you needed?


问:
Efficient way of merging data frames on custom conditions
Below are the below data frames i have esh -> earnings surprise history
and sph-> stock price history.

earnings surprise history

```<code>    ticker   reported_date reported_time_code  eps_actual
0    ABC     2017-10-05       AMC                1.01
1    ABC     2017-07-04       BMO                0.91
2    ABC     2017-03-03       BMO                1.08
3    ABC     2016-10-02       AMC                0.5
</code>```

stock price history

```<code>    ticker       date    adj_open   ad_close
0    ABC     2017-10-06   12.10      13.11
1    ABC     2017-12-05   11.11      11.87
2    ABC     2017-12-04   12.08      11.40
3    ABC     2017-12-03   12.01      13.03
..
101  ABC     2017-07-04   9.01        9.59
102  ABC     2017-07-03   7.89        8.19
</code>```

I like to build a new dataframe by merging two datasets which shall have the following columns as shown below and also if the reported_time_code from the earnings surprise history is AMC  then the record to be referred from stock price history should be the next day.if the reported_time_code is BM0  then record to be referred from stock price history should be the same day. if i used straight merge function on the actual_reported column of esh and data column of sph it will break the above conditions. looking for efficient way of transforming the data

Here is the resultant transformed data set

```<code>    ticker       date     adj_open   ad_close  eps_actual
0    ABC     2017-10-06    12.10      13.11      1.01
101  ABC     2017-07-04    9.01        9.59      0.91
</code>```

答:
Let's add a new column, 'date', to stock price history dataframe based on reported_time_code using np.where and drop unwanted columns then merge to earning history dataframe:

```<code>eh['reported_date'] = pd.to_datetime(eh.reported_date)

sph['date'] = pd.to_datetime(sph.date)

eh_new = eh.assign(date=np.where(eh.reported_time_code == 'AMC',
                                 eh.reported_date + pd.DateOffset(days=1),
                                 eh.reported_date)).drop(['reported_date','reported_time_code'],axis=1)

sph.merge(eh_new, on=['ticker','date'])
</code>```

Output:

```<code>  ticker       date  adj_open  ad_close  eps_actual
0    ABC 2017-10-06     12.10     13.11        1.01
1    ABC 2017-07-04      9.01      9.59        0.91
</code>```

Body:
Below are the below data frames i have esh -> earnings surprise history
and sph-> stock price history.

earnings surprise history

    ticker   reported_date reported_time_code  eps_actual
0    ABC     2017-10-05       AMC                1.01
1    ABC     2017-07-04       BMO                0.91
2    ABC     2017-03-03       BMO                1.08
3    ABC     2016-10-02       AMC                0.5

stock price history

    ticker       date    adj_open   ad_close
0    ABC     2017-10-06   12.10      13.11
1    ABC     2017-12-05   11.11      11.87
2    ABC     2017-12-04   12.08      11.40
3    ABC     2017-12-03   12.01      13.03
..
101  ABC     2017-07-04   9.01        9.59
102  ABC     2017-07-03   7.89        8.19

I like to build a new dataframe by merging two datasets which shall have the following columns as shown below and also if the reported_time_code from the earnings surprise history is AMC  then the record to be referred from stock price history should be the next day.if the reported_time_code is BM0  then record to be referred from stock price history should be the same day. if i used straight merge function on the actual_reported column of esh and data column of sph it will break the above conditions. looking for efficient way of transforming the data

Here is the resultant transformed data set

    ticker       date     adj_open   ad_close  eps_actual
0    ABC     2017-10-06    12.10      13.11      1.01
101  ABC     2017-07-04    9.01        9.59      0.91

Body:
Let's add a new column, 'date', to stock price history dataframe based on reported_time_code using np.where and drop unwanted columns then merge to earning history dataframe:

eh['reported_date'] = pd.to_datetime(eh.reported_date)

sph['date'] = pd.to_datetime(sph.date)

eh_new = eh.assign(date=np.where(eh.reported_time_code == 'AMC',
                                 eh.reported_date + pd.DateOffset(days=1),
                                 eh.reported_date)).drop(['reported_date','reported_time_code'],axis=1)

sph.merge(eh_new, on=['ticker','date'])

Output:

  ticker       date  adj_open  ad_close  eps_actual
0    ABC 2017-10-06     12.10     13.11        1.01
1    ABC 2017-07-04      9.01      9.59        0.91


问:
jQuery scrolltop animate not animating
Here is what I have.

The clicking function works and jumps to that part of the section, but the scrolling animation isn't working.

Anything I did wrong?

```<code>    <nav class="navbar navbar-inverse navbar-fixed-top" id="my-navbar">
        <div class="container text-right">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

            </div>

<div class="collapse navbar-collapse text-left" id="navbar-collapse" >
  <ul class="nav navbar-nav">
    <li><a href="#home">Home</a></li>
    <li><a href="#skills">Skills</a></li>
    <li><a href="#feedback">Feedback</a></li>
    <li><a href="#about">About me</a></li>
    <li><a href="#contact">Contact</a></li>
  </ul>
</div>

<script>
  $("#navbar").on("click", function(e) {
    e.preventDefault();
    var section = $(this).attr("href");
    $("html, body").animate({
      scrollTop: $(section).offset().top
    }, 1500);
  });
</script>
</code>```

答: There is no element #navbar on your page, so the click event never gets fired, and the browser just behaves as usual (jumping to the anchor) - try using something like #navbar-collapse, or .nav a.

Title: jQuery scrolltop animate not animating

Body:
Here is what I have.

The clicking function works and jumps to that part of the section, but the scrolling animation isn't working.

Anything I did wrong?

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">

                </button>

Home

Skills

Feedback

About me

Contact


问:
Wiremock Stubbing not working
I've just started using Wiremock and I have a question about stubbing.

From the docs, it seems to be that you can use either a JSON file under mappings OR the code stubFor(get(urlEqualTo(... in your Java code. However, I'm finding that using stubFor(get(urlEqualTo( results in 'Request was not matched' messages appearing in the Wiremock console.

Is this correct behaviour? Does stubbing need both the code and the json file?

Thanks.

答: WireMock can work with just JSON payloads in mappings. Sounds like there's something else going on with your configuration, but I'd need more details to diagnose. </p>

Title: Wiremock Stubbing not working


问:
How can I convert a date from the format "dd/mm/yyyy" to "yyyy/dd/mm"?
I have a Textbox in which the user is supposed to enter a date in the format dd/mm/yyyy, this date is stored as yyyy/mm/dd in the database.

So I want the user to enter the date in dd/mm/yyyy format and later I want to convert to yyyy/mm/dd so that I can query database.

How can I convert the user input date dd/mm/yyyy to yyyy/mm/dd?

答:
Quick and maybe dirty:

```<code>string reformattedDate = DateTime.ParseExact(textBox1.Text, "dd/MM/yyyy", null).ToString("yyyy/MM/dd");
</code>```

This, of course, assumes that the content of the Textbox will always be in the assumed format, so their should be checks in before to ensure that. There's also the much safer way which does not need additional checks:

```<code>DateTime result;
if(DateTime.TryParseExact(textBox1.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out result)
{
    // Here you can safely use result
    string reformattedDate = result.ToString("yyyy/MM/dd");
} else {
    // Screw the user
}
</code>```

This will try to parse the content of the Textbox and return it to your via the out result, if successful, it will return true. Otherwise you can rest assured that the input was either not in the assumed format, or not a valid Date.

Please also be aware that ParseExact will throw an ArgumentNullException or an ArgumentException if the conversion fails.

MSDN Article for ParseExact

MSDN Article for TryParseExact

I have a text box in which the user is supposed to enter a date in dd/mm/yyyy format, this date is stored as yyyy/mm/dd in the database.

The obvious answer to this is: use a DateTimePicker and a parameterized query before wrestling with a string conversion. It will save you a lot of headache in the long run.

Body:
Quick and maybe dirty:

string reformattedDate = DateTime.ParseExact(textBox1.Text, "dd/MM/yyyy", null).ToString("yyyy/MM/dd");

This, of course, assumes that the content of the Textbox will always be in the assumed format, so their should be checks in before to ensure that. There's also the much safer way which does not need additional checks:

DateTime result;
if(DateTime.TryParseExact(textBox1.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out result)
{
    // Here you can safely use result
    string reformattedDate = result.ToString("yyyy/MM/dd");
} else {
    // Screw the user
}

This will try to parse the content of the Textbox and return it to your via the out result, if successful, it will return true. Otherwise you can rest assured that the input was either not in the assumed format, or not a valid Date.

Please also be aware that ParseExact will throw an ArgumentNullException or an ArgumentException if the conversion fails.

MSDN Article for ParseExact

MSDN Article for TryParseExact

I have a text box in which the user is supposed to enter a date in dd/mm/yyyy format, this date is stored as yyyy/mm/dd in the database.

The obvious answer to this is: use a DateTimePicker and a parameterized query before wrestling with a string conversion. It will save you a lot of headache in the long run.