问:
variable of Class not being recognized in the function for Angular 2 typescript with GoJS
I have an application which uses:

Angular 2

GoJS for visualization

It consists of:

Parent Component: src/app/search.component.ts

it consists of a search bar and some area where a API call to the server will manifest buttons.

Child Component: src/app/search-details.component.ts

it consists of a
 which manifests the GoJS Radial Layout Diagram

within the SearchDetailsComponent class of the child component there is a simple function called nodeClicked which is as follows:

```<code>nodeClicked(e, node) {
  // show the name of the clicked node on the console
  console.log(node.data.text);
  this.checkString = node.data.text // HERE is the ERROR....
}
</code>```

Every time the Diagram is rendered and the user clicks on any node, an error occurs stating:

TypeError: this is undefined

```<code>Stack-Trace:
execute/SearchDetailsComponent</SearchDetailsComponent.prototype.nodeClicked@http://run.plnkr.co/L7H44HHRrMceJAkj/src/app/search-details.component.ts!transpiled:96:21
Vh@https://unpkg.com/gojs/release/go-debug.js:539:43
Vg.prototype.standardMouseClick@https://unpkg.com/gojs/release/go-debug.js:537:201
ek.prototype.doMouseUp@https://unpkg.com/gojs/release/go-debug.js:667:73
E.prototype.doMouseUp@https://unpkg.com/gojs/release/go-debug.js:802:92
Ll/a.no@https://unpkg.com/gojs/release/go-debug.js:1012:149
ZoneDelegate.prototype.invokeTask@https://unpkg.com/zone.js/dist/zone.js:424:17
onInvokeTask@https://unpkg.com/@angular/core/bundles/core.umd.js:3956:28
ZoneDelegate.prototype.invokeTask@https://unpkg.com/zone.js/dist/zone.js:423:17
Zone.prototype.runTask@https://unpkg.com/zone.js/dist/zone.js:191:28
ZoneTask/this.invoke@https://unpkg.com/zone.js/dist/zone.js:486:28
</code>```

the this it is referring to is that of the checkString variable declares in the class SearchDetailsComponent.

How is the checkString not recognized? I have defined it above. This error keeps showing up with a API service I wish to call every time the node is clicked and a HTTP GET is called too.

What am I doing wrong here?

Live Plunker

Embed Plunker

答:
As @WalterNorthwoods' answer suggests. I created an inline function for the Node.click as follows:

```<code>click: (e: go.InputEvent, obj: go.GraphObject) => { this.nodeClicked(e, obj); }
</code>```

the nodeClicked function is now callable and the this.checkString value is displayed perfectly.

Body:
I have an application which uses:

Angular 2

GoJS for visualization

It consists of:

Parent Component: src/app/search.component.ts

it consists of a search bar and some area where a API call to the server will manifest buttons.

Child Component: src/app/search-details.component.ts

it consists of a
 which manifests the GoJS Radial Layout Diagram

within the SearchDetailsComponent class of the child component there is a simple function called nodeClicked which is as follows:

nodeClicked(e, node) {
  // show the name of the clicked node on the console
  console.log(node.data.text);
  this.checkString = node.data.text // HERE is the ERROR....
}

Every time the Diagram is rendered and the user clicks on any node, an error occurs stating:

TypeError: this is undefined

Stack-Trace:
execute/SearchDetailsComponent</SearchDetailsComponent.prototype.nodeClicked@http://run.plnkr.co/L7H44HHRrMceJAkj/src/app/search-details.component.ts!transpiled:96:21
Vh@https://unpkg.com/gojs/release/go-debug.js:539:43
Vg.prototype.standardMouseClick@https://unpkg.com/gojs/release/go-debug.js:537:201
ek.prototype.doMouseUp@https://unpkg.com/gojs/release/go-debug.js:667:73
E.prototype.doMouseUp@https://unpkg.com/gojs/release/go-debug.js:802:92
Ll/a.no@https://unpkg.com/gojs/release/go-debug.js:1012:149
ZoneDelegate.prototype.invokeTask@https://unpkg.com/zone.js/dist/zone.js:424:17
onInvokeTask@https://unpkg.com/@angular/core/bundles/core.umd.js:3956:28
ZoneDelegate.prototype.invokeTask@https://unpkg.com/zone.js/dist/zone.js:423:17
Zone.prototype.runTask@https://unpkg.com/zone.js/dist/zone.js:191:28
ZoneTask/this.invoke@https://unpkg.com/zone.js/dist/zone.js:486:28

the this it is referring to is that of the checkString variable declares in the class SearchDetailsComponent.

How is the checkString not recognized? I have defined it above. This error keeps showing up with a API service I wish to call every time the node is clicked and a HTTP GET is called too.

What am I doing wrong here?

Live Plunker

Embed Plunker

Body:
As @WalterNorthwoods' answer suggests. I created an inline function for the Node.click as follows:

click: (e: go.InputEvent, obj: go.GraphObject) => { this.nodeClicked(e, obj); }

the nodeClicked function is now callable and the this.checkString value is displayed perfectly.


来源: stackexchange

问:
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>```

答:
1) The problem with deleting is

```<code>[categoryArray removeObjectAtIndex:indexPath.row];
</code>```

Remove it from db too.

Once you delete the row, reload the tableView using [tableView reloadData]

2) There is no problem if it is the only one item

Edit:

This is the problem

```<code>[categoryArray removeObjectAtIndex:indexPath.row];
NSString *selectedCategory = [categoryArray objectAtIndex:indexPath.row];
</code>```

You have deleted the value at indexPath.row from array after that accessing the value at same indexPath.row, obviously it will delete the next value only.. :)

So put that

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

line before [categoryArray removeObjectAtIndex:indexPath.row];

ContentLicense: CC BY-SA 3.0

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

Body:
1) The problem with deleting is

[categoryArray removeObjectAtIndex:indexPath.row];

Remove it from db too.

Once you delete the row, reload the tableView using [tableView reloadData]

2) There is no problem if it is the only one item

Edit:

This is the problem

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

You have deleted the value at indexPath.row from array after that accessing the value at same indexPath.row, obviously it will delete the next value only.. :)

So put that

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

line before [categoryArray removeObjectAtIndex:indexPath.row];

ContentLicense: CC BY-SA 2.5


问:
Turn html text into markdown manually (javascript / nodejs)
I'm a bit stuck. I have scraped a website and would now like to convert it into markdown. My html looks like this:

```<code>Some text more text, and more text. Some text more text, and more text.
Once in a while  <span class="bold">something is bold</span>.
Then some more text. And <span class="bold">more bold stuff</span>.
</code>```

There are html to markdown modules available, however, they would only work if the text  looked like this .

How could I go through the html, and everytime I find a span which is supposed to bold something, turn this piece of the html into bold markdown, that is, make it **look like this**

答:
Notepad++ is an open-source editor that supports regex. This picture shows the basic idea.

You know how to use an editor to find and replace strings. In an editor like Notepad++ you can look for string patterns and replace parts of the patterns and keep what's left. In your case, you want to find strings that are framed by HTML markup. Here the regex in the 'Find what' edit box displays that, with the special notation ([^<]*) meaning save zero or more of any character other than the '<' for use in a replacement string. The 'Replace with' edit box says used what was saved (as \1) in the expression **\1** which gives you what you prefer to have in the text file. It remains to click on 'Replace all'.

To be able to do this you need to install Notepad++ and learn some basic Perl regex. To get this dialogue box click on Ctl-H. Of course, if you get it wrong there's always Ctl-Z.

Body:
I'm a bit stuck. I have scraped a website and would now like to convert it into markdown. My html looks like this:

Some text more text, and more text. Some text more text, and more text.
Once in a while  something is bold.
Then some more text. And more bold stuff.

There are html to markdown modules available, however, they would only work if the text  looked like this .

How could I go through the html, and everytime I find a span which is supposed to bold something, turn this piece of the html into bold markdown, that is, make it **look like this**


问:
Listview divider after each item
i can't understand, why divider don't comes after every item? It shows only after last item! I really don't know what to do.

I am parsing some information by using Jsoup.

What i have:

enter image description here

My Listview

```<code>   <ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentEnd="true"
    android:layout_alignParentTop="true"
    android:touchscreenBlocksFocus="true" />
</code>```

答:
If you are using ListView all you need to do is add android:divider tag, like this:

```<code> <ListView
     android:id="@+id/listView"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_alignParentEnd="true"
     android:layout_alignParentTop="true"
     android:touchscreenBlocksFocus="true"
     android:divider="#FFCC00"
     android:dividerHeight="2dp"/>
