问:
Angular 2 Inline template cannot read property of undefined
I am trying to render data inside a tab body section based on clicking an icon on a tabset. Here is a screen shot of my initial, successfully rendered view:

But when I click a new tabset icon to load data into the tab body section, I get the following exception:

```<code>TypeError: Cannot read property 'category' of undefined
at CompiledTemplate.proxyViewClass.View_DnDMiniCardGroupComponent0.detectChangesInternal (/PaletteSchemaModule/DnDMiniCardGroupComponent/component.ngfactory.js:144)
at CompiledTemplate.proxyViewClass.AppView.detectChanges (view.js:425)
at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (view.js:620)
at CompiledTemplate.proxyViewClass.AppView.internalDetectChanges (view.js:410)
at CompiledTemplate.proxyViewClass.View_TabCommunityComponent0.detectChangesInternal (/PaletteSchemaModule/TabCommunityComponent/component.ngfactory.js:89)
at CompiledTemplate.proxyViewClass.AppView.detectChanges (view.js:425)
at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (view.js:620)
at CompiledTemplate.proxyViewClass.AppView.internalDetectChanges (view.js:410)
at View_TypesContentComponent2.detectChangesInternal (/PaletteSchemaModule/TypesContentComponent/component.ngfactory.js:190)
at View_TypesContentComponent2.AppView.detectChanges (view.js:425)
at View_TypesContentComponent2.DebugAppView.detectChanges (view.js:620)
at ViewContainer.detectChangesInNestedViews (view_container.js:67)
at CompiledTemplate.proxyViewClass.View_TypesContentComponent0.detectChangesInternal (/PaletteSchemaModule/TypesContentComponent/component.ngfactory.js:592)
at CompiledTemplate.proxyViewClass.AppView.detectChanges (view.js:425)
at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (view.js:620)
</code>```

Here is a slice of my tabset template that shows tab content body based on ngSwitch and ngSwitchCase:

```<code><div class="schema-palette" [ngSwitch]="tabId">
    <myapp-base-palette *ngSwitchCase="'T'">
        <myapp-tabset [tabType]="'T'" (onTabSelected)="tabChanged($event)" palette-tabset></myapp-tabset>
        <myapp-tab-community palette-content-region></myapp-tab-community>
    </myapp-base-palette>
</div>
</code>```

Here is my myapp-tab-community component template:

```<code><div class="community-buffer" ngFor="let miniCardGrp of miniCardGrps; let i = index">
  <div style="height:5px" *ngIf="i === 0"></div>
  <myapp-dnd-mini-card-group [miniCardGrp]="miniCardGrp"></myapp-dnd-mini-card-group>
</div>
</code>```

Here is myapp-tab-community component typescript:

```<code>import { Component, OnInit, AfterViewInit } from '@angular/core';

import { PalettesService } from '../../palettes.service';
import { MiniCardGroup } from '../../palettes.helpers';
import { DnDMiniCardGroupComponent } from '../../shared/dnd-mini-card-group/dnd-mini-card-group.component';

@Component({
  selector: 'myapp-tab-community',
  templateUrl: './tab-community.component.html',
  styleUrls: ['./tab-community.component.scss'],
  providers: [PalettesService]
})
export class TabCommunityComponent implements OnInit, AfterViewInit {

  miniCardGrps: MiniCardGroup[];

  constructor(private palettesService: PalettesService) {}

  ngOnInit() {
    this.miniCardGrps = [];
    this.miniCardGrps = this.palettesService.getTemplateTypes();

    // DATA IS SUCCESSFULLY RETRIEVED
    console.log('TabCommunityComponent.ngOnInit = ' + JSON.stringify(this.miniCardGrps));
  }

  ngAfterViewInit() {
    // ERROR BLOCKS EVALUATION
    console.log('TabCommunityComponent.ngAfterViewInit = ' + JSON.stringify(this.miniCardGrps));
  }

  trackByMiniCardGroup(index: number, miniCardGrp: MiniCardGroup) {
    return miniCardGrp.category;
  }

}
</code>```

An array of myapp-dnd-mini-card-group components should be rendered but the error is thrown from its template.

The template file:

```<code><div class="mini-card-grp-collapse">
  <div class="mini-card-grp-collapse-row">
    <div class="mini-card-grp-title">
      <a data-toggle="collapse" [href]="href" aria-expanded="true" attr.aria-controls="{{ ariaControls }}">
        <!-- THIS LINE THROWS -->
        <md-icon class="white-text md-16">play_arrow</md-icon>{{ miniCardGrp.category }}
      </a>
    </div>
    <div class="mini-card-grp-title-helper">
      <md-icon class="white-text md-24">help_outline</md-icon>
    </div>
  </div>
</div>
<div class="collapse in" [id]="id">
  <div class="mini-card-wrapper" *ngFor="let miniCard of miniCardGrp.miniCards">
    <myapp-dnd-mini-card [miniCard]="miniCard"></myapp-dnd-mini-card>
  </div>
</div>
</code>```

Now the typescript file:

```<code>import { Component, OnInit, AfterViewInit, Input } from '@angular/core';

import { MathHelper } from '../../../../utils/math';
import { MiniCardGroup } from '../../palettes.helpers';

import { DndMiniCardComponent } from '../dnd-mini-card/dnd-mini-card.component';

@Component({
  selector: 'myapp-dnd-mini-card-group',
  templateUrl: './dnd-mini-card-group.component.html',
  styleUrls: ['./dnd-mini-card-group.component.scss']
})
export class DnDMiniCardGroupComponent implements OnInit, AfterViewInit
{

  @Input() miniCardGrp: MiniCardGroup;
  @Input() href: string;
  @Input() id: string;
  @Input() ariaControls: string;

  constructor() {
    let mathHelper = new MathHelper();
    let random$ = mathHelper.getRandomNumberString();
    this.id = random$;
    this.href = '#' + random$;
    this.ariaControls = random$;
  }

  ngOnInit() {
    // IS UNDEFINED
    console.log('DnDMiniCardGroupComponent.ngOnInit = ' + JSON.stringify(this.miniCardGrp));
  }

  ngAfterViewInit() {
    // IS NEVER REACHED
    console.log('DnDMiniCardGroupComponent.ngAfterViewInit = ' + JSON.stringify(this.miniCardGrp));
  }

}
</code>```

What am I doing wrong here?

As requested, here is what the mini-card-group component looks like:

```<code><div class="btn-grp-collapse">
  <div class="btn-grp-collapse-row">
    <div class="btn-grp-title">
      <a data-toggle="collapse" [href]="href" aria-expanded="true" attr.aria-controls="{{ ariaControls }}">
        <md-icon class="white-text md-16">play_arrow</md-icon>{{ dndButtonGrp.title }}
      </a>
    </div>
    <div class="btn-grp-title-helper">
      <md-icon class="white-text md-24">help_outline</md-icon>
    </div>
  </div>
</div>
<div class="collapse in" [id]="id">
  <div class="btn-wrapper" *ngFor="let dndButton of dndButtonGrp.dndButtons">
    <myapp-dnd-button [dndButton]="dndButton"></myapp-dnd-button>
  </div>
</div>
</code>```

Its typescript file:

```<code>import { Component, Input, OnInit } from '@angular/core';

import { MathHelper } from '../../../../utils/math'
import { DnDButtonGroup } from './dnd-button-group.helpers';

import { DndButtonComponent } from '../dnd-button/dnd-button.component';

@Component({
  selector: 'myapp-dnd-button-group',
  templateUrl: './dnd-button-group.component.html',
  styleUrls: ['./dnd-button-group.component.scss']
})
export class DnDButtonGroupComponent implements OnInit {

  @Input() dndButtonGrp: DnDButtonGroup;
  @Input() href: string;
  @Input() id: string;
  @Input() ariaControls: string;

  constructor() {
    let mathHelper = new MathHelper();
    let random$ = mathHelper.getRandomNumberString();
    this.id = random$;
    this.href = '#' + random$;
    this.ariaControls = random$;
  }

  ngOnInit() {}

}
</code>```

答:
When you call the service the data might not be arrived yet, you need to subscribe to the service to get the data</p>

```<code>ngOnInit() {
    this.palettesService
    .getTemplateTypes()
    .subscribe(data => this.miniCardGrps = data);
}
</code>```

Body:
I am trying to render data inside a tab body section based on clicking an icon on a tabset. Here is a screen shot of my initial, successfully rendered view:

But when I click a new tabset icon to load data into the tab body section, I get the following exception:

TypeError: Cannot read property 'category' of undefined
at CompiledTemplate.proxyViewClass.View_DnDMiniCardGroupComponent0.detectChangesInternal (/PaletteSchemaModule/DnDMiniCardGroupComponent/component.ngfactory.js:144)
at CompiledTemplate.proxyViewClass.AppView.detectChanges (view.js:425)
at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (view.js:620)
at CompiledTemplate.proxyViewClass.AppView.internalDetectChanges (view.js:410)
at CompiledTemplate.proxyViewClass.View_TabCommunityComponent0.detectChangesInternal (/PaletteSchemaModule/TabCommunityComponent/component.ngfactory.js:89)
at CompiledTemplate.proxyViewClass.AppView.detectChanges (view.js:425)
at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (view.js:620)
at CompiledTemplate.proxyViewClass.AppView.internalDetectChanges (view.js:410)
at View_TypesContentComponent2.detectChangesInternal (/PaletteSchemaModule/TypesContentComponent/component.ngfactory.js:190)
at View_TypesContentComponent2.AppView.detectChanges (view.js:425)
at View_TypesContentComponent2.DebugAppView.detectChanges (view.js:620)
at ViewContainer.detectChangesInNestedViews (view_container.js:67)
at CompiledTemplate.proxyViewClass.View_TypesContentComponent0.detectChangesInternal (/PaletteSchemaModule/TypesContentComponent/component.ngfactory.js:592)
at CompiledTemplate.proxyViewClass.AppView.detectChanges (view.js:425)
at CompiledTemplate.proxyViewClass.DebugAppView.detectChanges (view.js:620)

Here is a slice of my tabset template that shows tab content body based on ngSwitch and ngSwitchCase:

    <myapp-base-palette *ngSwitchCase="'T'">
        <myapp-tabset [tabType]="'T'" (onTabSelected)="tabChanged($event)" palette-tabset></myapp-tabset>
        <myapp-tab-community palette-content-region></myapp-tab-community>
    </myapp-base-palette>

Here is my myapp-tab-community component template:

  <myapp-dnd-mini-card-group [miniCardGrp]="miniCardGrp"></myapp-dnd-mini-card-group>

Here is myapp-tab-community component typescript:

import { Component, OnInit, AfterViewInit } from '@angular/core';

import { PalettesService } from '../../palettes.service';
import { MiniCardGroup } from '../../palettes.helpers';
import { DnDMiniCardGroupComponent } from '../../shared/dnd-mini-card-group/dnd-mini-card-group.component';