</code>```

Also Optionally you can set divider height with android:dividerHeight tag.

Title: Listview divider after each item

Body:
i can't understand, why divider don't comes after every item? It shows only after last item! I really don't know what to do.

I am parsing some information by using Jsoup.

What i have:

enter image description here

My Listview

   <ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentEnd="true"
    android:layout_alignParentTop="true"
    android:touchscreenBlocksFocus="true" />

Body:
If you are using ListView all you need to do is add android:divider tag, like this:

 <ListView
     android:id="@+id/listView"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_alignParentEnd="true"
     android:layout_alignParentTop="true"
     android:touchscreenBlocksFocus="true"
     android:divider="#FFCC00"
     android:dividerHeight="2dp"/>

Also Optionally you can set divider height with android:dividerHeight tag.


问:
Does Kubernetes have webhook or similar functionality?
I'd like a webserver to be notified if Kubernetes kills a pod and for what reason e.g. DEADLINE_EXCEEDED or OOM. Does Kubernetes have webhook functionality for this or some other mechanism where I can be told when it does something. </p>

答:
There isn't a webhook per-se, however there are kubernetes events that you can listen to.

Quick google turned up this article


问:
Does Azure have support for HttpRuntime.Cache for an ASP.Net application?
My ASP.Net application uses HTTPRuntime.Cache. If I host it on Azure:

Will there be any compilation errors assuming HTTPRuntime.Cache is not supported on Azure

There will not be any compliation errors, but HttpRunTime.Cache always returns null for any requested key

HttpRuntime.Case just works fine

Which of my assumptions is correct?

答: You can use HttpRuntime.Cache in Azure web role without any problem as we too are using it. Thing to keep in mind is that this Cache is machine specific, in case you have multiple instance running, each would have its own cache data. </p>


问:
VS Code: debug project .NET Core project that resides in a subfolder
After moving my .NET Core project into a subfolder in the solution I am no longer able to Debug it using VS Code.

If I move tasks.json and launch.json into the project folder and open VS Code there I am able to debug, but I would like to be able to open the entire solution in VS Code.

The error message I am getting is this:

MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.

The error seems to state that my task runner can no longer find my project, so I tried adding this to tasks.json:

```<code>{
    "version": "0.1.0",
    "command": "dotnet",
    "isShellCommand": true,
    "args": [],
    "tasks": [
        {
            "taskName": "build",
            "args": [ ],
            "isBuildCommand": true,
            "showOutput": "silent",
            "problemMatcher": "$msCompile"
        }
    ],

    // My addition
    "options": {
        "cwd": "${workspaceRoot}/myProjectFolder"
    }
}
</code>```

Doing this I am able to start the task, but I then get the following error:

```<code>Exception thrown: 'System.IO.FileNotFoundException' in
Microsoft.Extensions.Configuration.FileExtensions.dll
</code>```

How do I configure the .NET Core debugger to be able to run a project that resides in a sub folder?

答:
The reason for the FileNotFoundException pointed by mrtedweb, the program not finding the appsettings.json can be solved without changing the program code.

Just edit launch.json, modifying the cwd configuration to point to the project subfolder instead of the root workspace which is the default, from
cwd: ${workspaceRoot} to, ${workspaceRoot}/TheProject.

```<code>// C:\Solution\.vscode\launch.json
{
    "version": "0.2.0",
    "configurations": [
           {
                "name": ".NET Core Launch (console)",
                "type": "coreclr",
                "request": "launch",
                "preLaunchTask": "build",
                "program": "${workspaceRoot}/TheProject/bin/Debug/netcoreapp1.1/TheProject.dll",
                "args": [],
                "cwd": "${workspaceRoot}/TheProject",
                "stopAtEntry": false,
                "console": "internalConsole",
                "env": {
                    "ASPNETCORE_ENVIRONMENT": "Development",
                    "ASPNETCORE_URLS": "http://localhost:5050"
                }
            }
    ]
}
</code>```

With this launch.json, it's possible to run the application from VS Code opening it from a root solution folder with the project inside a subfolder.

```<code>C:\Solution>code .
</code>```

And it can also be run from the commandline without changing the paths in the program from the project subfolder.

```<code>C:\Solution\TheProject>dotnet run TheProject.csproj
</code>```

Body:
After moving my .NET Core project into a subfolder in the solution I am no longer able to Debug it using VS Code.

If I move tasks.json and launch.json into the project folder and open VS Code there I am able to debug, but I would like to be able to open the entire solution in VS Code.

The error message I am getting is this:

MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.

The error seems to state that my task runner can no longer find my project, so I tried adding this to tasks.json:

{
    "version": "0.1.0",
    "command": "dotnet",
    "isShellCommand": true,
    "args": [],
    "tasks": [
        {
            "taskName": "build",
            "args": [ ],
            "isBuildCommand": true,
            "showOutput": "silent",
            "problemMatcher": "$msCompile"
        }
    ],

    // My addition
    "options": {
        "cwd": "${workspaceRoot}/myProjectFolder"
    }
}

Doing this I am able to start the task, but I then get the following error:

Exception thrown: 'System.IO.FileNotFoundException' in
Microsoft.Extensions.Configuration.FileExtensions.dll

How do I configure the .NET Core debugger to be able to run a project that resides in a sub folder?

Body:
The reason for the FileNotFoundException pointed by mrtedweb, the program not finding the appsettings.json can be solved without changing the program code.

Just edit launch.json, modifying the cwd configuration to point to the project subfolder instead of the root workspace which is the default, from
cwd: ${workspaceRoot} to, ${workspaceRoot}/TheProject.

// C:\Solution\.vscode\launch.json
{
    "version": "0.2.0",
    "configurations": [
           {
                "name": ".NET Core Launch (console)",
                "type": "coreclr",
                "request": "launch",
                "preLaunchTask": "build",
                "program": "${workspaceRoot}/TheProject/bin/Debug/netcoreapp1.1/TheProject.dll",
                "args": [],
                "cwd": "${workspaceRoot}/TheProject",
                "stopAtEntry": false,
                "console": "internalConsole",
                "env": {
                    "ASPNETCORE_ENVIRONMENT": "Development",
                    "ASPNETCORE_URLS": "http://localhost:5050"
                }
            }
    ]
}

With this launch.json, it's possible to run the application from VS Code opening it from a root solution folder with the project inside a subfolder.

C:\Solution>code .

And it can also be run from the commandline without changing the paths in the program from the project subfolder.

C:\Solution\TheProject>dotnet run TheProject.csproj


问:
Extracting ASX data using pandas
I am trying to extract stock market data from yahoo finance following is the link https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX

My code is as follows

```<code>import pandas as pd
dfs = pd.read_html('https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX')
print(dfs)
</code>```

The above code leads to following error

```<code>Traceback (most recent call last):
  File "/home/furqan/Desktop/Data/Fundamental Analysis/get_data/ax_data.py", line 5, in <module>
    dfs = pd.read_html('https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX')
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 874, in read_html
    parse_dates, tupleize_cols, thousands, attrs, encoding)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 747, in _parse
    thousands=thousands))
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 628, in _data_to_frame
    _expand_elements(body)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 611, in _expand_elements
    body[ind] += empty * (lens_max - length)
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U47') dtype('<U47') dtype('<U47')
</code>```

How can I solve this issue?

答:
Thanks done using.</p>

```<code>import fix_yahoo_finance as yf
data = yf.download("SPY", start="2017-01-01", end="2017-04-30")
</code>```

Title: Extracting ASX data using pandas

Body:
I am trying to extract stock market data from yahoo finance following is the link https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX

My code is as follows

import pandas as pd
dfs = pd.read_html('https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX')
print(dfs)

The above code leads to following error

Traceback (most recent call last):
  File "/home/furqan/Desktop/Data/Fundamental Analysis/get_data/ax_data.py", line 5, in <module>
    dfs = pd.read_html('https://au.finance.yahoo.com/quote/ABP.AX/history?p=ABP.AX')
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 874, in read_html
    parse_dates, tupleize_cols, thousands, attrs, encoding)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 747, in _parse
    thousands=thousands))
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 628, in _data_to_frame
    _expand_elements(body)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/html.py", line 611, in _expand_elements
    body[ind] += empty * (lens_max - length)
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U47') dtype('<U47') dtype('<U47')

How can I solve this issue?

Body:
Thanks done using.

import fix_yahoo_finance as yf
data = yf.download("SPY", start="2017-01-01", end="2017-04-30")


问:
Purchasing Amazon reserved instances based on average usage
It seems possible to purchase reserved instances based on average usage instead of initial usage.  For example, if I purchased 2 RIs, ran 1 instance on day 1 and ran 3 instances on day 2, it will be essentially the same usage rate as if I ran 2 instances for 2 days.  Will RI calculation see it that way, or will I be charged 3 days of RI usage and 1 day of on-demand usage?</p>

答:
Reserved instances look at concurrent run times only. If you have two reserved RIs, and you are running 3 instances for 1 day and 1 instance for 1 day, you are NOT covered by your RI allocations, instead, you pay for 1 on-demand day.

Under the hood there is literal capacity reserved for you, so it wouldnt make sense otherwise


问:
Rxjs Retry with Delay function
I am trying to use retry with delay function, I expect function will call after 1000ms delay, but it doesnot, what can be error here?
look at console output, it is same time 16:22:48.

I expect there 16:22:48, 16:22:59 ...

```<code>canCreate: boolean;
getSomeFunction(): Observable<boolean> {
        return new Observable<boolean>(
            observer => {
                const canCreate = null; // this is just null for now, will some value later
                if (canCreate == null) {
                    observer.error('error');
                } else {
                    observer.next(true);
                }
                observer.complete();
            }
        )
    }