@Component({
  selector: 'myapp-tab-community',
  templateUrl: './tab-community.component.html',
  styleUrls: ['./tab-community.component.scss'],
  providers: [PalettesService]
})
export class TabCommunityComponent implements OnInit, AfterViewInit {

  miniCardGrps: MiniCardGroup[];

  constructor(private palettesService: PalettesService) {}

  ngOnInit() {
    this.miniCardGrps = [];
    this.miniCardGrps = this.palettesService.getTemplateTypes();

    // DATA IS SUCCESSFULLY RETRIEVED
    console.log('TabCommunityComponent.ngOnInit = ' + JSON.stringify(this.miniCardGrps));
  }

  ngAfterViewInit() {
    // ERROR BLOCKS EVALUATION
    console.log('TabCommunityComponent.ngAfterViewInit = ' + JSON.stringify(this.miniCardGrps));
  }

  trackByMiniCardGroup(index: number, miniCardGrp: MiniCardGroup) {
    return miniCardGrp.category;
  }

}

An array of myapp-dnd-mini-card-group components should be rendered but the error is thrown from its template.

The template file:

        <md-icon class="white-text md-16">play_arrow</md-icon>{{ miniCardGrp.category }}

      <md-icon class="white-text md-24">help_outline</md-icon>

    <myapp-dnd-mini-card [miniCard]="miniCard"></myapp-dnd-mini-card>

Now the typescript file:

import { Component, OnInit, AfterViewInit, Input } from '@angular/core';

import { MathHelper } from '../../../../utils/math';
import { MiniCardGroup } from '../../palettes.helpers';

import { DndMiniCardComponent } from '../dnd-mini-card/dnd-mini-card.component';

@Component({
  selector: 'myapp-dnd-mini-card-group',
  templateUrl: './dnd-mini-card-group.component.html',
  styleUrls: ['./dnd-mini-card-group.component.scss']
})
export class DnDMiniCardGroupComponent implements OnInit, AfterViewInit
{

  @Input() miniCardGrp: MiniCardGroup;
  @Input() href: string;
  @Input() id: string;
  @Input() ariaControls: string;

  constructor() {
    let mathHelper = new MathHelper();
    let random$ = mathHelper.getRandomNumberString();
    this.id = random$;
    this.href = '#' + random$;
    this.ariaControls = random$;
  }

  ngOnInit() {
    // IS UNDEFINED
    console.log('DnDMiniCardGroupComponent.ngOnInit = ' + JSON.stringify(this.miniCardGrp));
  }

  ngAfterViewInit() {
    // IS NEVER REACHED
    console.log('DnDMiniCardGroupComponent.ngAfterViewInit = ' + JSON.stringify(this.miniCardGrp));
  }

}

What am I doing wrong here?

As requested, here is what the mini-card-group component looks like:

        <md-icon class="white-text md-16">play_arrow</md-icon>{{ dndButtonGrp.title }}

      <md-icon class="white-text md-24">help_outline</md-icon>

    <myapp-dnd-button [dndButton]="dndButton"></myapp-dnd-button>

Its typescript file:

import { Component, Input, OnInit } from '@angular/core';

import { MathHelper } from '../../../../utils/math'
import { DnDButtonGroup } from './dnd-button-group.helpers';

import { DndButtonComponent } from '../dnd-button/dnd-button.component';

@Component({
  selector: 'myapp-dnd-button-group',
  templateUrl: './dnd-button-group.component.html',
  styleUrls: ['./dnd-button-group.component.scss']
})
export class DnDButtonGroupComponent implements OnInit {

  @Input() dndButtonGrp: DnDButtonGroup;
  @Input() href: string;
  @Input() id: string;
  @Input() ariaControls: string;

  constructor() {
    let mathHelper = new MathHelper();
    let random$ = mathHelper.getRandomNumberString();
    this.id = random$;
    this.href = '#' + random$;
    this.ariaControls = random$;
  }

  ngOnInit() {}

}

Body:
When you call the service the data might not be arrived yet, you need to subscribe to the service to get the data

ngOnInit() {
    this.palettesService
    .getTemplateTypes()
    .subscribe(data => this.miniCardGrps = data);
}


来源: stackexchange

问:
How to post dynamic created elements to database MVC c#
Good day, i have dynamically created form elements with jquery that looks like this:

```<code><label for="fname" class="fname_label col-sm-2 control-label">First Name</label>
<div class="col-sm-4">
    <input type="text" class="fname_input form-control" id="fname" placeholder="First Name" name="firstnames">
</div>

<label for="uemail" class="uemail_label col-sm-2 control-label">Email</label>
<div class="col-sm-4">
    <input type="text" class="uemail_input form-control" id="uemail" placeholder="Email" name="emailaddresses">
</code>```

A user can create multiple elements like this with same name and ids. I mean if a user should click on add more, the same elements are created with the same name and id with jquery. A user can create multiple elements say 10 or more. My question is how can i post or insert the values of the dynamically create elements to the database. i am using c# in MVC. Thank You.

答:
Had a bit of time and put this together.  I created a JavaScript namespace to hold my functions, data etc; kept the jQuery part separate for the event (submit and add rows) management.  You could easily add capability to delete new entry groups (row) as well, just need ONE to stay as I used .clone() to get that new row.

Sample markup using  some bootstrap stuff (not required for the functional part).  Note I used jQuery for the ajax stuff, you would not have to but it made the sample a bit smaller perhaps.

```<code><div class="container">
  <form id="myform">
    <div class="inputs-holder">
      <fieldset class="entry-group">
        <legend class="col-form-legend col-xm-2">
          one input
        </legend>
        <div class="form-group row">
          <label class="col-xs-2 col-form-label col-form-label-sm">Name</label>
          <div class="col-xs-7">
            <input required="true" class="form-control form-control-xs name-field" type="text" />
          </div>
        </div>
        <div class="form-group row">
          <label class="col-xs-2 col-form-label col-form-label-sm">Email</label>
          <div class="col-xs-7">
            <input required="true" class="form-control form-control-xs email-field" type="email" placeholder="enter email" value="testme@example.com" />
          </div>
        </div>
      </fieldset>
    </div>
    <div class="form-group row">
      <div class="offset-xs-2 col-xs-5">
        <button id="submitme" type="submit" class="btn btn-primary btn-xs">Submit Me</button>
      </div>
      <div class="offset-xs-2 col-xs-5">
        <button id="addnewgroup" type="button" class="btn btn-xs">Add new group</button>
      </div>
    </div>
  </form>
</div>
<div id="results">
  Entries
</div>
</code>```

Some script to process and push data via ajax to server:

```<code>/* Latest compiled and minified JavaScript included as External Resource */

var myApp = myApp || {};
myApp.arrayObj = {
  // some stuff clipped out not used here...
  // use to lookup duplicates
  lookup: function(myArray, searchTerm, property, firstOnly) {
    var found = [];
    var i = myArray.length;
    while (i--) {
      if (myArray[i][property] === searchTerm) {
        found.push(myArray[i]);
        if (firstOnly) break; //if only the first
      }
    }
    return found;
  },
  // could be used to validate duplicates for example
  lookupAll: function(myArray, property, searchTerm) {
    return this.lookup(myArray, searchTerm, property, false);
  }
};
myApp.data = {
  entries: [],
  saveUrl: "/Home/SaveEmails" this COULD be from server/MVC
};
myApp.func = {
  addEmailRow: function(myArray, item, allowdups, uniquekey) {
    // matches the  POCO object class names
    var entry = {
      "name": item.name,
      "email": item.email
    };
    if (allowdups || (!allowdups && !myApp.arrayObj.lookup(myArray, entry[uniquekey], uniquekey, true).length)) {
      myArray.push(entry);
    } else if (allowdups && myApp.arrayObj.lookup(myArray, entry[uniquekey], uniquekey, true).length) {
      myApp.data.entries[uniquekey] = item[uniquekey];
    } else if (allowdups && !myApp.arrayObj.lookup(myArray, entry[uniquekey], uniquekey, true).length) {
      myArray.push(entry);
    }
  },
  // just something to show what is entered/being submitted
  showEntries: function(list) {
    $.each(list, function(index, value) {
      $('#results').append("<div>" + value.name + " " + value.email + "</div>");
    });
  },
  // the important part
  saveEntries: function(list) {
    var entries = JSON.stringify({
      'Entries': list
    });

    $.ajax({
        contentType: 'application/json;',
        dataType: 'json',
        type: 'POST',
        url: myApp.data.saveUrl,
        data: entries
      }).done(function() {
        $('#results').html('"SaveEmails()" successfully called.');
      })
      .fail(function(response) {
        $('#results').html(response);
      });
  }
};
$(document).ready(function() {
  // add new "group" row
  $('#addnewgroup').on('click', function() {
    var holder = $('.inputs-holder');
    // clone that first row
    var newRow = holder.find('.entry-group').eq(0).clone();
    // clear any values entered and append it
    newRow.find('input').val("");
    newRow.appendTo(holder);
  });
  // a bit verbose for clarity here
  $('#myform').on('submit', function(e) {
    e.preventDefault();
    e.stopPropagation();
    // clear entries
    myApp.data.entries = [];
    var allowdups = false,
      uniquekey = "name";
    var holder = $('.inputs-holder');
    // get entries
    holder.find('.entry-group').each(function() {
      var email = $(this).find('.email-field').val();
      var name = $(this).find('.name-field').val();
      var item = {
        "email": email,
        "name": name
      };
      myApp.func.addEmailRow(myApp.data.entries, item, allowdups, uniquekey);
    });
    $('#results').html("<div>Results:</div>");
    myApp.func.showEntries(myApp.data.entries);
    myApp.func.saveEntries(myApp.data.entries);

    // supress default submit form
    return false;
  });
});
</code>```

Now the server side:

```<code>/* MVC for this: */
// POCO object: - reference this whereever you put it.
public class EmailEntry
{
    public String name { get; set; }
    public String email { get; set; }
}

// controller/ method: used IEnumerable instead of List as simpler
public class HomeController : Controller
{
   [HttpPost]
    public void SaveEmails(IEnumerable<EmailEntry> entries)
    {
        // do stuff with email entries here...validate/save for example
    }
}
</code>```

ALL this is untested and my contain small errors but I believe it to be pretty bug free.

ContentLicense: CC BY-SA 3.0

Body:
Good day, i have dynamically created form elements with jquery that looks like this:

First Name

    <input type="text" class="fname_input form-control" id="fname" placeholder="First Name" name="firstnames">

Email

    <input type="text" class="uemail_input form-control" id="uemail" placeholder="Email" name="emailaddresses">

A user can create multiple elements like this with same name and ids. I mean if a user should click on add more, the same elements are created with the same name and id with jquery. A user can create multiple elements say 10 or more. My question is how can i post or insert the values of the dynamically create elements to the database. i am using c# in MVC. Thank You.

Body:
Had a bit of time and put this together.  I created a JavaScript namespace to hold my functions, data etc; kept the jQuery part separate for the event (submit and add rows) management.  You could easily add capability to delete new entry groups (row) as well, just need ONE to stay as I used .clone() to get that new row.