this.getSomeFunction()
      .do((value) => {
        this.cCreate = value;
      }, (error) => {
         console.log(error + new Date().toTimeString());
      })
      .delay(1000)
      .retry(10)
      .subscribe(
        value => this.cCreate = value,
        error => {
          this.cCreate = false;
        },
        () => {}
      );
  }
</code>```

and console result is :

答:
I come up with following solution using retryWhen and Observable.Interval, but in this solution, error function of subscribe never calls,

```<code>this.branchService.getCanCreate()
  .do((value) => {
    this.cCreate = value;
  }, (error) => {
    console.log('do', error + new Date().toTimeString());
  })
  .retryWhen(errors => {
    return Observable.interval(1000).take(3).concat(Observable.throw('error')));
  })
  .subscribe(
    value => {
      this.cCreate = !!value
      console.log('success', new Date().toTimeString());
    },
    error => {
      console.log('subscribe', error + new Date().toTimeString());
      this.cCreate = false;
    },
    () => {
      console.log('finally', new Date().toTimeString());
    }
  );
</code>```

Title: Rxjs Retry with Delay function

Body:
I am trying to use retry with delay function, I expect function will call after 1000ms delay, but it doesnot, what can be error here?
look at console output, it is same time 16:22:48.

I expect there 16:22:48, 16:22:59 ...

canCreate: boolean;
getSomeFunction(): Observable<boolean> {
        return new Observable<boolean>(
            observer => {
                const canCreate = null; // this is just null for now, will some value later
                if (canCreate == null) {
                    observer.error('error');
                } else {
                    observer.next(true);
                }
                observer.complete();
            }
        )
    }

this.getSomeFunction()
      .do((value) => {
        this.cCreate = value;
      }, (error) => {
         console.log(error + new Date().toTimeString());
      })
      .delay(1000)
      .retry(10)
      .subscribe(
        value => this.cCreate = value,
        error => {
          this.cCreate = false;
        },
        () => {}
      );
  }

and console result is :

Body:
I come up with following solution using retryWhen and Observable.Interval, but in this solution, error function of subscribe never calls,

this.branchService.getCanCreate()
  .do((value) => {
    this.cCreate = value;
  }, (error) => {
    console.log('do', error + new Date().toTimeString());
  })
  .retryWhen(errors => {
    return Observable.interval(1000).take(3).concat(Observable.throw('error')));
  })
  .subscribe(
    value => {
      this.cCreate = !!value
      console.log('success', new Date().toTimeString());
    },
    error => {
      console.log('subscribe', error + new Date().toTimeString());
      this.cCreate = false;
    },
    () => {
      console.log('finally', new Date().toTimeString());
    }
  );


问:
print values of all items in array JAVASCRIPT / d3
Sorry if it's a bit rookie:

I have a csv file turned into array with property-value duos.

```<code>console.log(data);
console.log(data[0].property_name);
console.log(data.property_name);
</code>```

first and second line work perfectly
the third line doesn't work (returns undefined)

答:
Data is an array. Each element in the array presumably has a property_name. So data[0], or the first element in the array, works just fine. If you want all the values printed out use a for loop or foreach loop or print each out like...

```<code>console.log(data[0].property_name);
console.log(data[1].property_name);
</code>```

For Loop

```<code>for (i = 0; i < data.length; i++) {
    console.log(i);
    console.log(data[i].property_name);
}
</code>```

Body:
Sorry if it's a bit rookie:

I have a csv file turned into array with property-value duos.

console.log(data);
console.log(data[0].property_name);
console.log(data.property_name);

first and second line work perfectly
the third line doesn't work (returns undefined)

Body:
Data is an array. Each element in the array presumably has a property_name. So data[0], or the first element in the array, works just fine. If you want all the values printed out use a for loop or foreach loop or print each out like...

console.log(data[0].property_name);
console.log(data[1].property_name);

For Loop

for (i = 0; i < data.length; i++) {
    console.log(i);
    console.log(data[i].property_name);
}


问:
using the same webpart logic with different look in Sharepoint 2010
I have a custom developed webpart in Visual studio, and I want to use this same functionality in my sharepoint site multiple times but with different looks every time.

what's the best practice to achieve this?

答:
i would suggest used xslt based custom webpart so that you can apply different xslt on each instance to get different look and feel good example for the same is sharepoint coreresult webpart.

You have to inherit your webpart from  DataFormWebPart


问:
Access Bootstrap in jsfiddle
I am building this project in jsfiddle. I have imported the bootstrap resources I saw other people use, but bootstrap is not applying. For example, the submit button looks as follows:

```<code><input type="submit" class="btn btn-login" id="login-button">
</code>```

But in practice, it is a standard html button. I also tried to create three columns across the top like so:

```<code><div className="col-md-4">
    <p>
    fil
    </p>
  </div>
  <div className="col-md-4">
    <p>
    fil
    </p>
  </div>
  <div className="col-md-4">
    <p>
    fil
    </p>
  </div>
</code>```

But they end up just stacking on each other, rather than filling out the column. I have bootstrap.min.css and bootstrap.min.js. Am I missing any resources? How can I get bootstrap to function in this fiddle?

答:
The bootstrap CDN you linked in the External Resources on you JSfiddle is broken.

try use these ones

CSS: https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css

jQuery: https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js

JS: https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js

Title: Access Bootstrap in jsfiddle

Body:
I am building this project in jsfiddle. I have imported the bootstrap resources I saw other people use, but bootstrap is not applying. For example, the submit button looks as follows:

<input type="submit" class="btn btn-login" id="login-button">

But in practice, it is a standard html button. I also tried to create three columns across the top like so:

    fil

    fil

    fil

But they end up just stacking on each other, rather than filling out the column. I have bootstrap.min.css and bootstrap.min.js. Am I missing any resources? How can I get bootstrap to function in this fiddle?


问:
Is there a software that can read a lot of document filetypes
I know that, if you want to watch movies or videos, there is a program called VLC media player that lets you read many many media file types.
I am looking for something like this for document files (pdf, epub, ebook, doc, docx, rtf, html, txt, ... )

Thanks in advance if you know such a thing

答:
Calibre supports all of these formats.

I don't really know what you mean by the 'ebook' format, but Calibre can read EPUB, MOBI and AZW formats.


问:
How to have an optional parameter in Angular UI-Router v 1.+
In an older version (0.4?) of angular ui-router we could do this...

url: '/:optional'

And everything worked fine (minus an extra backslash in the url). But when I upgraded to 1.0.5 I see...

Error: Param values not valid for state 'projects.list'. Invalid params: [ optional ]

I tried...

url: '/{mine:(?:/[^/]+)?}' too but it didn't work either

Is there a way I can do this in the 1.0 world?

答:
Take a look at this answer to a similar question.

Also, as stated in the UI Router's documentation:

Route parameters with regular expressions can't be optional or greedy


问:
DataTables warning: Requested unknown parameter '0' from the data source for row '0'
Does anybody please know, what is wrong with the very simple HTML file below?

I am just trying to use an array of objects as the data source for DataTables:

tests.html:

```<code><html>
<head>
<link type="text/css" rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<link type="text/css" rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.2/css/jquery.dataTables_themeroller.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.2/jquery.dataTables.min.js"></script>
<script type="text/javascript">

var data = [
    {"Name":"UpdateBootProfile","Result":"PASS","ExecutionTime":"00:00:00","Measurement":[]},
    {"Name":"NRB Boot","Result":"PASS","ExecutionTime":"00:00:50.5000000","Measurement":[{"TestName":"TOTAL_TURN_ON_TIME","Result":"PASS","Value":"50.5","LowerLimit":"NaN","UpperLimit":"NaN","ComparisonType":"nctLOG","Units":"SECONDS"}]},
    {"Name":"NvMgrCommit","Result":"PASS","ExecutionTime":"00:00:00","Measurement":[]},
    {"Name":"SyncNvToEFS","Result":"PASS","ExecutionTime":"00:00:01.2500000","Measurement":[]}
];

$(function() {
        var testsTable = $('#tests').dataTable({
                bJQueryUI: true,
                aaData: data,
                aoColumns: [
                        { mData: 'Name' },
                        { mData: 'Result' },
                        { mData: 'ExecutionTime' }
                ]
        });
});

</script>
</head>
<body>

<table id="tests">
<thead>
<tr>
<th>Name</th>
<th>Result</th>
<th>ExecutionTime</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

</body>
</html>
</code>```

UPDATE: Ok, I've got the answer from the author to use a newer version of DataTables or rename mData to mDataProp

答:
This plagued me for over an hour.

If you're using the dataSrc option and column defs option, make sure they are in the correct locations. I had nested column defs in the ajax settings and lost way too much time figuring that out.

This is good:

This is not good:

Subtle difference, but real enough to cause hair loss.

Body:
Does anybody please know, what is wrong with the very simple HTML file below?

I am just trying to use an array of objects as the data source for DataTables:

tests.html:

<link type="text/css" rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<link type="text/css" rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.2/css/jquery.dataTables_themeroller.css">

Name
Result
ExecutionTime

UPDATE: Ok, I've got the answer from the author to use a newer version of DataTables or rename mData to mDataProp


问:
Ajax generated content, unable to hide when onclick
Here is my code:

HTML Code: (Dynamic Generated by ajax).

```<code><div class="btn btn-primary" image-data="imagedata" name-data="name data" artist-data="artist data" country-data="in" id="1252785363" onclick="ajax($(this));return false;">Add Album</div>
<div class="btn btn-primary" image-data="imagedata" name-data="name data" artist-data="artist data" country-data="in" id="1252985363" onclick="ajax($(this));return false;">Add Album</div>
<div class="btn btn-primary" image-data="imagedata" name-data="name data" artist-data="artist data" country-data="in" id="1256985363" onclick="ajax($(this));return false;">Add Album</div>
</code>```

Each DIV has unique ID!

Javascript:

```<code>function ajax($this) {
  var id = $this.attr("id");
  var image_data = $this.attr("image-data");
  var name_data = $this.attr("name-data");
  var artist_data = $this.attr("artist-data");
  var country_data = $this.attr("country-data");

  $.ajax({
    method: "POST",
    url: "URL to Call",
    dataType: "text",
    data: {
      image: image_data,
      artist: artist_data,
      name: name_data,
      country: country_data,
      id: id
    },
    success: function(response) {
      console.log(response);
      $(id).hide();
      alert(id);
    }
  });
}
</code>```

Its return the response, its alert the ID, but somehow i am unable to find, i try $(id).css('display', 'none'); , toggle but no luck!

If possible please let me know the solution!

答:
You need to use a # prefix to select an ID.

```<code>$("#" + id).hide();
</code>```

Body:
Here is my code:

HTML Code: (Dynamic Generated by ajax).

Add Album

Add Album

Add Album

Each DIV has unique ID!

Javascript:

function ajax($this) {
  var id = $this.attr("id");
  var image_data = $this.attr("image-data");
  var name_data = $this.attr("name-data");
  var artist_data = $this.attr("artist-data");
  var country_data = $this.attr("country-data");

  $.ajax({
    method: "POST",
    url: "URL to Call",
    dataType: "text",
    data: {
      image: image_data,
      artist: artist_data,
      name: name_data,
      country: country_data,
      id: id
    },
    success: function(response) {
      console.log(response);
      $(id).hide();
      alert(id);
    }
  });
}

Its return the response, its alert the ID, but somehow i am unable to find, i try $(id).css('display', 'none'); , toggle but no luck!

If possible please let me know the solution!

Body:
You need to use a # prefix to select an ID.

$("#" + id).hide();


问:
How to get returned div's offset/position in react?
In my code return i have:

```<code>return (
  <div  className="pos__container" >
  <div  className="pos__container--line" ></div>
    {timeList}
  </div>
);
</code>```

 has margin-left:10%; other styles are irrelevant.

In the function under constructor I want to get its position.

To get the offset i need to get a div first.

I have tried:
const element = ReactDOM.findDOMNode(this); which returns
findDOMNode was called on an unmounted component.

Also tried using document.QuerySelector(".pos__container--line"); which returns null

Feel like I'm out of the options.

Any suggestions how I could do this right or any other ways to do it ?

Any help would be appreciated.

Thanks in advance!

答:
First, you need to add a ref to the element you are interested in:

```<code>return (
  <div  className="pos__container" >
  <div  className="pos__container--line" ref={el => this.containerLine = el} ></div>
    {timeList}
  </div>
);
</code>```

Then you can access that ref after the component was rendered:

```<code>componentDidMount() {
    // it is a regular DOM node
    this.containerLine.offsetTop
    // or with jquery
    $(this.containerLine).offset()
}
</code>```

Body:
In my code return i have:

return (

    {timeList}

);

 has margin-left:10%; other styles are irrelevant.

In the function under constructor I want to get its position.

To get the offset i need to get a div first.

I have tried:
const element = ReactDOM.findDOMNode(this); which returns
findDOMNode was called on an unmounted component.

Also tried using document.QuerySelector(".pos__container--line"); which returns null

Feel like I'm out of the options.

Any suggestions how I could do this right or any other ways to do it ?

Any help would be appreciated.

Thanks in advance!

Body:
First, you need to add a ref to the element you are interested in:

return (
  <div  className="pos__container" >
  <div  className="pos__container--line" ref={el => this.containerLine = el} ></div>
    {timeList}
  </div>
);

Then you can access that ref after the component was rendered:

componentDidMount() {
    // it is a regular DOM node
    this.containerLine.offsetTop
    // or with jquery
    $(this.containerLine).offset()
}


问:
Using CSS for layout, clearing float for stating on next line ?? Need to create a layout of 2 cols and 5 rows
I have created a layout using DIVs rather than tables. It seems to be working... I had to clear:none after each div consisting of column and content.

But i end up with an extra line under each 2 columns before the other 2 columns start. I will outlay my code below, what am i doing wrong?.. What i want to do is create a table like layout but using divs consisting of 5 rows and each row have 2 columns.

```<code> <div id="column1" style="float:left;width:200px;">1st Title</div>
 <div id="container1" style="float:left;"> <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList></div>
 <div style="clear:both;"></div>
 <div id="column2" style="float:left;width:200px;">2nd Title</div>
 <div id="container2" style="float:left;"> <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList></div>
 <div style="clear:both;"></div>
</code>```

答:
Why don't you use display attribute rather than float, e.g. (you'll need to group your divs within divs with class "row"):

```<code>.row {
    display: table-row;
}

#column1, #container1, #column2, #container2 {
    display: table-cell;
}
</code>```

Body:
I have created a layout using DIVs rather than tables. It seems to be working... I had to clear:none after each div consisting of column and content.

But i end up with an extra line under each 2 columns before the other 2 columns start. I will outlay my code below, what am i doing wrong?.. What i want to do is create a table like layout but using divs consisting of 5 rows and each row have 2 columns.

1st Title

 <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

2nd Title

 <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

Body:
Why don't you use display attribute rather than float, e.g. (you'll need to group your divs within divs with class "row"):

.row {
    display: table-row;
}

#column1, #container1, #column2, #container2 {
    display: table-cell;
}


问:
ProcessBuilder can't find command, though it can be found in terminal
I have a Java application which starts Mopidy via ProcessBuilder.
This is my code:

```<code>if(mopidy==null){
     try {
         btnStartMopidy.setDisable(true);
         btnStopMopidy.setDisable(false);
         ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "mopidy");
         pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
         pb.redirectError(ProcessBuilder.Redirect.INHERIT);
         mopidy = pb.start();
     } catch (IOException ex) {
         ex.printStackTrace();
         Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
     }
 }
</code>```

The weird thing is when I run it from Netbeans, the output says the Mopidy command cannot be found, BUT..

When I run the built .jar file via the terminal, I get the expected Mopidy output. When I run the .jar file by double clicking on it, I get the same error saying the command cannot be found.

Any thoughts?

EDIT:

This time I tried to invoke the program directly instead of using bash -c.

```<code>ProcessBuilder pb = new ProcessBuilder("/usr/local/bin/mopidy");
</code>```

It seems Mopidy can be found now, but I'm getting a different error. It says that a certain Python package (GStreamer, which is required for Mopidy) cannot be found, though it is installed.

答: This is a weird bug in eclipse that never gets fixed.  Don't restart your eclipse after adding it to PATH variable.  Exit eclipse and start again and it should work.</p>

Body:
I have a Java application which starts Mopidy via ProcessBuilder.
This is my code:

if(mopidy==null){
     try {
         btnStartMopidy.setDisable(true);
         btnStopMopidy.setDisable(false);
         ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "mopidy");
         pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
         pb.redirectError(ProcessBuilder.Redirect.INHERIT);
         mopidy = pb.start();
     } catch (IOException ex) {
         ex.printStackTrace();
         Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
     }
 }

The weird thing is when I run it from Netbeans, the output says the Mopidy command cannot be found, BUT..

When I run the built .jar file via the terminal, I get the expected Mopidy output. When I run the .jar file by double clicking on it, I get the same error saying the command cannot be found.

Any thoughts?

EDIT:

This time I tried to invoke the program directly instead of using bash -c.

ProcessBuilder pb = new ProcessBuilder("/usr/local/bin/mopidy");

It seems Mopidy can be found now, but I'm getting a different error. It says that a certain Python package (GStreamer, which is required for Mopidy) cannot be found, though it is installed.


问:
Matplotlib fixed figure size and subplots positions
I'm bothering you with a question about subplot sizes in matplotlib. I need to create a figure of a fixed size composed of 3 subplots in a single row. For 'editorial reasons' I need fix the size of the figure But I also want to fix the sizes and positions of the subplots without affecting the figure size (the third subplot must be narrower than the first two).

I tried using GridSpec without success. I also tried fixing the figure size with "figsize" and using add_axes for the subplots but, depending of the relative size of the subplots, the overall size of the figure and the subplots changes.

When using gnuplot one can use "set origin" and "set size" for the subplots. Us there something similar in matplotlib?

答:
Something like this? Changing the width ratio will change the sizes of the individual subplots.

```<code>fig, [ax1, ax2, ax3] = plt.subplots(1,3, gridspec_kw = {'width_ratios':[3, 2, 1]}, figsize=(10,10))