Sample markup using  some bootstrap stuff (not required for the functional part).  Note I used jQuery for the ajax stuff, you would not have to but it made the sample a bit smaller perhaps.

<div class="container">
  <form id="myform">
    <div class="inputs-holder">
      <fieldset class="entry-group">
        <legend class="col-form-legend col-xm-2">
          one input
        </legend>
        <div class="form-group row">
          <label class="col-xs-2 col-form-label col-form-label-sm">Name</label>
          <div class="col-xs-7">
            <input required="true" class="form-control form-control-xs name-field" type="text" />
          </div>
        </div>
        <div class="form-group row">
          <label class="col-xs-2 col-form-label col-form-label-sm">Email</label>
          <div class="col-xs-7">
            <input required="true" class="form-control form-control-xs email-field" type="email" placeholder="enter email" value="testme@example.com" />
          </div>
        </div>
      </fieldset>
    </div>
    <div class="form-group row">
      <div class="offset-xs-2 col-xs-5">
        <button id="submitme" type="submit" class="btn btn-primary btn-xs">Submit Me</button>
      </div>
      <div class="offset-xs-2 col-xs-5">
        <button id="addnewgroup" type="button" class="btn btn-xs">Add new group</button>
      </div>
    </div>
  </form>
</div>
<div id="results">
  Entries
</div>

Some script to process and push data via ajax to server:

/* Latest compiled and minified JavaScript included as External Resource */

var myApp = myApp || {};
myApp.arrayObj = {
  // some stuff clipped out not used here...
  // use to lookup duplicates
  lookup: function(myArray, searchTerm, property, firstOnly) {
    var found = [];
    var i = myArray.length;
    while (i--) {
      if (myArray[i][property] === searchTerm) {
        found.push(myArray[i]);
        if (firstOnly) break; //if only the first
      }
    }
    return found;
  },
  // could be used to validate duplicates for example
  lookupAll: function(myArray, property, searchTerm) {
    return this.lookup(myArray, searchTerm, property, false);
  }
};
myApp.data = {
  entries: [],
  saveUrl: "/Home/SaveEmails" this COULD be from server/MVC
};
myApp.func = {
  addEmailRow: function(myArray, item, allowdups, uniquekey) {
    // matches the  POCO object class names
    var entry = {
      "name": item.name,
      "email": item.email
    };
    if (allowdups || (!allowdups && !myApp.arrayObj.lookup(myArray, entry[uniquekey], uniquekey, true).length)) {
      myArray.push(entry);
    } else if (allowdups && myApp.arrayObj.lookup(myArray, entry[uniquekey], uniquekey, true).length) {
      myApp.data.entries[uniquekey] = item[uniquekey];
    } else if (allowdups && !myApp.arrayObj.lookup(myArray, entry[uniquekey], uniquekey, true).length) {
      myArray.push(entry);
    }
  },
  // just something to show what is entered/being submitted
  showEntries: function(list) {
    $.each(list, function(index, value) {
      $('#results').append("<div>" + value.name + " " + value.email + "</div>");
    });
  },
  // the important part
  saveEntries: function(list) {
    var entries = JSON.stringify({
      'Entries': list
    });

    $.ajax({
        contentType: 'application/json;',
        dataType: 'json',
        type: 'POST',
        url: myApp.data.saveUrl,
        data: entries
      }).done(function() {
        $('#results').html('"SaveEmails()" successfully called.');
      })
      .fail(function(response) {
        $('#results').html(response);
      });
  }
};
$(document).ready(function() {
  // add new "group" row
  $('#addnewgroup').on('click', function() {
    var holder = $('.inputs-holder');
    // clone that first row
    var newRow = holder.find('.entry-group').eq(0).clone();
    // clear any values entered and append it
    newRow.find('input').val("");
    newRow.appendTo(holder);
  });
  // a bit verbose for clarity here
  $('#myform').on('submit', function(e) {
    e.preventDefault();
    e.stopPropagation();
    // clear entries
    myApp.data.entries = [];
    var allowdups = false,
      uniquekey = "name";
    var holder = $('.inputs-holder');
    // get entries
    holder.find('.entry-group').each(function() {
      var email = $(this).find('.email-field').val();
      var name = $(this).find('.name-field').val();
      var item = {
        "email": email,
        "name": name
      };
      myApp.func.addEmailRow(myApp.data.entries, item, allowdups, uniquekey);
    });
    $('#results').html("<div>Results:</div>");
    myApp.func.showEntries(myApp.data.entries);
    myApp.func.saveEntries(myApp.data.entries);

    // supress default submit form
    return false;
  });
});

Now the server side:

/* MVC for this: */
// POCO object: - reference this whereever you put it.
public class EmailEntry
{
    public String name { get; set; }
    public String email { get; set; }
}

// controller/ method: used IEnumerable instead of List as simpler
public class HomeController : Controller
{
   [HttpPost]
    public void SaveEmails(IEnumerable<EmailEntry> entries)
    {
        // do stuff with email entries here...validate/save for example
    }
}

ALL this is untested and my contain small errors but I believe it to be pretty bug free.


问:
java: how to get Timezone abbreviation (from offset)?
My code like belows, I am using android. I found different devices may have different result.

Using different phone: I can get : "EST" or "GMT-05:00".

However, I just want to get abbreviation(just like "EST").

How can I get the abbreviation (or change offset to abbreviation)?

```<code>   String timezone =Calendar.getInstance().getTimeZone().getDisplayName(false, TimeZone.SHORT);
</code>```

答:
If anyone else need the solution : I just tweak the code and get desired short name, which i needed to display to user. </p>

```<code>private static String getTimeZoneShortName() {

    String tz = TimeZone.getDefault().getDisplayName();

    String[] stz = tz.split(" ");

    StringBuilder sName = new StringBuilder();

    for (int i = 0; i < stz.length; i++) {
        sName.append(stz[i].charAt(0));
    }
    return sName.toString();
}
</code>```

Body:
My code like belows, I am using android. I found different devices may have different result.

Using different phone: I can get : "EST" or "GMT-05:00".

However, I just want to get abbreviation(just like "EST").

How can I get the abbreviation (or change offset to abbreviation)?

   String timezone =Calendar.getInstance().getTimeZone().getDisplayName(false, TimeZone.SHORT);

Body:
If anyone else need the solution : I just tweak the code and get desired short name, which i needed to display to user.

private static String getTimeZoneShortName() {

    String tz = TimeZone.getDefault().getDisplayName();

    String[] stz = tz.split(" ");

    StringBuilder sName = new StringBuilder();

    for (int i = 0; i < stz.length; i++) {
        sName.append(stz[i].charAt(0));
    }
    return sName.toString();
}


问:
data.frame with a column containing a matrix in R
I'm trying to put some matrices in a dataframe in R, something like :

```<code>m <- matrix(c(1,2,3,4), nrow=2, ncol=2)
df <- data.frame(id=1, mat=m)
</code>```

But when I do that, I get a dataframe with 2 rows and 3 columns instead of a dataframe with 1 row and 2 columns.

Reading the documentation, I have to escape my matrix using I().

```<code>df <- data.frame(id=1, mat=I(m))

str(df)
'data.frame':   2 obs. of  2 variables:
 $ id : num  1 1
 $ mat: AsIs [1:2, 1:2] 1 2 3 4
</code>```

As I understand it, the dataframe contains one row for each row of the matrix, and the mat field is a list of matrix column values.

Thus, how can I obtain a dataframe containing matrices ?

Thanks !

答:
I came across the same problem trying to understand the gasoline data in pls package. Used $ for the job.
First, lets create a matrix, lets call it spectra_mat, then a vector called response_var1.

```<code>spectra_mat = matrix(1:45, 9, 5)
response_var1 = seq(1:9)
</code>```

Now we put the vector response_var1 in a new data frame - lets call it df.

```<code>df = data.frame(response_var1)
df$spectra = spectra_mat
</code>```

To check,

```<code>str(df)

'data.frame':   9 obs. of  2 variables:
 $ response_var1: int  1 2 3 4 5 6 7 8 9
 $ spectra      : int [1:9, 1:5] 1 2 3 4 5 6 7 8 9 10 ...
</code>```

Body:
I'm trying to put some matrices in a dataframe in R, something like :

m <- matrix(c(1,2,3,4), nrow=2, ncol=2)
df <- data.frame(id=1, mat=m)

But when I do that, I get a dataframe with 2 rows and 3 columns instead of a dataframe with 1 row and 2 columns.

Reading the documentation, I have to escape my matrix using I().

df <- data.frame(id=1, mat=I(m))

str(df)
'data.frame':   2 obs. of  2 variables:
 $ id : num  1 1
 $ mat: AsIs [1:2, 1:2] 1 2 3 4

As I understand it, the dataframe contains one row for each row of the matrix, and the mat field is a list of matrix column values.

Thus, how can I obtain a dataframe containing matrices ?

Thanks !

Body:
I came across the same problem trying to understand the gasoline data in pls package. Used $ for the job.
First, lets create a matrix, lets call it spectra_mat, then a vector called response_var1.

spectra_mat = matrix(1:45, 9, 5)
response_var1 = seq(1:9)

Now we put the vector response_var1 in a new data frame - lets call it df.

df = data.frame(response_var1)
df$spectra = spectra_mat

To check,

str(df)

'data.frame':   9 obs. of  2 variables:
 $ response_var1: int  1 2 3 4 5 6 7 8 9
 $ spectra      : int [1:9, 1:5] 1 2 3 4 5 6 7 8 9 10 ...


问:
How to block and inform threads
I have a List object in my class and two methods which are used to add and remove items from the list.

There are multiple threads trying to access the list.

I want to ensure that only one thread is updating the list at an instance.

If a list is empty and a thread wants to remove an item then I want to make the thread wait till there is an item in the list.

When an item is inserted in the list
then I want to inform other threads
which are waiting to access the list
that the list is not empty anymore
and they can remove the items (using events).

What is the best mechanism to achieve this goal?

答: Maybe you want .NET 4.0's BlockingCollection.</p>

ContentLicense: CC BY-SA 2.5

Title: How to block and inform threads


问:
$scope.watch being called too many times
I thought I had this problem solved but it turns out I didn't so any offers of help would be much appreciated.

Basically, I'm having trouble with my controllers and scopes which is causing my $scope.$watch() to be called when I don't want it to.

I have an Angular view (html) with a dropdown and pagination tag using different controllers and views.

First, I have this: (where form_item_Division.html is simply a dropdown of Divisions)

```<code><div class="panel panel-primary panel-shad-1" ng-controller="DashboardIEPItemDraftCtrl">
        <div ng-include="'views/partials/form_item_Division.html'"></div>
        <div ng-include="'app/dashboard/iep.html'" ng-controller="DashboardIEPItemDraftCtrl"></div>
</div>
</code>```

My iep.html looks like this:

```<code><div ng-controller="DashboardIEPItemDraftCtrl">
<div ng-include="'app/dashboard/iepitem_table1.html'" ng-if="numberOfItemsByUserDivision > 0"></div>

        <div class="col-xs-12 text-center" ng-show="totalNumberPages > 1">
            <pagination items-per-page="itemsPerPage"
                    total-items="numberOfItemsByUserDivision"
                    ng-model="currentPage"
                    max-size="3"
                    boundary-links="true"
                    rotate="false"
                    class="pagination-sm panel-shad-1"
                    num-pages="totalNumberPages"
                    previous-text="‹"
                    next-text="›"
                    first-text="«"
                    last-text="»">
            </pagination>
        </div>
</div>
</code>```

My iepitem_table1.html defines the table layout and is under a different controller.  It looks like this:

```<code><table class="table table-condensed table-striped table-hover" ng-controller="IEPItemTableCtrl">

   (table layout defined here)

</table>
</code>```

The relevant part of my script is shown below:

```<code>$scope.getItemsBySelectedDivision = function (selectedDivisionId) {
   blah.get({ count: true, filter: 'DivisionPerformingId eq ' +
   selectedDivisionId }).$promise.then(
      function (response) {
         $scope.itemsByUserDivision.length = 0;
         $scope.itemsByUserDivision = response.value;
         $scope.numberOfItemsByUserDivision = response.value.length;
         $scope.totalNumberPages = Math.ceil(response.value.length /
         $scope.itemsPerPage);
         var pagedData = $scope.itemsByUserDivision.slice(0,
         $scope.itemsPerPage);
         $scope.itemsByUserDivision = pagedData;
      },
      function (error) {
          // Do something when it errors
      });
        };

$scope.$watch("currentPage", function () {
   if ($scope.itemsByUserDivision != null) {
     $scope.itemsByUserDivision = originalItems;
     var pagedData = $scope.itemsByUserDivision.slice(($scope.currentPage -
     1) * $scope.itemsPerPage, $scope.currentPage * $scope.itemsPerPage);
     $scope.itemsByUserDivision = pagedData;
 }
 });
</code>```

When I select a Division from the dropdown and scroll through the pages with the pagination tag everything is fine.  However, when I scroll through the pages of a division that has more than one page and then go back and select another Division the results shown are not correct.  I think this is because my $scope.$watch() is being called when I don't want it to.  I think I don't have my controllers arranged properly for this scenario.  At any rate, any help is much appreciated.

Thanks,

Pete

答:
You can compare for change in variable you are watching,</p>

```<code>    $scope.$watch("currentPage", function (oldVal,newVal) {
        if(newVal!==oldVal){
               if ($scope.itemsByUserDivision != null) {
               $scope.itemsByUserDivision = originalItems;
               var pagedData =$scope.itemsByUserDivision.slice(($scope.currentPage -
         1) * $scope.itemsPerPage, $scope.currentPage *  $scope.itemsPerPage);
         $scope.itemsByUserDivision = pagedData;
     }
   }
     });
</code>```

Body:
I thought I had this problem solved but it turns out I didn't so any offers of help would be much appreciated.

Basically, I'm having trouble with my controllers and scopes which is causing my $scope.$watch() to be called when I don't want it to.

I have an Angular view (html) with a dropdown and pagination tag using different controllers and views.

First, I have this: (where form_item_Division.html is simply a dropdown of Divisions)

My iep.html looks like this:

 0">

 1">
            <pagination items-per-page="itemsPerPage"
                    total-items="numberOfItemsByUserDivision"
                    ng-model="currentPage"
                    max-size="3"
                    boundary-links="true"
                    rotate="false"
                    class="pagination-sm panel-shad-1"
                    num-pages="totalNumberPages"
                    previous-text="‹"
                    next-text="›"
                    first-text="«"
                    last-text="»">
            </pagination>

My iepitem_table1.html defines the table layout and is under a different controller.  It looks like this:

   (table layout defined here)

The relevant part of my script is shown below:

$scope.getItemsBySelectedDivision = function (selectedDivisionId) {
   blah.get({ count: true, filter: 'DivisionPerformingId eq ' +
   selectedDivisionId }).$promise.then(
      function (response) {
         $scope.itemsByUserDivision.length = 0;
         $scope.itemsByUserDivision = response.value;
         $scope.numberOfItemsByUserDivision = response.value.length;
         $scope.totalNumberPages = Math.ceil(response.value.length /
         $scope.itemsPerPage);
         var pagedData = $scope.itemsByUserDivision.slice(0,
         $scope.itemsPerPage);
         $scope.itemsByUserDivision = pagedData;
      },
      function (error) {
          // Do something when it errors
      });
        };

$scope.$watch("currentPage", function () {
   if ($scope.itemsByUserDivision != null) {
     $scope.itemsByUserDivision = originalItems;
     var pagedData = $scope.itemsByUserDivision.slice(($scope.currentPage -
     1) * $scope.itemsPerPage, $scope.currentPage * $scope.itemsPerPage);
     $scope.itemsByUserDivision = pagedData;
 }
 });

When I select a Division from the dropdown and scroll through the pages with the pagination tag everything is fine.  However, when I scroll through the pages of a division that has more than one page and then go back and select another Division the results shown are not correct.  I think this is because my $scope.$watch() is being called when I don't want it to.  I think I don't have my controllers arranged properly for this scenario.  At any rate, any help is much appreciated.

Thanks,

Pete

Body:
You can compare for change in variable you are watching,

    $scope.$watch("currentPage", function (oldVal,newVal) {
        if(newVal!==oldVal){
               if ($scope.itemsByUserDivision != null) {
               $scope.itemsByUserDivision = originalItems;
               var pagedData =$scope.itemsByUserDivision.slice(($scope.currentPage -
         1) * $scope.itemsPerPage, $scope.currentPage *  $scope.itemsPerPage);
         $scope.itemsByUserDivision = pagedData;
     }
   }
     });


问:
Pandas: count some value in all columns
I have a dataframe

```<code>graph   0       1       2       3       4
1       blue    blue    blue    blue    blue
2       blue    blue    blue    blue    blue
3       blue    red     blue    blue    red
4       red     blue    red     red     blue
5       red     red     blue    red     red
6       blue    blue    blue    blue    blue
</code>```

I need to get the count of the value 'blue' of every string/line.

The desired output:

```<code>graph   result
1       5
2       5
3       3
4       2
5       1
6       5
</code>```

I try to do it with

```<code>(df['0', '1', '2', '3', '4']).applymap(lambda x: str.count(x, 'blue'))
</code>```

But it returns

```<code>KeyError: ('0', '1', '2', '3', '4')
</code>```

答:
```<code>In [35]: df.set_index('graph').eq('blue').sum(1).reset_index(name='result')
Out[35]:
   graph  result
0      1       5
1      2       5
2      3       3
3      4       2
4      5       1
5      6       5
</code>```

Title: Pandas: count some value in all columns

Body:
I have a dataframe

graph   0       1       2       3       4
1       blue    blue    blue    blue    blue
2       blue    blue    blue    blue    blue
3       blue    red     blue    blue    red
4       red     blue    red     red     blue
5       red     red     blue    red     red
6       blue    blue    blue    blue    blue

I need to get the count of the value 'blue' of every string/line.

The desired output:

graph   result
1       5
2       5
3       3
4       2
5       1
6       5

I try to do it with

(df['0', '1', '2', '3', '4']).applymap(lambda x: str.count(x, 'blue'))

But it returns

KeyError: ('0', '1', '2', '3', '4')


问:
How to get a list of packages from one machine and install in another with Chocolatey?
Calling clist -l gives me a list of packages with versions:

```<code>7zip.install 16.04
ccleaner 5.28.6005
ConEmu 17.3.16.0
...
</code>```

How do I get this list without version information?

My intention is to use this output to call choco install 7zip.install ccleaner ConEmu ... on another machine. An alternative answer could be how to use the output of clist directly into cinst.