plt.show()
</code>```

If you want to have some more control over the sizes you could also use Axes. It is still relative, but now in fractions of the entire figure size.

```<code>import matplotlib.pyplot as plt

# use plt.Axes(figure, [left, bottom, width, height])
# where each value in the frame is between 0 and 1

# left
figure = plt.figure(figsize=(10,3))
ax1 = plt.Axes(figure, [.1, .1, .25, .80])
figure.add_axes(ax1)
ax1.plot([1, 2, 3], [1, 2, 3])

# middle
ax2 = plt.Axes(figure, [.4, .1, .25, .80])
figure.add_axes(ax2)
ax2.plot([1, 2, 3], [1, 2, 3])

# right
ax3= plt.Axes(figure, [.7, .1, .25, .80])
figure.add_axes(ax3)
ax3.plot([1, 2, 3], [1, 2, 3])

plt.show()
</code>```

Body:
Something like this? Changing the width ratio will change the sizes of the individual subplots.

fig, [ax1, ax2, ax3] = plt.subplots(1,3, gridspec_kw = {'width_ratios':[3, 2, 1]}, figsize=(10,10))

plt.show()

If you want to have some more control over the sizes you could also use Axes. It is still relative, but now in fractions of the entire figure size.

import matplotlib.pyplot as plt

# use plt.Axes(figure, [left, bottom, width, height])
# where each value in the frame is between 0 and 1

# left
figure = plt.figure(figsize=(10,3))
ax1 = plt.Axes(figure, [.1, .1, .25, .80])
figure.add_axes(ax1)
ax1.plot([1, 2, 3], [1, 2, 3])

# middle
ax2 = plt.Axes(figure, [.4, .1, .25, .80])
figure.add_axes(ax2)
ax2.plot([1, 2, 3], [1, 2, 3])

# right
ax3= plt.Axes(figure, [.7, .1, .25, .80])
figure.add_axes(ax3)
ax3.plot([1, 2, 3], [1, 2, 3])

plt.show()


问:
View Stackify Prefix for all IIS sites
I'm running Stackify Prefix (v2.5.19) and a bunch of (IIS hosted) micro services on my local machine.

SP seems to only show events from some of the applications in the browser. However, when I examine C:\Program Files (x86)\StackifyPrefix\profiles\, I can see paths corresponding to the process id's of the other services, and the expected data is in the profile0.log file.

How do I get SP to display this data for all of my applications in the browser?

答:
Prefix for non-web apps takes some additional work to do.  The problem is that Prefix doesn't know how to define the start and end of a transaction natively.  There are some things that we do automatically figure out and we are building more support for known non-iis transactions but the best method is to instrument those yourself.

Here is a guide to how to do it.

http://support.stackify.com/hc/en-us/articles/210565263-How-to-use-Prefix-with-non-IIS-NET-applications

Title: View Stackify Prefix for all IIS sites


问:
How to open 10 browsers with jmeter
I'm using jmeter for performance testing.I used Selenium for functional testing.I want to test 10 users access same login page at same time.I can do that with jmeter. I want to open 10 browsers at same time(like selenium )and display on screen,can I do that using jmeter??Is there any plugin  that I can use for this??</p>

答:
BadBoy may be useful for you here:
http://www.badboy.com.au/

It's free software that records your actions, which you can then export to a jmx file to run as a test script.

Title: How to open 10 browsers with jmeter


问:
Trouble with Angular UI Bootstrap Datepicker
I need to integrate the datepicker but its not working properly.

This is my HTML

```<code> <div class="form-group">
                <label>Date</label>
                <p class="input-group">
        <input type="text" class="form-control"
         datepicker-popup="mediumDate"
         is-open="shipment.valuationDatePickerIsOpen"
        ng-click="shipment.valuationDatePickerOpen()"
        ng-model="shipment.valuationDate" />
  <span class="input-group-btn">
     <button type="button" class="btn btn-default"
        ng-click="shipment.valuationDatePickerOpen($event)">
         <i class="fa fa-calendar"></i>
     </button>
</span>
</p>

</div>
</code>```

And this is my controller

```<code>var vm = this;
    // $scope.Eship;

      vm.valuationDate = new Date();
  vm.valuationDatePickerIsOpen = false;
  vm.opens = [];

  $scope.$watch(function () {
       return vm.valuationDatePickerIsOpen;
   },function(value){
      vm.opens.push("valuationDatePickerIsOpen: " + value + " at: " + new Date());
   });

  vm.valuationDatePickerOpen = function ($event) {

      if ($event) {
          $event.preventDefault();
          $event.stopPropagation();
      }
      this.valuationDatePickerIsOpen = true;
  };
</code>```

I already import the ui-bootstrap directive.
I dont know whats missing or whats wrong.

答:
You have the issue because you're using datepicker-popup instead of uib-datepicker-popup directive.
Just make sure you're using right versions of Angular and UI Bootstrap, then take a look on the Docs of that module.

I fixed your example, please find the code here: https://plnkr.co/edit/cMj8IXD7KYTUgi7hY0W7?p=preview

I hope it helps.

Body:
I need to integrate the datepicker but its not working properly.

This is my HTML

                Date

        <input type="text" class="form-control"
         datepicker-popup="mediumDate"
         is-open="shipment.valuationDatePickerIsOpen"
        ng-click="shipment.valuationDatePickerOpen()"
        ng-model="shipment.valuationDate" />

     <button type="button" class="btn btn-default"
        ng-click="shipment.valuationDatePickerOpen($event)">

     </button>

And this is my controller

var vm = this;
    // $scope.Eship;

      vm.valuationDate = new Date();
  vm.valuationDatePickerIsOpen = false;
  vm.opens = [];

  $scope.$watch(function () {
       return vm.valuationDatePickerIsOpen;
   },function(value){
      vm.opens.push("valuationDatePickerIsOpen: " + value + " at: " + new Date());
   });

  vm.valuationDatePickerOpen = function ($event) {

      if ($event) {
          $event.preventDefault();
          $event.stopPropagation();
      }
      this.valuationDatePickerIsOpen = true;
  };

I already import the ui-bootstrap directive.
I dont know whats missing or whats wrong.


问:
Batch file selection based on partial filename, or highest number
I'm trying to come up with a small menu structure and resulting file selection to apply Windows image files.

Scenario:
I want to be able to select a single WIM file from a directory with an option to either choose the newest, or a specific version, based on the numbering.

Image_Name_101.wim
 Image_Name_102.wim
 Image_Name_103.wim

etc. exist, user can either go for option (1) and pick the highest number/latest image, or manually enter the revision number to choose an older image.

Ideally, the selected file is then passed into a DISM command, which applies the image. (eg dism /Apply-Image /ImageFile:X:\*Image_Name_102.wim* /Index:1 /ApplyDir:C:\ )

I have found somewhat similar examples but fail to apply them to my project.
Any pointers, hints, help is welcome.

答:
```<code>echo off
setlocal enabledelayedexpansion
set count=0
for %%a in (imagename*.wim) do (
  set /a count+=1
  echo !count!  %%a
  set "file[!count!]=%%a"
)
:Loop
set /p "nr=Enter Number: "
set /a nr=%nr%
if %nr% leq 0 goto :Loop
if %nr% gtr %count% goto :Loop

ECHO dism /Apply-Image /ImageFile:X:\!file[%nr%]! /Index:1 /ApplyDir:C:\
</code>```

remove the ECHO when the output is ok.

the for loop enumerates all matching files. The :Loop part gets user input and does a basic input validation.

Body:
echo off
setlocal enabledelayedexpansion
set count=0
for %%a in (imagename*.wim) do (
  set /a count+=1
  echo !count!  %%a
  set "file[!count!]=%%a"
)
:Loop
set /p "nr=Enter Number: "
set /a nr=%nr%
if %nr% leq 0 goto :Loop
if %nr% gtr %count% goto :Loop

ECHO dism /Apply-Image /ImageFile:X:\!file[%nr%]! /Index:1 /ApplyDir:C:\

remove the ECHO when the output is ok.

the for loop enumerates all matching files. The :Loop part gets user input and does a basic input validation.


问:
Is there a way to call a function in ListView?
I have a ListView and I want to execute a script in python to update our database everytime I enter in the listview, or periodically.

Is there a way to do that ?

```<code>class AccessPointList(generic.ListView): #receives the whole set of AccessPoint and send to HTML
model = AccessPoint
#call a function in python -> c.update()
#or create a def to update our database
</code>```

答:
Sure, just override one of the methods when you want to run it, then call super to continue with normal execution of the ListView</p>

```<code>class AccessPointList(generic.ListView):
    model = AccessPoint

    def get(self, request, *args, **kwargs):
        # call your function
        return super().get(request, *args, **kwargs)
</code>```

Body:
I have a ListView and I want to execute a script in python to update our database everytime I enter in the listview, or periodically.

Is there a way to do that ?

class AccessPointList(generic.ListView): #receives the whole set of AccessPoint and send to HTML
model = AccessPoint
#call a function in python -> c.update()
#or create a def to update our database

Body:
Sure, just override one of the methods when you want to run it, then call super to continue with normal execution of the ListView

class AccessPointList(generic.ListView):
    model = AccessPoint

    def get(self, request, *args, **kwargs):
        # call your function
        return super().get(request, *args, **kwargs)


问:
Renew Push certificate and keep current App Store App working
I have an app on app store, which is using an iOS Provisioning Profile (Distribution) which is expired.
This Profile contains Push Certificate that's also expired (and does not appear anymore in the portal).

Question 1:
Is there a way to recreate the push certificate and then renew the profile?  (I still have the push certificate (expired) on my keychain)?

Question 2:
Do I need to re-submit the app to app store with a new profile that contains the new Push certificate?

Since the push certificate is expired, I can probably not send notifications to the existing users of the app.

答:
For the Apple side:

Log into https://identity.apple.com/pushcert/

View your certificate and identify what service it is for

Click "Renew"

Your service:

Log in and find the "push certificate setup" area (for google this is Mobile Apple Push Cert

Download your services signing request

Apple:

Upload your signing request

Download their response

Your service:

Upload the signed response

At this point, everything should be set


问:
How to GROUP and SUM json data using angular/ionic?
I have a JSON object that looks like this:

```<code>  "Classes": [
    {
      "ID": "MATH101",
      "Class": "Math",
      "StudentCount": "2"
    },
    {
      "ID": "MATH101",
      "Class": "Math",
      "StudentCount": "8"
    },
    {
      "ID": "ENGLISH101",
      "Class": "English",
      "StudentCount": "13"
    }]
</code>```

This JSON object is stored in $scope.
How can I first group the data by Class and then SUM the StudentCount?

So the resulting JSON object would look something like this - ideally stored as a new scope variable:

```<code>  "Classes": [
    {
      "ID": "MATH101",
      "Class": "Math",
      "StudentCount": "10"
    },
    {
      "ID": "ENGLISH101",
      "Class": "English",
      "StudentCount": "13"
    }]
</code>```

I've searched everywhere, and the only thing I can find are examples of doing this in conjunction with an ng-repeat, but I'm not using that here. I just need to massage this data for use in angular-chartjs.

Thank you very much for taking the time to look at my question.

答:
the transformation is just a logical part, your ng-repeat and all you can use then to render that in UI how you want.

here I am writing a function that will do the job for you

```<code>function populateSumArray(inputClasses) {
    opClasses = [];
    inputClasses.forEach(function(item) {
        var existing = opClasses.find(function(each) {
            return each.Class === item.Class;
        });
        if (existing) {
            existing.StudentCount = parseInt(existing.StudentCount) + parseInt(item.StudentCount);
        } else {
            opClasses.push(item);
        }
    });
    return opClasses;
}
</code>```

and you can call this to transform it to a new array (calculated) and store it whereever you need. If you want to update the same scope variable then here is an example

```<code>$scope.Classes = populateSumArray($scope.Classes)
</code>```

hope, it helps :)

Body:
I have a JSON object that looks like this:

  "Classes": [
    {
      "ID": "MATH101",
      "Class": "Math",
      "StudentCount": "2"
    },
    {
      "ID": "MATH101",
      "Class": "Math",
      "StudentCount": "8"
    },
    {
      "ID": "ENGLISH101",
      "Class": "English",
      "StudentCount": "13"
    }]

This JSON object is stored in $scope.
How can I first group the data by Class and then SUM the StudentCount?

So the resulting JSON object would look something like this - ideally stored as a new scope variable:

  "Classes": [
    {
      "ID": "MATH101",
      "Class": "Math",
      "StudentCount": "10"
    },
    {
      "ID": "ENGLISH101",
      "Class": "English",
      "StudentCount": "13"
    }]

I've searched everywhere, and the only thing I can find are examples of doing this in conjunction with an ng-repeat, but I'm not using that here. I just need to massage this data for use in angular-chartjs.

Thank you very much for taking the time to look at my question.

Body:
the transformation is just a logical part, your ng-repeat and all you can use then to render that in UI how you want.

here I am writing a function that will do the job for you

function populateSumArray(inputClasses) {
    opClasses = [];
    inputClasses.forEach(function(item) {
        var existing = opClasses.find(function(each) {
            return each.Class === item.Class;
        });
        if (existing) {
            existing.StudentCount = parseInt(existing.StudentCount) + parseInt(item.StudentCount);
        } else {
            opClasses.push(item);
        }
    });
    return opClasses;
}

and you can call this to transform it to a new array (calculated) and store it whereever you need. If you want to update the same scope variable then here is an example

$scope.Classes = populateSumArray($scope.Classes)

hope, it helps :)


问:
Why is copying with {ctrl down}c{ctrl up} more secure than ^c?
The  AutoHotkey Beginner Tutorial includes the following sample script to demonstrate hotkeys.

```<code>^b::
   send, {ctrl down}c{ctrl up}             ; Copies the selected text. ^c could be used as well, but this method is more secure.
   SendInput, [b]{ctrl down}v{ctrl up}[/b]
Return
</code>```

The code comments suggest that {ctrl down}c{ctrl up} is a more secure way of copying text than ^c. However, the tutorial never elaborates on why the latter method is less secure.

Why is copying text with {ctrl down}c{ctrl up} considered more secure than using ^c?

答:
"Secure" in the sense they mean, is that the command is more likely to succeed in the majority of applications the command is being sent to.

First, examine the send type (SendInput, SendDirect, SendPlay, etc) and their various quirks.

When you use a Send method of any type it is not actually pressing your keyboard keys - it is sending a control message to the active window (hence the need for different send methods, sometimes).

Next, it's really all about timing, assuming the messages are getting through.

If you were to use {ctrl down}your-stuff{ctrl up} you can control the timing of each individually, such as:

```<code>Send {ctrl down}
Sleep 200
Send c
Sleep 200
Send {ctrl up}
</code>```

This sometimes becomes necessary if the system is not accepting your ^c-type command - and it's almost always due to timing or buffering issues with the sent message. I get away with ^c-type messages most of the time, when working in windowed applications. However, if you are working in a DirectX application (like a game), having explicit timing for key-down and key-up events is crucial.

Body:
The  AutoHotkey Beginner Tutorial includes the following sample script to demonstrate hotkeys.

^b::
   send, {ctrl down}c{ctrl up}             ; Copies the selected text. ^c could be used as well, but this method is more secure.
   SendInput, [b]{ctrl down}v{ctrl up}[/b]
Return

The code comments suggest that {ctrl down}c{ctrl up} is a more secure way of copying text than ^c. However, the tutorial never elaborates on why the latter method is less secure.

Why is copying text with {ctrl down}c{ctrl up} considered more secure than using ^c?

Body:
"Secure" in the sense they mean, is that the command is more likely to succeed in the majority of applications the command is being sent to.

First, examine the send type (SendInput, SendDirect, SendPlay, etc) and their various quirks.

When you use a Send method of any type it is not actually pressing your keyboard keys - it is sending a control message to the active window (hence the need for different send methods, sometimes).

Next, it's really all about timing, assuming the messages are getting through.

If you were to use {ctrl down}your-stuff{ctrl up} you can control the timing of each individually, such as:

Send {ctrl down}
Sleep 200
Send c
Sleep 200
Send {ctrl up}

This sometimes becomes necessary if the system is not accepting your ^c-type command - and it's almost always due to timing or buffering issues with the sent message. I get away with ^c-type messages most of the time, when working in windowed applications. However, if you are working in a DirectX application (like a game), having explicit timing for key-down and key-up events is crucial.


问:
Any advice for speeding up the compile time in Flex Builder 3?
I run Flex Builder 3 on a mac and as my project grows - the compile time gets longer and longer and longer.  I am using some SWC's and there is a fair amount of code but it shouldn't take minutes to build and crash daily should it?</p>

答:
I don't use Flex Builder, but I use the Flex SDK compiler everyday and I was wasting tons of time waiting for the MXMLC compiler to do its job until I found Flex Compiler SHell:

http://blog.zarate.tv/2008/12/07/theres-something-called-flex-compiler-shell/

Although in theory Flex Builder already uses this optimizations, might be worth checking.

OwnerDisplayName: onekidney

LastEditorDisplayName: travis

OwnerDisplayName: Zárate


答:
The id attribute you are reading does not contain the # selector, which JQuery wants when you search for the element.

If instead you use $("#" + id).hide(); I think you will get the result you are looking for.

Title: Ajax generated content, unable to hide when onclick


问:
R sapply/lapply with multiple ifelse statements
I'm trying to simplify the following multiple ifelse code using sapply or lapply (still can't distinguish them).

My goal is to allocate points based on placement like shown below.

```<code>df$Point <- ifelse(df$Placement_v2 <= 1, 10,
ifelse(df$Placement_v2 <= 10, 9,
ifelse(df$Placement_v2 <= 25, 8,
ifelse(df$Placement_v2 <= 50, 7, 1) )))
</code>```

This code works okay, but I want to make a dataframe and simply my code above using sapply or lapply (or anyother function).

I've tried this code but is not working as expected. Only the rows with placement 1 get 10 points and other rows end up with 1.

<2nd code>

```<code>df$Point <- sapply(df2$Placement, function(x) ifelse(df$Placement_v2 <= x, df2$Point[df2$Placement == x], 1 ) )
</code>```

How can I solve this problem?

答:
A few ways to go about this. I'll use data.table.

```<code>library(data.table)