答:
If you have a look at the help information for the choco install command (you can do this using choco install -h, you will find the following usage:

```<code>cinst <pkg|packages.config> [<pkg2> <pkgN>] [<options/switches>]
</code>```

As you will see, it is possible to pass a packages.config file, which would contain all the packages that you want to install. The format of this packages.config file is very simple and looks like the following:

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="calibre" version="2.81.0" />
  <package id="chocolatey" version="0.10.3" />
  <package id="chocolatey.extension" version="1.9.6" />
  <package id="chocolatey-core.extension" version="1.1.0" />
</packages>
</code>```

Once you have this file, installing all the packages again on another machine is a simple one line command.

A simple way to generate this packages.config file would be to install ChocolateyGUI (choco install chocolateygui), which includes an option to export the currently installed list of applications.

ContentLicense: CC BY-SA 4.0

Body:
Calling clist -l gives me a list of packages with versions:

7zip.install 16.04
ccleaner 5.28.6005
ConEmu 17.3.16.0
...

How do I get this list without version information?

My intention is to use this output to call choco install 7zip.install ccleaner ConEmu ... on another machine. An alternative answer could be how to use the output of clist directly into cinst.

Body:
If you have a look at the help information for the choco install command (you can do this using choco install -h, you will find the following usage:

cinst <pkg|packages.config> [<pkg2> <pkgN>] [<options/switches>]

As you will see, it is possible to pass a packages.config file, which would contain all the packages that you want to install. The format of this packages.config file is very simple and looks like the following:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="calibre" version="2.81.0" />
  <package id="chocolatey" version="0.10.3" />
  <package id="chocolatey.extension" version="1.9.6" />
  <package id="chocolatey-core.extension" version="1.1.0" />
</packages>

Once you have this file, installing all the packages again on another machine is a simple one line command.

A simple way to generate this packages.config file would be to install ChocolateyGUI (choco install chocolateygui), which includes an option to export the currently installed list of applications.


问:
Matching string regular expression
I would like to match data from strings like the following:

24.Legacy.S01E08.720p.HDTV.x264-AVS[rarbg]

Colony.S02E09.720p.HDTV.x264-FLEET[rarbg]

24.Legacy (everything before S01E08)

S => 01

E => 08

720p.HDTV.x264 (everything between S01E08 and -)

AVS (everything between - en [)

rarbg (everything between [])

The following test almost works but needs some tweaks:

```<code>preg_match_all(
    '/(.*?).S([0-9]+)E([0-9]+).(.*?)(.*?)[(.*?)]/s',
    $download,
    $posts,
    PREG_SET_ORDER
);
</code>```

答:
You should not need the /s modifier, it extends . to match meta chars and line breaks.
I would recommend to use the /e modifier to also allow lower case 's01e14'
Don't forget to escape the regex chars like . and [ with \. and \[

```<code>//         NAME  SEASON   EPISOE   MEDIUM  OPTIONS
$regex = '/(.+)\.S([0-9]+)E([0-9]+)\.(.+)\[(.+)\]/i';
preg_match_all(
    $regex,
    $download,
    $posts,
    PREG_SET_ORDER
);
</code>```

Test with '24.Legacy.S01E08.720p.HDTV.x264-AVS[rarbg]'

```<code>Array
(
    [0] => 24.Legacy.S01E08.720p.HDTV.x264-AVS[rarbg]
    [1] => 24.Legacy
    [2] => 01
    [3] => 08
    [4] => 720p.HDTV.x264-AVS
    [5] => rarbg
)
</code>```

Title: Matching string regular expression

Body:
I would like to match data from strings like the following:

24.Legacy.S01E08.720p.HDTV.x264-AVS[rarbg]

Colony.S02E09.720p.HDTV.x264-FLEET[rarbg]

24.Legacy (everything before S01E08)

S => 01

E => 08

720p.HDTV.x264 (everything between S01E08 and -)

AVS (everything between - en [)

rarbg (everything between [])

The following test almost works but needs some tweaks:

preg_match_all(
    '/(.*?).S([0-9]+)E([0-9]+).(.*?)(.*?)[(.*?)]/s',
    $download,
    $posts,
    PREG_SET_ORDER
);

Body:
You should not need the /s modifier, it extends . to match meta chars and line breaks.
I would recommend to use the /e modifier to also allow lower case 's01e14'
Don't forget to escape the regex chars like . and [ with \. and \[

//         NAME  SEASON   EPISOE   MEDIUM  OPTIONS
$regex = '/(.+)\.S([0-9]+)E([0-9]+)\.(.+)\[(.+)\]/i';
preg_match_all(
    $regex,
    $download,
    $posts,
    PREG_SET_ORDER
);

Test with '24.Legacy.S01E08.720p.HDTV.x264-AVS[rarbg]'

Array
(
    [0] => 24.Legacy.S01E08.720p.HDTV.x264-AVS[rarbg]
    [1] => 24.Legacy
    [2] => 01
    [3] => 08
    [4] => 720p.HDTV.x264-AVS
    [5] => rarbg
)


问:
How to set up GoCD to handle private git repositories that use SSH keys for authentication?
I have a git repository that authenticates users with SSH keys and I want to use that repo as a GoCD material. GoCD gives me this error:

```<code>Error performing command: --- Command ---
git ls-remote ssh://git@server/repo.git refs/heads/master
--- Environment ---
{GIT_ALLOW_PROTOCOL=http:https:ssh:git:file:rsync}
--- INPUT ----

--OUTPUT ---

--- ERROR ---
STDERR: Host key verification failed.
STDERR: fatal: Could not read from remote repository.
STDERR:
STDERR: Please make sure you have the correct access rights
STDERR: and the repository exists.
---
</code>```

Is there any way I can add the SSH key to GoCD?

答:
At the time of writing this answer, it's not possible to manage SSH keys in GoCD directly. To make it work you have to generate SSH keys for a GoCD server and all agents and then add them to the server that's hosting the git repository. You can also copy an existing key to the server & nodes but that's obviously not recommended.

For example, with standard GoCD server installation you should have the "go" user in your system:

```<code>$ grep GoCD /etc/passwd
go:x:998:998:GoCD User:/var/go:/bin/bash
</code>```

sudo as a "go" user and create the key

```<code>$ sudo su - go
$ ssh-keygen
...
$ ssh [server]
The authenticity of host '[server] ([1.3.3.7])' can't be established.
ECDSA key fingerprint is SHA256:Rxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[server]' (ECDSA) to the list of known hosts.
Permission denied (publickey,keyboard-interactive).
</code>```

The last step is important because if you don't make it, GoCD will give you the same error.

Now add your key to the git server and click "Check connection" in GoCD. It should print "Connection OK.".

Generate keys for each node and user that runs an agent.

Body:
I have a git repository that authenticates users with SSH keys and I want to use that repo as a GoCD material. GoCD gives me this error:

Error performing command: --- Command ---
git ls-remote ssh://git@server/repo.git refs/heads/master
--- Environment ---
{GIT_ALLOW_PROTOCOL=http:https:ssh:git:file:rsync}
--- INPUT ----

--OUTPUT ---

--- ERROR ---
STDERR: Host key verification failed.
STDERR: fatal: Could not read from remote repository.
STDERR:
STDERR: Please make sure you have the correct access rights
STDERR: and the repository exists.
---

Is there any way I can add the SSH key to GoCD?

Body:
At the time of writing this answer, it's not possible to manage SSH keys in GoCD directly. To make it work you have to generate SSH keys for a GoCD server and all agents and then add them to the server that's hosting the git repository. You can also copy an existing key to the server & nodes but that's obviously not recommended.

For example, with standard GoCD server installation you should have the "go" user in your system:

$ grep GoCD /etc/passwd
go:x:998:998:GoCD User:/var/go:/bin/bash

sudo as a "go" user and create the key

$ sudo su - go
$ ssh-keygen
...
$ ssh [server]
The authenticity of host '[server] ([1.3.3.7])' can't be established.
ECDSA key fingerprint is SHA256:Rxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[server]' (ECDSA) to the list of known hosts.
Permission denied (publickey,keyboard-interactive).

The last step is important because if you don't make it, GoCD will give you the same error.

Now add your key to the git server and click "Check connection" in GoCD. It should print "Connection OK.".

Generate keys for each node and user that runs an agent.


问:
Syntax error: Illegal return statement in JavaScript
I am getting a really weird JavaScript error when I run this code:

```<code><script type = 'text/javascript'>
var ask = confirm('".$message."');
if (ask == false)
{
    return false;
}

else
{
    return true;
}
</script>
</code>```

In the JavaScript console it says:

Syntax Error: Illegal return statement

It occurs at return true; and return false;

(I am echoing this javascript from a php function; the $message variable is one of the php parameters)

What is wrong with my code?

答:
where are you trying to return the value?
to console in dev tools is better for debugging</p>

```<code><script type = 'text/javascript'>
var ask = confirm('".$message."');
function answer(){
  if(ask==false){
    return false;
  } else {
    return true;
  }
}
console.log("ask : ", ask);
console.log("answer : ", answer());
</script>
</code>```

Body:
I am getting a really weird JavaScript error when I run this code:

In the JavaScript console it says:

Syntax Error: Illegal return statement

It occurs at return true; and return false;

(I am echoing this javascript from a php function; the $message variable is one of the php parameters)

What is wrong with my code?

Body:
where are you trying to return the value?
to console in dev tools is better for debugging

<script type = 'text/javascript'>
var ask = confirm('".$message."');
function answer(){
  if(ask==false){
    return false;
  } else {
    return true;
  }
}
console.log("ask : ", ask);
console.log("answer : ", answer());
</script>


问:
High Volume, High Speed Textbox in .Net
I am writing an application that will display serial/USB data at a rate of up to 250kb/sec. I am using the .net SerialPort class and reacting to the DataReceived event. For early implementations of this software, I simply stored the incoming data in a WinForms RichTextBox. This solution works fine until there are 50k - 100k lines in the control, at which point the application bogs down. Since then, I've tried accomplishing my goals with WPF and found the same problem. I tried, at one point, to keep only the currently visible text in the textbox, and store the rest in a large List<string> but this solution required a huge number of workarounds and, in the end, was abandoned - I'd rather not reinvent the wheel.

Now I come to you for a thread of hope - I am willing to try anything! Should I use a custom control (both pay and free controls are welcome)? SQLite? Virtualization as described above? Should I try polling the SerialPort instead of reacting to events?

答:
Use a thread to read the data and write it directly to a file.  Have your app refresh the last x number of lines from the file every so often.  Maybe even have the refresh based off of a notification from the reader thread?

By using multiple threads you'll keep the UI responsive and by writing straight to a file you'll ensure you've collected all of the data.  Also, it will allow you to pause the display long enough to actually copy/paste the data you want while continuing to capture data.

Possibly you could implement your own type of file reader that would allow the user to "scroll" through the file by only loading the parts you can actually display on screen at one time.

Title: High Volume, High Speed Textbox in .Net


问:
Chart js disable popup
I want to implement some text in middle of the Doughnut chart at Charts.js
The first step is 5to draw some text on the chart canvas.

When i move my cursor to red bar chartjs draw some tooltip(Red:300) on the canvas and deletes my text as a result.

How can i avoid all the canvas redraws by the chartjs after the initial chart is drawn?

答:
For chart.js v2, the new way to do it is to pass an empty events array to the options.

your options:

```<code>let chartOptions = {
    responsive: true,
    events: [],
    ...
};
</code>```

http://www.chartjs.org/docs/#chart-configuration-common-chart-configuration

Title: Chart js disable popup

Body:
For chart.js v2, the new way to do it is to pass an empty events array to the options.

your options:

let chartOptions = {
    responsive: true,
    events: [],
    ...
};

http://www.chartjs.org/docs/#chart-configuration-common-chart-configuration


问:
Directly using a list saved in an auxiliary file
Is there a way to save a list in an auxiliary file and then manipulate it directly, without having to download it, manipulate it, and then rewriting the file?

Namely, I would like to be able to do e.g. something like this:

```<code>L = open('file')
L.append(0)
L.close()
</code>```

What is the correct way to do it? Is there a specific class for it?

I solved the problem using shelve (a pickle-based library) as follows:

```<code>import shelve

f = shelve.open('list.db',writeback=True)
f['0'] = the list I want
L = f['0']

Manipulate L however I want

f.close()
</code>```

答:
If you put data in a file and you want to make modifications, any operation that changes the length of the data requires you to read and write back out the remainder of the file. (You can modify parts of the file in place if the length remains exactly the same, and you can append at the end or truncate from the end.)

So if you're looking for a way to keep your dataset in a file instead of loading it into memory, a plain file is not going to cut it. Neither is a pickled list, since it would have to be read in and written back out in its entirety. If that is your goal, I recommend using a database such as sqlite3, which does exactly what you want: It stores your data in a file, and takes care of the modifications for you.

```<code>import sqlite3
conn = sqlite3.connect('file.db')
c = conn.cursor()
c.execute("INSERT INTO mytable VALUES ('a', 'b', 'c')")
...
</code>```

Check out the sqlite documentation for the details on how to use it.

If your data doesn't have much structure, you may prefer dbm, which is a "key store" database for managing key-value pairs:

```<code>with dbm.open('file.dbm', 'c') as db:   # Open db, creating if necessary
    db['hello'] = 'Hello, world!'
</code>```

Body:
Is there a way to save a list in an auxiliary file and then manipulate it directly, without having to download it, manipulate it, and then rewriting the file?

Namely, I would like to be able to do e.g. something like this:

L = open('file')
L.append(0)
L.close()

What is the correct way to do it? Is there a specific class for it?

I solved the problem using shelve (a pickle-based library) as follows:

import shelve

f = shelve.open('list.db',writeback=True)
f['0'] = the list I want
L = f['0']

Manipulate L however I want

f.close()

Body:
If you put data in a file and you want to make modifications, any operation that changes the length of the data requires you to read and write back out the remainder of the file. (You can modify parts of the file in place if the length remains exactly the same, and you can append at the end or truncate from the end.)

So if you're looking for a way to keep your dataset in a file instead of loading it into memory, a plain file is not going to cut it. Neither is a pickled list, since it would have to be read in and written back out in its entirety. If that is your goal, I recommend using a database such as sqlite3, which does exactly what you want: It stores your data in a file, and takes care of the modifications for you.

import sqlite3
conn = sqlite3.connect('file.db')
c = conn.cursor()
c.execute("INSERT INTO mytable VALUES ('a', 'b', 'c')")
...

Check out the sqlite documentation for the details on how to use it.

If your data doesn't have much structure, you may prefer dbm, which is a "key store" database for managing key-value pairs:

with dbm.open('file.dbm', 'c') as db:   # Open db, creating if necessary
    db['hello'] = 'Hello, world!'


问:
Passing values List as parameter a function
Im working on a Java class by using reflection, I have a list of different type of objects:

```<code>public List<Object> MethodSignatureObjects
</code>```

and, I need to invoke a method by using the folowing logic:

```<code>   Class<?> c = Class.forName("class name");
   Method  method = c.getDeclaredMethod ("method name", parameterTypes)
   method.invoke (objectToInvokeOn, params)
</code>```

Is there any way to put the objects contained on MethodSignatureObjects on getDeclaredMethod, I mean, something like this:

```<code>Method  method = c.getDeclaredMethod (methodName, param1.class, param2.class, ..);
</code>```

where parameters1 , parameters2, parameter n.... come from   MethodSignatureObjects

I really appreaciate any advise.

Thank you so much.

答:
You cant pass a list but an array to the method</p>

```<code>// List<Object> methodSignatureObjects

int size = methodSignatureObjects.size();
Class<?>[] asArray = new Class<?>[size];
for ( int i = 0; i < size; i++ ) {
    asArray[i] = methodSignatureObjects.get(i).getClass();
}

Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod("method name", asArray);
method.invoke (objectToInvokeOn, params)
</code>```

Body:
Im working on a Java class by using reflection, I have a list of different type of objects:

public List<Object> MethodSignatureObjects

and, I need to invoke a method by using the folowing logic:

   Class<?> c = Class.forName("class name");
   Method  method = c.getDeclaredMethod ("method name", parameterTypes)
   method.invoke (objectToInvokeOn, params)

Is there any way to put the objects contained on MethodSignatureObjects on getDeclaredMethod, I mean, something like this:

Method  method = c.getDeclaredMethod (methodName, param1.class, param2.class, ..);

where parameters1 , parameters2, parameter n.... come from   MethodSignatureObjects

I really appreaciate any advise.

Thank you so much.

Body:
You cant pass a list but an array to the method

// List<Object> methodSignatureObjects

int size = methodSignatureObjects.size();
Class<?>[] asArray = new Class<?>[size];
for ( int i = 0; i < size; i++ ) {
    asArray[i] = methodSignatureObjects.get(i).getClass();
}

Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod("method name", asArray);
method.invoke (objectToInvokeOn, params)


问:
Web2py: IntegrityError('NOT NULL constraint failed:post.message
I thought I had escaped/ solved this error. But now am stuck. My db.py code:

```<code>Post = db.define_table('post',
                       Field('message', 'text', requires=IS_NOT_EMPTY(), notnull=False),
                       Field('answers', 'text', requires=IS_NOT_EMPTY(), notnull=False),
                       auth.signature
       )
Post.is_active.readable=False
Post.is_active.writeable=False
</code>```

controller:

@auth.requires_login()

```<code>def index():
    db.post.answers.writable=False
    db.post.answers.readable=False
    form = SQLFORM(post, formstyle='divs')
    if form.process().accepted:
        pass
    messages = db(post).select(orderby=~post.created_on)
    .......code
    #after several codes in now need to post a message to answers field, WITHOUT using a form in the view page
    db.post.insert(answers=report)
</code>```

In my view:

```<code>{{for msg in messages:}}
code
{{=msg.message}}
{{report from answers field}}
</code>```

My issue is that i keep getting the error:  IntegrityError('NOT NULL constraint failed:post.message

How do I solve this error?
Kind regards

答:
If the database table was originally created with notnull=True, later changing the model to notnull=False will have no effect, as removing the NOT NULL constraint requires an external tool (the DAL cannot remove such constraints).

As you suggest in your comment, you can instead set the default value for the field to something like an empty string, but if you do in fact want to allow null values, you should instead use a database administration tool to remove the constraint from the database schema.

Body:
I thought I had escaped/ solved this error. But now am stuck. My db.py code:

Post = db.define_table('post',
                       Field('message', 'text', requires=IS_NOT_EMPTY(), notnull=False),
                       Field('answers', 'text', requires=IS_NOT_EMPTY(), notnull=False),
                       auth.signature
       )
Post.is_active.readable=False
Post.is_active.writeable=False

controller:

@auth.requires_login()

def index():
    db.post.answers.writable=False
    db.post.answers.readable=False
    form = SQLFORM(post, formstyle='divs')
    if form.process().accepted:
        pass
    messages = db(post).select(orderby=~post.created_on)
    .......code
    #after several codes in now need to post a message to answers field, WITHOUT using a form in the view page
    db.post.insert(answers=report)

In my view:

{{for msg in messages:}}
code
{{=msg.message}}
{{report from answers field}}

My issue is that i keep getting the error:  IntegrityError('NOT NULL constraint failed:post.message

How do I solve this error?
Kind regards


问:
Call a method from multiple thread to populate a data structure and then read that data structure from a single background thread?
I have a class in which my add method is being called by multiple threads to populate clientidToTimestampHolder LinkedBlockingQueue. And then in the same below class, I have a background thread which runs every 30 milliseconds and calls a processData() method which drains clientidToTimestampHolder to List of Map and then I iterate that List to send data to different service by calling appropriate method.

I can get same userid many times with different timestamp so that is why I am using LinkedBlockingQueue with map.

```<code>public class Handler {
  private final ScheduledExecutorService executorService = Executors
      .newSingleThreadScheduledExecutor();
  private final LinkedBlockingQueue<Map.Entry<String, Long>> clientidToTimestampHolder =
      new LinkedBlockingQueue<>();

  private static class Holder {
    private static final Handler INSTANCE = new Handler();
  }

  public static Handler getInstance() {
    return Holder.INSTANCE;
  }

  private Handler() {
    executorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        processData();
      }
    }, 0, 30, TimeUnit.MILLISECONDS);
  }

  // called by multiple threads to populate clientidToTimestampHolder map
  public void add(final String clientid, final Long timestamp) {
    clientidToTimestampHolder.offer(Maps.immutableEntry(clientid, timestamp));
  }

  // called by single background thread every 30 milliseconds
  public void processData() {
    final List<Map.Entry<String, Long>> entries = new ArrayList<>();
    clientidToTimestampHolder.drainTo(entries);
    for (Map.Entry<String, Long> entry : entries) {
      String clientid = entry.getKey();
      long timestamp = entry.getValue();
      boolean isUpdated = isUpdatedClient(clientid, timestamp);
      if (!isUpdated) {
        updateClient(String.valueOf(clientid));
      }
    }
  }
}
</code>```

Is my above code thread safe and there is no race condition and I won't miss any data in processData() method? Since add method will be called from multiple threads and then I have a single background thread which runs every 30 milliseconds to calls processData() method which extracts data from clientidToTimestampHolder LinkedBlockingQueue.

答:
Anonymous classes contain a this reference to the outside class (i.e. Handler). You've unsafely published the this reference before the final field freeze, the threads of the executor may not see the collection properly initialized when it is read.

Other than that, I don't see how processData will miss any updates. If the drain operation does not catch a concurrent write, it will not be on the next run. Unless you are worried about this (in which case, you will need to lock), it looks fine to me as long as you do not also modify the collection.

On a side note, what is the purpose of String#valueOf on a string?

Body:
I have a class in which my add method is being called by multiple threads to populate clientidToTimestampHolder LinkedBlockingQueue. And then in the same below class, I have a background thread which runs every 30 milliseconds and calls a processData() method which drains clientidToTimestampHolder to List of Map and then I iterate that List to send data to different service by calling appropriate method.

I can get same userid many times with different timestamp so that is why I am using LinkedBlockingQueue with map.

public class Handler {
  private final ScheduledExecutorService executorService = Executors
      .newSingleThreadScheduledExecutor();
  private final LinkedBlockingQueue<Map.Entry<String, Long>> clientidToTimestampHolder =
      new LinkedBlockingQueue<>();

  private static class Holder {
    private static final Handler INSTANCE = new Handler();
  }

  public static Handler getInstance() {
    return Holder.INSTANCE;
  }

  private Handler() {
    executorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        processData();
      }
    }, 0, 30, TimeUnit.MILLISECONDS);
  }

  // called by multiple threads to populate clientidToTimestampHolder map
  public void add(final String clientid, final Long timestamp) {
    clientidToTimestampHolder.offer(Maps.immutableEntry(clientid, timestamp));
  }

  // called by single background thread every 30 milliseconds
  public void processData() {
    final List<Map.Entry<String, Long>> entries = new ArrayList<>();
    clientidToTimestampHolder.drainTo(entries);
    for (Map.Entry<String, Long> entry : entries) {
      String clientid = entry.getKey();
      long timestamp = entry.getValue();
      boolean isUpdated = isUpdatedClient(clientid, timestamp);
      if (!isUpdated) {
        updateClient(String.valueOf(clientid));
      }
    }
  }
}

Is my above code thread safe and there is no race condition and I won't miss any data in processData() method? Since add method will be called from multiple threads and then I have a single background thread which runs every 30 milliseconds to calls processData() method which extracts data from clientidToTimestampHolder LinkedBlockingQueue.


问:
Dynamic angular.js orderby button ng-click
Here is the code:

```<code><button ng-init="propriety: 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'"></button>
<div ng-repeat="item in items | orderBy: propriety">
  <li>item.name - item.price</li>