set.seed(123)
df <- data.table(Placement_v2 = runif(200, -10, 100))
</code>```

First option, move the evaluation out to a function, and then lapply the function to your Placement_v2 column. This has the benefit of being much cleaner than your nested ifelse statements.

```<code>funky <- function(x) {

  if (x <= 1) {
    val <- 10
  } else if (x <= 10){
    val <- 9
  } else if (x <= 25){
    val <- 8
  } else if (x <= 50){
    val <- 7
  } else {
    val <- 1
  }

  return(val)

}

df[, Point := unlist(lapply(Placement_v2, funky))]
</code>```

Result:

```<code>     Placement_v2 Point
  1:    21.633527     8
  2:    76.713565     1
  3:    34.987461     7
  4:    87.131914     1
  5:    93.451401     1
 ---
196:    41.318597     7
197:    34.751585     7
198:    62.515336     1
199:     6.758128     9
200:    53.015376     1
</code>```

I would instead approach this by subsetting the data, and assigning by each subset. You could do this by specifying each subset df[Placement_v2 <= 1], df[Placement_v2 >= 1 & Placement_v2 <= 10], etc. But, if you do it in the correct order, you can avoid the double equality evaluation.

```<code>df[, Point := 1]
df[Placement_v2 <= 50, Point := 7]
df[Placement_v2 <= 25, Point := 8]
df[Placement_v2 <= 10, Point := 9]
df[Placement_v2 <=  1, Point := 10]
</code>```

Which gives the same result:

```<code>     Placement_v2 Point
  1:    21.633527     8
  2:    76.713565     1
  3:    34.987461     7
  4:    87.131914     1
  5:    93.451401     1
 ---
196:    41.318597     7
197:    34.751585     7
198:    62.515336     1
199:     6.758128     9
200:    53.015376     1
</code>```

Body:
I'm trying to simplify the following multiple ifelse code using sapply or lapply (still can't distinguish them).

My goal is to allocate points based on placement like shown below.

df$Point <- ifelse(df$Placement_v2 <= 1, 10,
ifelse(df$Placement_v2 <= 10, 9,
ifelse(df$Placement_v2 <= 25, 8,
ifelse(df$Placement_v2 <= 50, 7, 1) )))

This code works okay, but I want to make a dataframe and simply my code above using sapply or lapply (or anyother function).

I've tried this code but is not working as expected. Only the rows with placement 1 get 10 points and other rows end up with 1.

<2nd code>

df$Point <- sapply(df2$Placement, function(x) ifelse(df$Placement_v2 <= x, df2$Point[df2$Placement == x], 1 ) )

How can I solve this problem?

Body:
A few ways to go about this. I'll use data.table.

library(data.table)

set.seed(123)
df <- data.table(Placement_v2 = runif(200, -10, 100))

First option, move the evaluation out to a function, and then lapply the function to your Placement_v2 column. This has the benefit of being much cleaner than your nested ifelse statements.

funky <- function(x) {

  if (x <= 1) {
    val <- 10
  } else if (x <= 10){
    val <- 9
  } else if (x <= 25){
    val <- 8
  } else if (x <= 50){
    val <- 7
  } else {
    val <- 1
  }

  return(val)

}

df[, Point := unlist(lapply(Placement_v2, funky))]

Result:

     Placement_v2 Point
  1:    21.633527     8
  2:    76.713565     1
  3:    34.987461     7
  4:    87.131914     1
  5:    93.451401     1
 ---
196:    41.318597     7
197:    34.751585     7
198:    62.515336     1
199:     6.758128     9
200:    53.015376     1

I would instead approach this by subsetting the data, and assigning by each subset. You could do this by specifying each subset df[Placement_v2 <= 1], df[Placement_v2 >= 1 & Placement_v2 <= 10], etc. But, if you do it in the correct order, you can avoid the double equality evaluation.

df[, Point := 1]
df[Placement_v2 <= 50, Point := 7]
df[Placement_v2 <= 25, Point := 8]
df[Placement_v2 <= 10, Point := 9]
df[Placement_v2 <=  1, Point := 10]

Which gives the same result:

     Placement_v2 Point
  1:    21.633527     8
  2:    76.713565     1
  3:    34.987461     7
  4:    87.131914     1
  5:    93.451401     1
 ---
196:    41.318597     7
197:    34.751585     7
198:    62.515336     1
199:     6.758128     9
200:    53.015376     1


问:
Opencart - Instant update quantity in cart
For standard opencart behavior, after adding the product in cart, user needs to click to update button manually for quantity update. For sample, please refer to http://demo.opencart.com/. However, I would like to change to when I change the quantity, the cart info can be refreshed immediately. I've tried following code but it doesn't work:

For catalog/view/theme/default/template/checkout/cart.tpl, I updated:

button type="submit" data-toggle="tooltip" title="" class="btn btn-primary">
  i class="fa fa-refresh">/button>

(don't know why I cannot paste the code properly on the above line. I've removed some < to make it show)

to

```<code><button type="button" data-toggle="tooltip" title="<?php echo $button_update; ?>" class="btn btn-primary" onchange="cart.update('<?php echo $product['key']; ?>', '<?php echo $product['quantity']; ?>');"><i class="fa fa-refresh"></i></button>
</code>```

In catalog/view/javascript/common.js

There is a function

```<code>var cart = {
  //skip some lines for other function
    'update': function(key, quantity) {
        $.ajax({
            url: 'index.php?route=checkout/cart/edit',
            type: 'post',
            data: 'key=' + key + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
            dataType: 'json',
            beforeSend: function() {
                $('#cart > button').button('loading');
            },
            complete: function() {
                $('#cart > button').button('reset');
            },
            success: function(json) {
                // Need to set timeout otherwise it wont update the total
                setTimeout(function () {
                    $('#cart > button').html('<img src="image/catalog/content/cart/quote-icon.png" alt="quote"><span class="badge badge-giftu rounded-x">' + json['totallines'] + '</span>');
                }, 100);

                if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
                    $('#cart > ul').load('index.php?route=common/cart/info ul li');
                } else {
                    $('#cart > ul').load('index.php?route=common/cart/info ul li');
                }
            }
        });
    },
}
</code>```

I tried if I change to cart.remove under the on.change function, it works. However, it doesn't work for cart.udpate. Is there anyone know what is the issue of triggering the ajax update issue?

答:
I myself had such a problem solved it like this

Old code (i have custom them):

```<code><input type="text" name="quantity[<?php echo $product['key']; ?>]" value="<?php echo $product['quantity']; ?>" size="1" class="form-control"/>
<span class="input-group-btn">
<button type="submit" data-toggle="tooltip" title="<?php echo $button_update; ?>" class="btn btn-primary"><i class="fa fa-refresh"></i></button>
<button type="button" data-toggle="tooltip" title="<?php echo $button_remove; ?>" class="btn btn-danger"
        onclick="cart.remove('<?php echo $product['key']; ?>');"><i class="fa fa-times-circle"></i></button>
</code>```

New Code (fixed) look on input and Remove(button type="button" If he also does not work)

```<code><input type="text" name="quantity[<?php echo $product['cart_id']; ?>]" value="<?php echo $product['quantity']; ?>"
       size="1" class="form-control"/>
<span class="input-group-btn">
    <button type="submit" data-toggle="tooltip" title="<?php echo $button_update; ?>"
            class="btn btn-primary"><i class="fa fa-refresh"></i></button>
    <button type="button" data-toggle="tooltip" title="<?php echo $button_remove; ?>" class="btn btn-danger"
            onclick="cart.remove('<?php echo $product['cart_id']; ?>');"><i class="fa fa-times-circle"></i></button>