</div>
</code>```

What am i missing?

Edit 1:
Changed to ng-click, still not working.

Edit 2:
Added ng-init.

Edit 3:
Fixed missing double quotation mark. Still not working.

答:
Change

From

```<code><button ng-init="propriety: 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'></button>
</code>```

To

```<code><button ng-init="propriety: 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'"></button>
</code>```

Body:
Here is the code:

<button ng-init="propriety: 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'"></button>

item.name - item.price

What am i missing?

Edit 1:
Changed to ng-click, still not working.

Edit 2:
Added ng-init.

Edit 3:
Fixed missing double quotation mark. Still not working.

Body:
Change

From

<button ng-init="propriety: 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'></button>

To

<button ng-init="propriety: 'name'" ng-click="propriety == 'name' ? propriety = 'price' : propriety = 'name'"></button>


问:
How To prevent user from entering anything other than positive numbers in TextBox
I am developing a UWP app where i need to make sure that the user couldn't enter anything except Positive integers with a max length of 8 characters followed by a decimal and two more digits.
The Examples could be

```<code>12345.50,
123456.50,
123.23
</code>```

I have to implement these on a TextBox. I would like to make sure that the Shift key cant be used on the keyboard and the numbers have to be entered from the Numeric keyboard(both)

I wrote this code , but its accepting special characters and shift key.

Lets assume that there is only one mode of input and that is via only the keyboard

```<code> private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            if ((!char.IsControl(Convert.ToChar(e.Key)) && !char.IsDigit(Convert.ToChar(e.Key)) &&
      (Convert.ToChar(e.Key) != '.')))
            {
                e.Handled = true;
            }
        }