</code>```

There was a problem that incorrectly gave the notation for the fields it was necessary to put the key in the cart_id

Body:
For standard opencart behavior, after adding the product in cart, user needs to click to update button manually for quantity update. For sample, please refer to http://demo.opencart.com/. However, I would like to change to when I change the quantity, the cart info can be refreshed immediately. I've tried following code but it doesn't work:

For catalog/view/theme/default/template/checkout/cart.tpl, I updated:

button type="submit" data-toggle="tooltip" title="" class="btn btn-primary">
  i class="fa fa-refresh">/button>

(don't know why I cannot paste the code properly on the above line. I've removed some < to make it show)

to

<button type="button" data-toggle="tooltip" title="<?php echo $button_update; ?>" class="btn btn-primary" onchange="cart.update('<?php echo $product['key']; ?>', '<?php echo $product['quantity']; ?>');"></button>

In catalog/view/javascript/common.js

There is a function

var cart = {
  //skip some lines for other function
    'update': function(key, quantity) {
        $.ajax({
            url: 'index.php?route=checkout/cart/edit',
            type: 'post',
            data: 'key=' + key + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
            dataType: 'json',
            beforeSend: function() {
                $('#cart > button').button('loading');
            },
            complete: function() {
                $('#cart > button').button('reset');
            },
            success: function(json) {
                // Need to set timeout otherwise it wont update the total
                setTimeout(function () {
                    $('#cart > button').html('' + json['totallines'] + '');
                }, 100);

                if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
                    $('#cart > ul').load('index.php?route=common/cart/info ul li');
                } else {
                    $('#cart > ul').load('index.php?route=common/cart/info ul li');
                }
            }
        });
    },
}

I tried if I change to cart.remove under the on.change function, it works. However, it doesn't work for cart.udpate. Is there anyone know what is the issue of triggering the ajax update issue?

Body:
I myself had such a problem solved it like this

Old code (i have custom them):

<input type="text" name="quantity[<?php echo $product['key']; ?>]" value="<?php echo $product['quantity']; ?>" size="1" class="form-control"/>
<span class="input-group-btn">
<button type="submit" data-toggle="tooltip" title="<?php echo $button_update; ?>" class="btn btn-primary"><i class="fa fa-refresh"></i></button>
<button type="button" data-toggle="tooltip" title="<?php echo $button_remove; ?>" class="btn btn-danger"
        onclick="cart.remove('<?php echo $product['key']; ?>');"><i class="fa fa-times-circle"></i></button>

New Code (fixed) look on input and Remove(button type="button" If he also does not work)

<input type="text" name="quantity[<?php echo $product['cart_id']; ?>]" value="<?php echo $product['quantity']; ?>"
       size="1" class="form-control"/>
<span class="input-group-btn">
    <button type="submit" data-toggle="tooltip" title="<?php echo $button_update; ?>"
            class="btn btn-primary"><i class="fa fa-refresh"></i></button>
    <button type="button" data-toggle="tooltip" title="<?php echo $button_remove; ?>" class="btn btn-danger"
            onclick="cart.remove('<?php echo $product['cart_id']; ?>');"><i class="fa fa-times-circle"></i></button>

There was a problem that incorrectly gave the notation for the fields it was necessary to put the key in the cart_id


问:
Converting from vector<string> to wchar_t**
```<code>std::vector<std::string> elems = split(command, ' ');
const int argc = elems.size();
wchar_t** argv = new wchar_t*[argc]();
//wchar_t* argv[10];
for (int i = 0; i < argc; i++) {
    const char* arg = elems[i].c_str();
    int size = strlen(arg);
    size_t length = 0;
    wchar_t* e = new wchar_t[size];
    mbstowcs_s(&length, e, size + 1, arg, size);
    argv[i] = e;
}
</code>```

This is my code attempting to convert a vector of strings to a wchar_t**. When I comment out the third line and uncomment the fourth line, it works. But I want my wchar_t** to persist, so I want to use the third line and not the fourth. Please explain to me why the third line does not work as expected.

答: You're allocating new wchar_t[size] but copying size + 1 characters into it. That's undefined behavior.

Body:
std::vector<std::string> elems = split(command, ' ');
const int argc = elems.size();
wchar_t** argv = new wchar_t*[argc]();
//wchar_t* argv[10];
for (int i = 0; i < argc; i++) {
    const char* arg = elems[i].c_str();
    int size = strlen(arg);
    size_t length = 0;
    wchar_t* e = new wchar_t[size];
    mbstowcs_s(&length, e, size + 1, arg, size);
    argv[i] = e;
}

This is my code attempting to convert a vector of strings to a wchar_t**. When I comment out the third line and uncomment the fourth line, it works. But I want my wchar_t** to persist, so I want to use the third line and not the fourth. Please explain to me why the third line does not work as expected.


问:
PHPUnit can't find path, extra folders added by PhpStorm
I'm running phpunit and it gives me an error

```<code>PHP Fatal error:  Class 'MyApp\MyBundle\Tests\Units\Classes\Action\ActionTestCase' not found in /var/www/src/tests/src/MyApp/MyBundle/Classes/Action/KeywordTest.php on line 7
</code>```

In that class is

```<code>5 use MyApp\MyBundle\Tests\Units\Classes\Action\ActionTestCase as TestCase;
6
7 class KeywordTest extends TestCase {
</code>```

The thing I can't understand is, ActionTestCase exists, but at MyApp\MyBundle\Classes\Action\ActionTestCase

When I use the autocomplete function of PhpStorm, it uses the path with the \Tests\Units part. That is the only path it finds, and if I double click in there it directs to the correct class. And yet PHPUnit doesn't find it.

Where is this extra path being added? In PhpStorm or Composer or somewhere else?

The composer.json file includes this

```<code>"autoload": {
    "psr-0": {
        "": "src/"
    }
}
,
"autoload-dev": {
    "psr-4": {
        "": "src/tests"
    }
},
</code>```

The phpunit.xml file includes this

```<code><phpunit bootstrap="app/autoload.php">
</code>```

答:
Moving tests out of src sounds like a good suggestion (regarding Jakub Zalas comment), you can better say if that is an option for you or not.

Regardless of that, the dev autoloader is not correctly configured for that path:

```<code>"autoload-dev": {
    "psr-4": {
        "": "src/tests"
    }
},
</code>```

Would look for the file

```<code>src\tests\MyApp\MyBundle\Classes\Action\ActionTestCase.php
</code>```

but you have the file at

```<code>src\tests\src\MyApp\MyBundle\Classes\Action\ActionTestCase.php
          ^^^
</code>```

Adding the missing src/ part should make it working:

```<code>"autoload-dev": {
    "psr-4": {
        "": "src/tests/src/"
    }
},
</code>```

Don't forget to dump the autoload again:

```<code>composer dump-autoload
</code>```

after you change the composer.json.

Body:
I'm running phpunit and it gives me an error

PHP Fatal error:  Class 'MyApp\MyBundle\Tests\Units\Classes\Action\ActionTestCase' not found in /var/www/src/tests/src/MyApp/MyBundle/Classes/Action/KeywordTest.php on line 7

In that class is

5 use MyApp\MyBundle\Tests\Units\Classes\Action\ActionTestCase as TestCase;
6
7 class KeywordTest extends TestCase {

The thing I can't understand is, ActionTestCase exists, but at MyApp\MyBundle\Classes\Action\ActionTestCase

When I use the autocomplete function of PhpStorm, it uses the path with the \Tests\Units part. That is the only path it finds, and if I double click in there it directs to the correct class. And yet PHPUnit doesn't find it.

Where is this extra path being added? In PhpStorm or Composer or somewhere else?

The composer.json file includes this

"autoload": {
    "psr-0": {
        "": "src/"
    }
}
,
"autoload-dev": {
    "psr-4": {
        "": "src/tests"
    }
},

The phpunit.xml file includes this

<phpunit bootstrap="app/autoload.php">

Body:
Moving tests out of src sounds like a good suggestion (regarding Jakub Zalas comment), you can better say if that is an option for you or not.

Regardless of that, the dev autoloader is not correctly configured for that path:

"autoload-dev": {
    "psr-4": {
        "": "src/tests"
    }
},

Would look for the file

src\tests\MyApp\MyBundle\Classes\Action\ActionTestCase.php

but you have the file at

src\tests\src\MyApp\MyBundle\Classes\Action\ActionTestCase.php
          ^^^

Adding the missing src/ part should make it working:

"autoload-dev": {
    "psr-4": {
        "": "src/tests/src/"
    }
},

Don't forget to dump the autoload again:

composer dump-autoload

after you change the composer.json.


问:
Tell eclipse to reload environment variables
I'm setting an environment variable in a .bat file using set and setx which is executed by my java application.

But the next time I run my application the environment variables are back to their old values - I have to restart Eclipse for the changes to take effect.

How can I tell eclipse to reload environment variables each time I run my application?

答: You can exit and start your eclipse instead of restarting it.  It should just work fine then.</p>