</code>```

答:
Your assumption is jot a real-world scenario. You cannot prevent the user from entering data other than by keyboard: speech, ink, IMEs, autosuggest, etc. will all enter text in your TextBox without going through the KeyDown event.

The only way to ensure the TextBox gets only your valid format is after the only is received: in TextChanging, TextChanged, LostFocus, submit-button input, etc.

Since hit acceptance requirement is self-contained TextChanging is probably the best place: make sure the text is allowed and remove and characters which are invalid. Be careful not to be so restrictive that the user can't get to valid input: don't reject a "." that isn't followed by two digits before the user can enter those digits.

An other option (much better if two fields depend on each other) is to let the user make invalid input but tell them: leave the bad input, but mark it invalid and don't accept the form until it has been fixed.

Also take a look at the TextBoxMask property in the UWP Community Toolkit at http://docs.uwpcommunitytoolkit.com/en/master/controls/TextBoxMask/

Body:
I am developing a UWP app where i need to make sure that the user couldn't enter anything except Positive integers with a max length of 8 characters followed by a decimal and two more digits.
The Examples could be

12345.50,
123456.50,
123.23

I have to implement these on a TextBox. I would like to make sure that the Shift key cant be used on the keyboard and the numbers have to be entered from the Numeric keyboard(both)

I wrote this code , but its accepting special characters and shift key.

Lets assume that there is only one mode of input and that is via only the keyboard

 private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            if ((!char.IsControl(Convert.ToChar(e.Key)) && !char.IsDigit(Convert.ToChar(e.Key)) &&
      (Convert.ToChar(e.Key) != '.')))
            {
                e.Handled = true;
            }
        }


问:
Readonly field syntactic shortcut
As we know the code:

```<code>using(myDisposable)
{
}
</code>```

is equivalent of

```<code>try
{
   //do something with myDisposable
}
finally
{
  IDisposable disposable = myDisposable as IDisposable;
  if(disposable != null)
  {
    disposable.Dispose();
  }
}
</code>```

and

```<code>lock(_locker)
{
}
</code>```

is equivalent of

```<code>Monitor.Enter(_locker);
try
{

}
finally
{

  Monitor.Exit(_locker);
}
</code>```

What is the equivalent of readonly field?

```<code>readonly object _data = new object();
</code>```

答:
There isn't one; that is, you can't express a readonly field except with the readonly keyword.

The readonly keyword is a signal to the compiler that the field may only be modified inside the class's constructor.

Title: Readonly field syntactic shortcut

Body:
As we know the code:

using(myDisposable)
{
}

is equivalent of

try
{
   //do something with myDisposable
}
finally
{
  IDisposable disposable = myDisposable as IDisposable;
  if(disposable != null)
  {
    disposable.Dispose();
  }
}

and

lock(_locker)
{
}

is equivalent of

Monitor.Enter(_locker);
try
{

}
finally
{

  Monitor.Exit(_locker);
}

What is the equivalent of readonly field?

readonly object _data = new object();


问:
How to use variables in for loop statements in javascript?
So I'm trying to get this to roll an amount of dice equal to the specified input. To achieve this, I'm using a for loop, however it's not working.
As I just started coding recently, I have no idea why. Could someone please help?</p>

```<code><!DOCTYPE html>
<html>
<body>

<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>

<p id="display"></p>

<script>
var random = [];
document.getElementById("display").innerHTML = random;
a = document.getElementById("diceamount").innerHTML;

function FirstFunction() {
for (i=0; i<"a"; i++) {
    x = Math.floor(Math.random() * 4) + 1;
    random.push(x);
    document.getElementById("display").innerHTML = random;
    }
}
</script>

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

答:
This is not how you define "a".

This is how you do it:

```<code>for (i=0; i<a; i++) {
</code>```

This is how you get the value from the text field:

```<code>var b = document.getElementById('textbox_id').value;
</code>```

Then get the integer value:

```<code>var a = parseInt(b);
</code>```

And then the for loop:

```<code>for (i=0; i<a; i++) {
</code>```

Body:
So I'm trying to get this to roll an amount of dice equal to the specified input. To achieve this, I'm using a for loop, however it's not working.
As I just started coding recently, I have no idea why. Could someone please help?

<!DOCTYPE html>

<input type="number" id="diceamount" value="1">
<button onclick="FirstFunction()">Roll!</button>

Body:
This is not how you define "a".

This is how you do it:

for (i=0; i<a; i++) {

This is how you get the value from the text field:

var b = document.getElementById('textbox_id').value;

Then get the integer value:

var a = parseInt(b);

And then the for loop:

for (i=0; i<a; i++) {


问:
An array passed to a function gives nan elements (C++)
I have a function that takes in an array and defines a new array made up of a subset of the original array.

```<code>#include<iostream>
#include<cmath>
using namespace std;
double * subarray(double *array){
       double *sub= new double[100];
       for (int i=0; i<10; i++){
         sub[i]=array[i];
       }
    return sub;
}
int main(){
  double *x=new double[100];
  double *y=new double[10];

  for(int j=0; j<100; j++){
     x[j]=sin(j*3.14/2.0);
  }
  y=subarray(x);
  for(int k=0; k<10; k++){
     cout<<y[k]<<endl;
  }
return 0;
}
</code>```

When I run this code some of the elements of the sub array come out as nan.

答:
calling subarray is creating a new double[100] then passing that back out. But it's a completely separate array to y = new double[10]. Whenever you call "new" it's making a new thing, separate to all other "new" things. y gets the address of the "new double[100]" but it loses track of the address of the "new double[10]" you made in main, which is a memory leak. If you're going to return a pointer to an new'ly allocated item, start the pointer that's going to store it as a nullptr, and call "delete" or "delete []" when you're done, depending on whether it was a "new[]" thing or just "new".

```<code>#include<iostream>
#include<cmath>
using namespace std;
double * subarray(double *array) {
    double *sub = new double[10]; // don't allocated more than you want to use
    for (int i = 0; i < 10; i++) {
        sub[i] = array[i];
    }
    return sub;
}
int main() {
    double *x = new double[100];
    double *y = nullptr; // don't set this if you're going to overwrite it

    for (int j = 0; j < 100; j++) {
        x[j] = sin(j*3.14 / 2.0);
    }
    y = subarray(x);
    for (int k = 0; k < 10; k++) {
        cout << y[k] << endl;
    }

    delete [] x; // if you make new things, delete them afterwards
    delete [] y;

    std::cin.get();
    return 0;
}
</code>```

I don't get any NaNs when I run this, but you are allocating a lot of memory that never gets set, inside the function. You're allocating 100 spaces but only writing to 10. This isn't necessarily an error, but it's not efficient.

Body:
I have a function that takes in an array and defines a new array made up of a subset of the original array.

#include<iostream>
#include<cmath>
using namespace std;
double * subarray(double *array){
       double *sub= new double[100];
       for (int i=0; i<10; i++){
         sub[i]=array[i];
       }
    return sub;
}
int main(){
  double *x=new double[100];
  double *y=new double[10];

  for(int j=0; j<100; j++){
     x[j]=sin(j*3.14/2.0);
  }
  y=subarray(x);
  for(int k=0; k<10; k++){
     cout<<y[k]<<endl;
  }
return 0;
}

When I run this code some of the elements of the sub array come out as nan.

Body:
calling subarray is creating a new double[100] then passing that back out. But it's a completely separate array to y = new double[10]. Whenever you call "new" it's making a new thing, separate to all other "new" things. y gets the address of the "new double[100]" but it loses track of the address of the "new double[10]" you made in main, which is a memory leak. If you're going to return a pointer to an new'ly allocated item, start the pointer that's going to store it as a nullptr, and call "delete" or "delete []" when you're done, depending on whether it was a "new[]" thing or just "new".

#include<iostream>
#include<cmath>
using namespace std;
double * subarray(double *array) {
    double *sub = new double[10]; // don't allocated more than you want to use
    for (int i = 0; i < 10; i++) {
        sub[i] = array[i];
    }
    return sub;
}
int main() {
    double *x = new double[100];
    double *y = nullptr; // don't set this if you're going to overwrite it

    for (int j = 0; j < 100; j++) {
        x[j] = sin(j*3.14 / 2.0);
    }
    y = subarray(x);
    for (int k = 0; k < 10; k++) {
        cout << y[k] << endl;
    }

    delete [] x; // if you make new things, delete them afterwards
    delete [] y;

    std::cin.get();
    return 0;
}

I don't get any NaNs when I run this, but you are allocating a lot of memory that never gets set, inside the function. You're allocating 100 spaces but only writing to 10. This isn't necessarily an error, but it's not efficient.


问:
Need help in understanding how this particular Constraint Layout works
I was going through a Udacity course on Android development and found this example of Constraintlayout (though I have shown only a part of the xml code and screen shot here). I have a hard time understanding how this is working.

xml layout file snippet:

```<code>        <ImageView
        android:id="@+id/tableHeaderImage"
        android:background="@color/colorPrimaryLight"
        android:layout_height="24dp"
        android:layout_width="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="32dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintTop_toBottomOf="@+id/textViewDepartureTime"
        app:layout_constraintHorizontal_bias="0.33" />

    <!-- COMPLETED (12) Create an ImageView for the blue table's body -->
    <ImageView
        android:id="@+id/tableImage"
        android:background="@color/colorPrimary"
        android:layout_height="0dp"
        android:layout_width="0dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintBottom_toBottomOf="@+id/textViewTerminal"/>

    <!-- COMPLETED (13) Create a TextView for each of the labels and text fields in the blue table -->
    <TextView
        android:id="@+id/textViewTerminalLabel"
        android:text="@string/terminal_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Caption"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintLeft_toLeftOf="@+id/textViewTerminal"
        app:layout_constraintRight_toRightOf="@+id/textViewTerminal"

        app:layout_constraintTop_toTopOf="@+id/tableHeaderImage" />

    <TextView
        android:id="@+id/textViewGateLabel"
        android:text="@string/gate_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Caption"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintLeft_toLeftOf="@+id/textViewGate"
        app:layout_constraintRight_toRightOf="@+id/textViewGate"
        app:layout_constraintTop_toTopOf="@+id/tableHeaderImage"
        />

    <TextView
        android:id="@+id/textViewSeatLabel"
        android:text="@string/seat_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Caption"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintRight_toRightOf="@+id/textViewSeat"
        app:layout_constraintLeft_toLeftOf="@+id/textViewSeat"
        app:layout_constraintTop_toTopOf="@+id/tableHeaderImage"
        />

    <TextView
        tools:text="@string/terminal"
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:id="@+id/textViewTerminal"
        app:layout_constraintTop_toTopOf="@+id/tableImage"
        app:layout_constraintLeft_toLeftOf="@+id/tableImage"
        app:layout_constraintRight_toRightOf="@+id/tableImage"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/white"
        app:layout_constraintHorizontal_bias="0.0"
        android:textAlignment="center" />

    <TextView
        android:id="@+id/textViewGate"
        tools:text="@string/gate"
        android:layout_width="120dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="@+id/tableImage"
        app:layout_constraintRight_toRightOf="@+id/tableImage"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/white"
        android:textAlignment="center"
        app:layout_constraintTop_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintBottom_toBottomOf="@+id/tableImage"/>

    <TextView
        android:id="@+id/textViewSeat"
        tools:text="@string/seat"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="@+id/tableImage"
        app:layout_constraintLeft_toLeftOf="@+id/tableImage"
        app:layout_constraintRight_toRightOf="@+id/tableImage"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/white"
        app:layout_constraintHorizontal_bias="1.0"
        android:textAlignment="center"
        android:layout_width="120dp" />
</code>```

And the corresponding layout is:

As we see the first ImageView (tableHeaderImage) is used for the header of the table and the second ImageView (tableImage) is used for the content of the table.

(The layout @+id/textViewDepartureTime is simply above 'tableHeaderImage' and I have not shown here for simplicity)

I can understand how Table header is formed (@+id/tableHeaderImage) clearly.

But I dont understand how content table (@+id/tableImage) is formed.

As we can see in the code the content table has 0dp width and height and three TextViews (namely @+id/textViewTerminal , @+id/textViewGate ,@+id/textViewSeat) 'somehow' 'expand' this content table beyond 0dp.

And I am not getting how this expansion of content table has taken place(Especially the vertical expansion of it).

答:
You see, @+id/textViewTerminal has a height of wrap_content, which means that its height depends on the text size attribute value, which is currently @style/TextAppearance.AppCompat.Display2, in other words the text size is Regular, 45sp :

Material Design Typography Styles

The height of the @+id/tableImage is truly 0dp, but it is defined in a different way by using constraints Look at these lines of code from the tableImage XML definition:

```<code>...
app:layout_constraintTop_toBottomOf="@+id/tableHeaderImage"
app:layout_constraintBottom_toBottomOf="@+id/textViewTerminal"
...
</code>```

You can see very obviously that the height of the @+id/tableImage is defined by the distance from the bottom of the @+id/tableHeaderImage
to the bottom of the @+id/textViewTerminal  which is defined implicitly by the text size. Let me know if you understand it.

Asking questions is always the fastest way to learn anything.
Good luck with the course.

Body:
I was going through a Udacity course on Android development and found this example of Constraintlayout (though I have shown only a part of the xml code and screen shot here). I have a hard time understanding how this is working.

xml layout file snippet:

        <ImageView
        android:id="@+id/tableHeaderImage"
        android:background="@color/colorPrimaryLight"
        android:layout_height="24dp"
        android:layout_width="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="32dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintTop_toBottomOf="@+id/textViewDepartureTime"
        app:layout_constraintHorizontal_bias="0.33" />

    <ImageView
        android:id="@+id/tableImage"
        android:background="@color/colorPrimary"
        android:layout_height="0dp"
        android:layout_width="0dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintBottom_toBottomOf="@+id/textViewTerminal"/>

    <TextView
        android:id="@+id/textViewTerminalLabel"
        android:text="@string/terminal_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Caption"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintLeft_toLeftOf="@+id/textViewTerminal"
        app:layout_constraintRight_toRightOf="@+id/textViewTerminal"

        app:layout_constraintTop_toTopOf="@+id/tableHeaderImage" />

    <TextView
        android:id="@+id/textViewGateLabel"
        android:text="@string/gate_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Caption"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintLeft_toLeftOf="@+id/textViewGate"
        app:layout_constraintRight_toRightOf="@+id/textViewGate"
        app:layout_constraintTop_toTopOf="@+id/tableHeaderImage"
        />

    <TextView
        android:id="@+id/textViewSeatLabel"
        android:text="@string/seat_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Caption"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintRight_toRightOf="@+id/textViewSeat"
        app:layout_constraintLeft_toLeftOf="@+id/textViewSeat"
        app:layout_constraintTop_toTopOf="@+id/tableHeaderImage"
        />

    <TextView
        tools:text="@string/terminal"
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:id="@+id/textViewTerminal"
        app:layout_constraintTop_toTopOf="@+id/tableImage"
        app:layout_constraintLeft_toLeftOf="@+id/tableImage"
        app:layout_constraintRight_toRightOf="@+id/tableImage"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/white"
        app:layout_constraintHorizontal_bias="0.0"
        android:textAlignment="center" />

    <TextView
        android:id="@+id/textViewGate"
        tools:text="@string/gate"
        android:layout_width="120dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="@+id/tableImage"
        app:layout_constraintRight_toRightOf="@+id/tableImage"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/white"
        android:textAlignment="center"
        app:layout_constraintTop_toBottomOf="@+id/tableHeaderImage"
        app:layout_constraintBottom_toBottomOf="@+id/tableImage"/>

    <TextView
        android:id="@+id/textViewSeat"
        tools:text="@string/seat"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="@+id/tableImage"
        app:layout_constraintLeft_toLeftOf="@+id/tableImage"
        app:layout_constraintRight_toRightOf="@+id/tableImage"
        android:textAppearance="@style/TextAppearance.AppCompat.Display2"
        android:textColor="@android:color/white"
        app:layout_constraintHorizontal_bias="1.0"
        android:textAlignment="center"
        android:layout_width="120dp" />

And the corresponding layout is:

As we see the first ImageView (tableHeaderImage) is used for the header of the table and the second ImageView (tableImage) is used for the content of the table.

(The layout @+id/textViewDepartureTime is simply above 'tableHeaderImage' and I have not shown here for simplicity)

I can understand how Table header is formed (@+id/tableHeaderImage) clearly.

But I dont understand how content table (@+id/tableImage) is formed.

As we can see in the code the content table has 0dp width and height and three TextViews (namely @+id/textViewTerminal , @+id/textViewGate ,@+id/textViewSeat) 'somehow' 'expand' this content table beyond 0dp.

And I am not getting how this expansion of content table has taken place(Especially the vertical expansion of it).

Body:
You see, @+id/textViewTerminal has a height of wrap_content, which means that its height depends on the text size attribute value, which is currently @style/TextAppearance.AppCompat.Display2, in other words the text size is Regular, 45sp :

Material Design Typography Styles

The height of the @+id/tableImage is truly 0dp, but it is defined in a different way by using constraints Look at these lines of code from the tableImage XML definition:

...
app:layout_constraintTop_toBottomOf="@+id/tableHeaderImage"
app:layout_constraintBottom_toBottomOf="@+id/textViewTerminal"
...

You can see very obviously that the height of the @+id/tableImage is defined by the distance from the bottom of the @+id/tableHeaderImage
to the bottom of the @+id/textViewTerminal  which is defined implicitly by the text size. Let me know if you understand it.

Asking questions is always the fastest way to learn anything.
Good luck with the course.


答:
A readonly object is equivalent to the intialization without readonly.  The main difference is that the IL metadat will have the initonly bit set on the field.

Nitpick: Both your expansion of using and lock are incorrect in subtle ways.

The lock version is incorrect because it's expansion depends on the version of the CLR and C# compiler you are using.  The C# 4.0 compiler combined with the 4.0 runtime uses the Enter(object, ref bool) pattern instead of plain Enter(object)

The using version is subtly incorrect because it looks a bit closer to this in the finally block

```<code>if (disposable != null) {
  ((IDisposable)disposable).Dispose();
}
</code>```

Title: Readonly field syntactic shortcut

Body:
A readonly object is equivalent to the intialization without readonly.  The main difference is that the IL metadat will have the initonly bit set on the field.

Nitpick: Both your expansion of using and lock are incorrect in subtle ways.

The lock version is incorrect because it's expansion depends on the version of the CLR and C# compiler you are using.  The C# 4.0 compiler combined with the 4.0 runtime uses the Enter(object, ref bool) pattern instead of plain Enter(object)

The using version is subtly incorrect because it looks a bit closer to this in the finally block

if (disposable != null) {
  ((IDisposable)disposable).Dispose();
}


问:
Floating Action Menu in Horizontal Direction
I am new to android development and I am using this library for my FABs and FAB menus. All the expansion of FABs in this library are vertical. But I want a horizontal expanding of FAB menu items. How do I do that ??

library

答:
UPDATE: The Library has no support for horizontal expanding. Source

There is a parameter for opening direction:

```<code>fab:menu_openDirection="up"

fab:menu_openDirection="down"
</code>```

You can find it in the documentation you give.

Usage like this:

```<code><com.github.clans.fab.FloatingActionMenu
    android:id="@+id/menu"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    fab:menu_openDirection="up">

    <com.github.clans.fab.FloatingActionButton
        android:id="@+id/menu_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_star"
        fab:fab_size="mini"
        fab:fab_label="Menu item 1" />

</com.github.clans.fab.FloatingActionMenu>
</code>```

But I couldn't see any left or right direction. You can ask this question to library's developer.

Body:
UPDATE: The Library has no support for horizontal expanding. Source

There is a parameter for opening direction:

fab:menu_openDirection="up"

fab:menu_openDirection="down"

You can find it in the documentation you give.

Usage like this:

<com.github.clans.fab.FloatingActionMenu
    android:id="@+id/menu"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    fab:menu_openDirection="up">

    <com.github.clans.fab.FloatingActionButton
        android:id="@+id/menu_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_star"
        fab:fab_size="mini"
        fab:fab_label="Menu item 1" />

</com.github.clans.fab.FloatingActionMenu>

But I couldn't see any left or right direction. You can ask this question to library's developer.


问:
How to find the second lowest and second highest number in a user-inputted list using loops and no arrays
For my program, I need to find the highest pair and lowest pair from 8 user-inputted ints, I am required to use a loop and no arrays.
Ex. 6, 7, 8, 9, 10, 11, 12, 13 should return: (13, 12) , (6, 7)

How should I go about finding the second highest and second lowest number using a loop?

答:
This is how you would find the lowest number in a users input without an array.

```<code>Scanner sc = new Scanner(System.in);
int lowest;
for(int i = 0; i < 8; i++) {
    int temp = sc.nextInt();
    if(i == 0) lowest = temp;
    else if(lowest > temp) lowest = temp;
}

return lowest;
</code>```

Now this can also be used to find the highest number by just switching the > symbol in the else if to < and you will find the greatest number in the input.

You can then use this process to find the lowest and highest pairs by adding more variables.

Body:
This is how you would find the lowest number in a users input without an array.

Scanner sc = new Scanner(System.in);
int lowest;
for(int i = 0; i < 8; i++) {
    int temp = sc.nextInt();
    if(i == 0) lowest = temp;
    else if(lowest > temp) lowest = temp;
}

return lowest;

Now this can also be used to find the highest number by just switching the > symbol in the else if to < and you will find the greatest number in the input.

You can then use this process to find the lowest and highest pairs by adding more variables.