问:
Angular - Cannot Read Property '..' of undefined
in my Angular project, I'm getting an error that says "cannot read property of '...' of undefined" where the '...' is the index of whichever employee that is selected from the combo box.

A little background on my project. I have the user select an employee from a combo box (tracker.component). Then, then index of that employee is taken and used to display the information of that employee (summary.component). It works great, along with having next, previous, first, last buttons but whenever I open the summary panel (summary.component) I get the error that I stated above in the browser. Where am I messing up?

Here's my tracker.component.ts

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

import { PTODataService } from './pto-data.service';
import { PTOData } from './pto-data';
import { EmpInfoService } from './emp-info.service';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-tracker',
    templateUrl: `./tracker.component.html`,
    styleUrls: ['./tracker.component.css']
})

export class TrackerComponent implements OnInit{
    empInfo: EmpInfo[] = new Array<EmpInfo>();
    ptoData: PTOData[];
    isHidden: boolean = false;
    selectedEmployee: number = 0;

    public selectedType: string = "PTO";

    constructor(
        private empInfoService: EmpInfoService,
        private ptoDataService: PTODataService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => {
                this.empInfo = empInfo.sort((a, b) => a.LastName < b.LastName ? -1 : b.LastName  this.ptoData = ptoData
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
        this.getPTOData();
    }

    toggleSummary(): void {
        this.isHidden = !this.isHidden;
    }

    isNextValid() {
        if (this.selectedEmployee > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    isPreviousValid() {
        if (this.selectedEmployee < this.empInfo.length - 1) {
            return true;
        }
        else {
            return false;
        }
    }

    nextEmployee(): void {
        this.selectedEmployee = this.selectedEmployee + 1;
    }

    previousEmployee(): void {
        this.selectedEmployee = this.selectedEmployee - 1;
    }

    firstEmployee(): void {
        this.selectedEmployee = 0;
    }

    lastEmployee(): void {
        this.selectedEmployee = this.empInfo.length - 1;
    }
}```
</div>
</div>
</p>

<p>my tracker.component.html</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div [ngClass]="{'col-xs-12':isHidden === true, 'col-xs-7': isHidden !== false}">
    <button class="btn btn-default btn-primary" style="width:50px; height: 50px; float:right; padding-bottom: 10px; padding-top: 10px;margin:5px;" (click)="toggleSummary()"><i class="fa fa-pencil-square-o fa-2x" aria-hidden="true"></i></button>

    <div class="col-xs-12 no-pad" style="padding-bottom:50px;">
      <div class="col-xs-3">
        <select class="form-control" id="empName" [(ngModel)]="selectedEmployee">
          <option selected="selected" disabled>Employee Name...</option>
          <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{i}} {{emp.EmpID}} - {{emp.FirstName}} {{emp.LastName}}</option>
        </select>
      </div>
      <div class="col-xs-2">
        <select class="form-control" id="PTOtype" [(ngModel)]="selectedType">
          <option selected="selected" value="PTO">PTO</option>
          <option value="etoEarned">ETO - Earned</option>
          <option value="etoUsed">ETO - Used</option>
          <option value="STDLTD">STD/LTD</option>
          <option value="Uncharged">Uncharged</option>
        </select>
      </div>
    </div>
    <div class="col-xs-12">
      <table class="table table-striped table-bordered">
        <thead>
          <tr>
            <th>Date</th>
            <th>Full/Half</th>
            <th>Hours</th>
            <th>Scheduled?</th>
            <th>Notes</th>
            <th>In P/R?</th>
          </tr>
        </thead>
        <tfoot *ngIf="empInfo && empInfo.length > selectedEmployee">
          <tr>
            <td colspan="6">
              <span class="requestText">Requests:</span>
              <button class="btn btn-default btn-primary btn-bargin" style="float: right;" (click)="lastEmployee()"><i class="fa fa-step-forward fa-lrg" aria-hidden="true"></i></button>
              <button [disabled]="!isPreviousValid()" class="btn btn-default btn-primary btn-margin" style="float:right;" (click)="nextEmployee()"><i class="fa fa-play fa-lrg" aria-hidden="true"></i></button>
              <div class="footertext">{{selectedEmployee+1}} of {{empInfo.length}}</div>
              <button [disabled]="!isNextValid()" class="btn btn-default btn-primary btn-margin" style="float: right;" (click)="previousEmployee()"><i class="fa fa-play fa-flip-horizontal fa-lrg" aria-hidden="true"></i></button>
              <button class="btn btn-default btn-primary btn-margin" style="float: right;" (click)="firstEmployee()"><i class="fa fa-step-backward fa-lrg" aria-hidden="true"></i></button>
            </td>
          </tr>
        </tfoot>
        <tbody>
          <tr *ngFor="let pto of ptoData">
            <ng-container *ngIf="pto.type === selectedType">
              <ng-container *ngIf="pto.EmpKey === empInfo[selectedEmployee].EmpKey">
                <td>{{pto.date | date: 'MM/dd/y'}}</td>
                <td>{{pto.fullhalf}}</td>
                <td>{{pto.hours}}</td>
                <td>{{pto.scheduled}}</td>
                <td>{{pto.notes}}</td>
                <td>{{pto.inPR}}</td>
              </ng-container>
            </ng-container>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <div *ngIf="isHidden" class="col-xs-5">
    <pto-summary [selectedEmployee]="selectedEmployee"></pto-summary>
  </div>
</div></code>```

my summary.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmpInfoService } from './emp-info.service';
import { TrackerComponent } from './tracker.component';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-summary',
    templateUrl: `./summary.component.html`,
    styleUrls: ['./summary.component.css']
})

export class SummaryComponent implements OnInit{

    empInfo: EmpInfo[];
    @Input() selectedEmployee: number;

    timeVar = " hours";
    checkboxValue = false;

    constructor(private empInfoService: EmpInfoService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => {
                this.empInfo = empInfo.sort((a, b) => a.LastName < b.LastName ? -1 : b.LastName < a.LastName ? 1 : 0);
            });
    }

    ngOnInit(): void {
        this.getEmpInfo();
    }

    changeTime(): void {
        if (!this.checkboxValue)
        {
            this.timeVar = " hours"

            this.empInfo[this.selectedEmployee].STDLTD = this.empInfo[this.selectedEmployee].STDLTD * 8;
            this.empInfo[this.selectedEmployee].Uncharged = this.empInfo[this.selectedEmployee].Uncharged * 8;

            this.empInfo[this.selectedEmployee].PTOBase = this.empInfo[this.selectedEmployee].PTOBase * 8;
            this.empInfo[this.selectedEmployee].PTOCarry = this.empInfo[this.selectedEmployee].PTOCarry * 8;
            this.empInfo[this.selectedEmployee].PTOBorrowed = this.empInfo[this.selectedEmployee].PTOBorrowed * 8;
            this.empInfo[this.selectedEmployee].PTOBalance = this.empInfo[this.selectedEmployee].PTOBalance * 8;
            this.empInfo[this.selectedEmployee].PTORequests = this.empInfo[this.selectedEmployee].PTORequests * 8;
            this.empInfo[this.selectedEmployee].PTORemaining = this.empInfo[this.selectedEmployee].PTORemaining * 8;

            this.empInfo[this.selectedEmployee].ETOEarned = this.empInfo[this.selectedEmployee].ETOEarned * 8;
            this.empInfo[this.selectedEmployee].ETORequests = this.empInfo[this.selectedEmployee].ETORequests * 8;
            this.empInfo[this.selectedEmployee].ETORemaining = this.empInfo[this.selectedEmployee].ETORemaining * 8;
        }
        else
        {
            this.timeVar = " days"

            this.empInfo[this.selectedEmployee].STDLTD = this.empInfo[this.selectedEmployee].STDLTD / 8;
            this.empInfo[this.selectedEmployee].Uncharged = this.empInfo[this.selectedEmployee].Uncharged / 8;

            this.empInfo[this.selectedEmployee].PTOBase = this.empInfo[this.selectedEmployee].PTOBase / 8;
            this.empInfo[this.selectedEmployee].PTOCarry = this.empInfo[this.selectedEmployee].PTOCarry / 8;
            this.empInfo[this.selectedEmployee].PTOBorrowed = this.empInfo[this.selectedEmployee].PTOBorrowed / 8;
            this.empInfo[this.selectedEmployee].PTOBalance = this.empInfo[this.selectedEmployee].PTOBalance / 8;
            this.empInfo[this.selectedEmployee].PTORequests = this.empInfo[this.selectedEmployee].PTORequests / 8;
            this.empInfo[this.selectedEmployee].PTORemaining = this.empInfo[this.selectedEmployee].PTORemaining / 8;

            this.empInfo[this.selectedEmployee].ETOEarned = this.empInfo[this.selectedEmployee].ETOEarned / 8;
            this.empInfo[this.selectedEmployee].ETORequests = this.empInfo[this.selectedEmployee].ETORequests / 8;
            this.empInfo[this.selectedEmployee].ETORemaining = this.empInfo[this.selectedEmployee].ETORemaining / 8;
        }
    }
}```
</div>
</div>
</p>

<p>and my summary.component.html</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title pull-left">{{empInfo[selectedEmployee].LastName | uppercase}} Summary</h3>
    <div style="float: right;">
      <div class="onoffswitch">
        <input [(ngModel)]="checkboxValue" (change)="changeTime()" type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
        <label class="onoffswitch-label" for="myonoffswitch">
          <span class="onoffswitch-inner"></span>
          <span class="onoffswitch-switch"></span>
        </label>
      </div>
    </div>
    <div class="clearfix"></div>
  </div>
  <div class="panel-body">
    <form class="form-horizontal" role="form" style="overflow-x:auto;">
      <fieldset>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> Status </label>
            <div class="col-xs-7">
              <select class="form-control" id="empStatus" [(ngModel)]="empInfo[selectedEmployee].EmpStat" name="empStatus">
                <option value="Current">Current</option>
                <option value="Terminated">Terminated</option>
              </select>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> Anniversary </label>
            <div class="col-xs-7">
              <div class="input-group">
                <input class='form-control' type="text" id="empAnniversary" [(ngModel)]="empInfo[selectedEmployee].Anniversary" name="empAnniversary" />
                <span class="input-group-addon">years</span>
              </div>
            </div>
          </div>
         </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> Start Date </label>
            <div class="col-xs-7">
              <input class='form-control' type="text" id="empStartDate" [ngModel]="empInfo[selectedEmployee].StartDate | date: 'MM/dd/y'" name="empStartDate"/>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> Adjusted Start </label>
            <div class="col-xs-7">
              <input class='form-control' type="text" id="empAdjustedStart" [ngModel]="empInfo[selectedEmployee].AdjustedStart | date: 'MM/dd/y'" name="empAdjustedStart"/>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> STD/LTD </label>
            <div class="col-xs-7">
              <div class="input-group">
                <input class='form-control' type="text" id="empSTDLTD" [(ngModel)]="empInfo[selectedEmployee].STDLTD" name="empSTDLTD" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-5"> Uncharged </label>
            <div class="col-xs-7">
              <div class="input-group">
                <input class='form-control' type="text" id="empUncharged" [(ngModel)]="empInfo[selectedEmployee].Uncharged" name="empUncharged" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
      </fieldset>

      <fieldset>

        <h4>PTO</h4>
        <br />

        <div class="col-xs-12">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <div class="col-xs-1"></div>
            <label class="col-xs-2"> Base </label>
            <div class="col-xs-3">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBase" [(ngModel)]="empInfo[selectedEmployee].PTOBase" name="ptoBase" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-6">
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-2" style="font-weight: bold;"> + </label>
            <label class="col-xs-4"> Carryover </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoCarry" [(ngModel)]="empInfo[selectedEmployee].PTOCarry" name="ptoCarry" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <div class="col-xs-1"></div>
            <label class="col-xs-4"> Balance </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="empInfo[selectedEmployee].PTOBalance" name="ptoBalance" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-1"></div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-2" style="font-weight: bold;"> ― </label>
            <label class="col-xs-4"> Borrowed </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBorrowed" [(ngModel)]="empInfo[selectedEmployee].PTOBorrowed" name="ptoBorrowed" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
          <hr style="border: solid 1px black;border-bottom:1px solid black;clear:both" />
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-1" style="font-weight: bold;"> ― </label>
            <label class="col-xs-4"> Requests </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoRequests" [(ngModel)]="empInfo[selectedEmployee].PTORequests" name="ptoRequests" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-1"></div>
          </div>
          <hr style="border: solid 1px black;border-bottom:1px solid black;clear:both" />
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-2" style="font-weight: bold;"> = </label>
            <label class="col-xs-4"> Balance </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="empInfo[selectedEmployee].PTOBalance" name="ptoBalance" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
            <label class="col-xs-1" style="font-weight: bold;"> = </label>
            <label class="col-xs-4"> Available </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoRemaining" [(ngModel)]="empInfo[selectedEmployee].PTORemaining" name="ptoRemaining" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-1"></div>
          </div>
        </div>
      </fieldset>

      <fieldset>

        <h4>ETO</h4>
        <br />

          <div class="col-xs-6">
            <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
              <div class="col-xs-2"></div>
              <label class="col-xs-4"> Earned </label>
              <div class="col-xs-6">
                <div class="input-group">
                  <input class='form-control' type="text" id="etoEarned" [(ngModel)]="empInfo[selectedEmployee].ETOEarned" name="etoEarned" />
                  <span class="input-group-addon">{{timeVar}}</span>
                </div>
              </div>
            </div>
            <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
              <label class="col-xs-2"> ― </label>
              <label class="col-xs-4"> Requests </label>
              <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="etoRequests" [(ngModel)]="empInfo[selectedEmployee].ETORequests" name="etoRequests" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
              </div>
            </div>
            <hr style="border: solid 1px black;border-bottom:1px solid black;clear:both" />
            <div class="form-group" *ngIf="empInfo && empInfo.length > selectedEmployee">
              <label class="col-xs-2"> = </label>
              <label class="col-xs-4"> Available </label>
              <div class="col-xs-6">
                <div class="input-group">
                  <input class='form-control' type="text" id="etoRemaining" [(ngModel)]="empInfo[selectedEmployee].ETORemaining" name="etoRemaining" />
                  <span class="input-group-addon">{{timeVar}}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="col-xs-6"></div>

      </fieldset>
    </form>
  </div>
</div></code>```

答:
I assume based on the message that the problem is here: {{empInfo[selectedEmployee].LastName | uppercase}}

If your service is using Http, then it is an asynchronous operation. That means that your page is trying to display before the data is available.

There are several common ways to resolve this issue, but your best bet may be to add an *ngIf in your HTML to check whether you have data before displaying the page.

Something like you already did here:

```<code>*ngIf="empInfo && empInfo.length
</code>```

Body:
in my Angular project, I'm getting an error that says "cannot read property of '...' of undefined" where the '...' is the index of whichever employee that is selected from the combo box.

A little background on my project. I have the user select an employee from a combo box (tracker.component). Then, then index of that employee is taken and used to display the information of that employee (summary.component). It works great, along with having next, previous, first, last buttons but whenever I open the summary panel (summary.component) I get the error that I stated above in the browser. Where am I messing up?

Here's my tracker.component.ts

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

import { PTODataService } from './pto-data.service';
import { PTOData } from './pto-data';
import { EmpInfoService } from './emp-info.service';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-tracker',
    templateUrl: `./tracker.component.html`,
    styleUrls: ['./tracker.component.css']
})

export class TrackerComponent implements OnInit{
    empInfo: EmpInfo[] = new Array<EmpInfo>();
    ptoData: PTOData[];
    isHidden: boolean = false;
    selectedEmployee: number = 0;

    public selectedType: string = "PTO";

    constructor(
        private empInfoService: EmpInfoService,
        private ptoDataService: PTODataService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => {
                this.empInfo = empInfo.sort((a, b) => a.LastName < b.LastName ? -1 : b.LastName  this.ptoData = ptoData
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
        this.getPTOData();
    }

    toggleSummary(): void {
        this.isHidden = !this.isHidden;
    }

    isNextValid() {
        if (this.selectedEmployee > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    isPreviousValid() {
        if (this.selectedEmployee < this.empInfo.length - 1) {
            return true;
        }
        else {
            return false;
        }
    }

    nextEmployee(): void {
        this.selectedEmployee = this.selectedEmployee + 1;
    }

    previousEmployee(): void {
        this.selectedEmployee = this.selectedEmployee - 1;
    }

    firstEmployee(): void {
        this.selectedEmployee = 0;
    }

    lastEmployee(): void {
        this.selectedEmployee = this.empInfo.length - 1;
    }
}

my tracker.component.html

    <button class="btn btn-default btn-primary" style="width:50px; height: 50px; float:right; padding-bottom: 10px; padding-top: 10px;margin:5px;" (click)="toggleSummary()"></button>

        <select class="form-control" id="empName" [(ngModel)]="selectedEmployee">
          <option selected="selected" disabled>Employee Name...</option>
          <option *ngFor="let emp of empInfo; let i = index" [ngValue]="i">{{i}} {{emp.EmpID}} - {{emp.FirstName}} {{emp.LastName}}</option>
        </select>

        <select class="form-control" id="PTOtype" [(ngModel)]="selectedType">
          <option selected="selected" value="PTO">PTO</option>
          <option value="etoEarned">ETO - Earned</option>
          <option value="etoUsed">ETO - Used</option>
          <option value="STDLTD">STD/LTD</option>
          <option value="Uncharged">Uncharged</option>
        </select>

            Date
            Full/Half
            Hours
            Scheduled?
            Notes
            In P/R?

 selectedEmployee">

              Requests:
              <button class="btn btn-default btn-primary btn-bargin" style="float: right;" (click)="lastEmployee()"></button>
              <button [disabled]="!isPreviousValid()" class="btn btn-default btn-primary btn-margin" style="float:right;" (click)="nextEmployee()"></button>

{{selectedEmployee+1}} of {{empInfo.length}}

              <button [disabled]="!isNextValid()" class="btn btn-default btn-primary btn-margin" style="float: right;" (click)="previousEmployee()"></button>
              <button class="btn btn-default btn-primary btn-margin" style="float: right;" (click)="firstEmployee()"></button>

            <ng-container *ngIf="pto.type === selectedType">
              <ng-container *ngIf="pto.EmpKey === empInfo[selectedEmployee].EmpKey">
                {{pto.date | date: 'MM/dd/y'}}
                {{pto.fullhalf}}
                {{pto.hours}}
                {{pto.scheduled}}
                {{pto.notes}}
                {{pto.inPR}}
              </ng-container>
            </ng-container>

    <pto-summary [selectedEmployee]="selectedEmployee"></pto-summary>

my summary.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmpInfoService } from './emp-info.service';
import { TrackerComponent } from './tracker.component';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-summary',
    templateUrl: `./summary.component.html`,
    styleUrls: ['./summary.component.css']
})

export class SummaryComponent implements OnInit{

    empInfo: EmpInfo[];
    @Input() selectedEmployee: number;

    timeVar = " hours";
    checkboxValue = false;

    constructor(private empInfoService: EmpInfoService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => {
                this.empInfo = empInfo.sort((a, b) => a.LastName < b.LastName ? -1 : b.LastName < a.LastName ? 1 : 0);
            });
    }

    ngOnInit(): void {
        this.getEmpInfo();
    }

    changeTime(): void {
        if (!this.checkboxValue)
        {
            this.timeVar = " hours"

            this.empInfo[this.selectedEmployee].STDLTD = this.empInfo[this.selectedEmployee].STDLTD * 8;
            this.empInfo[this.selectedEmployee].Uncharged = this.empInfo[this.selectedEmployee].Uncharged * 8;

            this.empInfo[this.selectedEmployee].PTOBase = this.empInfo[this.selectedEmployee].PTOBase * 8;
            this.empInfo[this.selectedEmployee].PTOCarry = this.empInfo[this.selectedEmployee].PTOCarry * 8;
            this.empInfo[this.selectedEmployee].PTOBorrowed = this.empInfo[this.selectedEmployee].PTOBorrowed * 8;
            this.empInfo[this.selectedEmployee].PTOBalance = this.empInfo[this.selectedEmployee].PTOBalance * 8;
            this.empInfo[this.selectedEmployee].PTORequests = this.empInfo[this.selectedEmployee].PTORequests * 8;
            this.empInfo[this.selectedEmployee].PTORemaining = this.empInfo[this.selectedEmployee].PTORemaining * 8;

            this.empInfo[this.selectedEmployee].ETOEarned = this.empInfo[this.selectedEmployee].ETOEarned * 8;
            this.empInfo[this.selectedEmployee].ETORequests = this.empInfo[this.selectedEmployee].ETORequests * 8;
            this.empInfo[this.selectedEmployee].ETORemaining = this.empInfo[this.selectedEmployee].ETORemaining * 8;
        }
        else
        {
            this.timeVar = " days"

            this.empInfo[this.selectedEmployee].STDLTD = this.empInfo[this.selectedEmployee].STDLTD / 8;
            this.empInfo[this.selectedEmployee].Uncharged = this.empInfo[this.selectedEmployee].Uncharged / 8;

            this.empInfo[this.selectedEmployee].PTOBase = this.empInfo[this.selectedEmployee].PTOBase / 8;
            this.empInfo[this.selectedEmployee].PTOCarry = this.empInfo[this.selectedEmployee].PTOCarry / 8;
            this.empInfo[this.selectedEmployee].PTOBorrowed = this.empInfo[this.selectedEmployee].PTOBorrowed / 8;
            this.empInfo[this.selectedEmployee].PTOBalance = this.empInfo[this.selectedEmployee].PTOBalance / 8;
            this.empInfo[this.selectedEmployee].PTORequests = this.empInfo[this.selectedEmployee].PTORequests / 8;
            this.empInfo[this.selectedEmployee].PTORemaining = this.empInfo[this.selectedEmployee].PTORemaining / 8;

            this.empInfo[this.selectedEmployee].ETOEarned = this.empInfo[this.selectedEmployee].ETOEarned / 8;
            this.empInfo[this.selectedEmployee].ETORequests = this.empInfo[this.selectedEmployee].ETORequests / 8;
            this.empInfo[this.selectedEmployee].ETORemaining = this.empInfo[this.selectedEmployee].ETORemaining / 8;
        }
    }
}

and my summary.component.html

{{empInfo[selectedEmployee].LastName | uppercase}} Summary

        <input [(ngModel)]="checkboxValue" (change)="changeTime()" type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>

    <form class="form-horizontal" role="form" style="overflow-x:auto;">
      <fieldset>

 selectedEmployee">
             Status

              <select class="form-control" id="empStatus" [(ngModel)]="empInfo[selectedEmployee].EmpStat" name="empStatus">
                <option value="Current">Current</option>
                <option value="Terminated">Terminated</option>
              </select>

 selectedEmployee">
             Anniversary

                <input class='form-control' type="text" id="empAnniversary" [(ngModel)]="empInfo[selectedEmployee].Anniversary" name="empAnniversary" />
                years

 selectedEmployee">
             Start Date

              <input class='form-control' type="text" id="empStartDate" [ngModel]="empInfo[selectedEmployee].StartDate | date: 'MM/dd/y'" name="empStartDate"/>

 selectedEmployee">
             Adjusted Start

              <input class='form-control' type="text" id="empAdjustedStart" [ngModel]="empInfo[selectedEmployee].AdjustedStart | date: 'MM/dd/y'" name="empAdjustedStart"/>

 selectedEmployee">
             STD/LTD

                <input class='form-control' type="text" id="empSTDLTD" [(ngModel)]="empInfo[selectedEmployee].STDLTD" name="empSTDLTD" />
                {{timeVar}}

 selectedEmployee">
             Uncharged

                <input class='form-control' type="text" id="empUncharged" [(ngModel)]="empInfo[selectedEmployee].Uncharged" name="empUncharged" />
                {{timeVar}}

      </fieldset>

      <fieldset>

PTO

 selectedEmployee">

             Base

                <input class='form-control' type="text" id="ptoBase" [(ngModel)]="empInfo[selectedEmployee].PTOBase" name="ptoBase" />
                {{timeVar}}

 selectedEmployee">
             +
             Carryover

                <input class='form-control' type="text" id="ptoCarry" [(ngModel)]="empInfo[selectedEmployee].PTOCarry" name="ptoCarry" />
                {{timeVar}}

 selectedEmployee">

             Balance

                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="empInfo[selectedEmployee].PTOBalance" name="ptoBalance" />
                {{timeVar}}

 selectedEmployee">
             ―
             Borrowed

                <input class='form-control' type="text" id="ptoBorrowed" [(ngModel)]="empInfo[selectedEmployee].PTOBorrowed" name="ptoBorrowed" />
                {{timeVar}}

 selectedEmployee">
             ―
             Requests

                <input class='form-control' type="text" id="ptoRequests" [(ngModel)]="empInfo[selectedEmployee].PTORequests" name="ptoRequests" />
                {{timeVar}}

 selectedEmployee">
             =
             Balance

                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="empInfo[selectedEmployee].PTOBalance" name="ptoBalance" />
                {{timeVar}}

 selectedEmployee">
             =
             Available

                <input class='form-control' type="text" id="ptoRemaining" [(ngModel)]="empInfo[selectedEmployee].PTORemaining" name="ptoRemaining" />
                {{timeVar}}

      </fieldset>

      <fieldset>

ETO

 selectedEmployee">

               Earned

                  <input class='form-control' type="text" id="etoEarned" [(ngModel)]="empInfo[selectedEmployee].ETOEarned" name="etoEarned" />
                  {{timeVar}}

 selectedEmployee">
               ―
               Requests

                <input class='form-control' type="text" id="etoRequests" [(ngModel)]="empInfo[selectedEmployee].ETORequests" name="etoRequests" />
                {{timeVar}}

 selectedEmployee">
               =
               Available

                  <input class='form-control' type="text" id="etoRemaining" [(ngModel)]="empInfo[selectedEmployee].ETORemaining" name="etoRemaining" />
                  {{timeVar}}

      </fieldset>
    </form>

Body:
I assume based on the message that the problem is here: {{empInfo[selectedEmployee].LastName | uppercase}}

If your service is using Http, then it is an asynchronous operation. That means that your page is trying to display before the data is available.

There are several common ways to resolve this issue, but your best bet may be to add an *ngIf in your HTML to check whether you have data before displaying the page.

Something like you already did here:

*ngIf="empInfo && empInfo.length


来源: stackexchange

问:
why does java Charset need extra import?
I am teaching myself a little about Files and I/O in Java, based on this tutorial: Oracle Tutorial

Now, after writing some examples to understand input and output, I got a question regarding the import of certain libraries.

I created the following example program, and I ask myself why the program says:

Cannot find symbol - class Charset

```<code>import java.nio.*;

public class test
{

public static void main(String[] args)
{
    Charset charset = Charset.forName("US-ASCII");
}

}
</code>```

I know that the solution is to import the following
    import java.nio.charset.*;

But why do I have to import it, if I already got the parent library?

答: An example to help is when you think about it the object package is the king of all the packages, yet if you import it you don't get everything under it.  Then there would be no need to ever import stuff, not to mention the problems this creates.  You can't  just import a package and expect everything created under it to come with it.  Sub packages are still needed for storage reasons. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am teaching myself a little about Files and I/O in Java, based on this tutorial: Oracle Tutorial

Now, after writing some examples to understand input and output, I got a question regarding the import of certain libraries.

I created the following example program, and I ask myself why the program says:

Cannot find symbol - class Charset

import java.nio.*;

public class test
{

public static void main(String[] args)
{
    Charset charset = Charset.forName("US-ASCII");
}

}

I know that the solution is to import the following
    import java.nio.charset.*;

But why do I have to import it, if I already got the parent library?


问:
XSLT Formatting to remove empty columns (And the headers)
I have a database field I am pulling xml out of. This field contains the content from multiple XML feeds of which I need two. I am displaying the XML on a page and using XSLT to format it.

My issue is that there could be up to 40 elements per message in the DB, of that I am looking for about 30. However, not all messages will have all 30. I need help figuring out how to remove a column if there is no data to display.

If I can use XSLT then great, if it is JavaScript(Jquery) then that is fine too. There will never be more then one row and one header at a time.

Here is a sample of the XML

```<code><MessageToUser>
  <Name>Bob</Name>
  <MessageType>Text Message</MessageType>
  <MessageID>121223</MessageID>
  <ResponseTo />
  <Message>Call Me Please </Message>
  <OfficePhone>555-555-1212</OfficePhone>
  <CellPhone>555-555-5555</CellPhone>
</MessageToUser>
</code>```

And here is the XSL I am using

```<code><xsl:template match="/">
<html>
<head>
  <style type="text/css">
    .Header{min-width: 100px;background-color:#9acddd;}
  </style>
</head>
<body>
  <table border="1">
    <tr>
        <th class="Header">Name</th>
        <th class="Header">Message</th>
        <th class="Header">Cell Phone</th>
        <th class="Header">Office Phone</th>
        <th class="Header">Message Type</th>
        <th class="Header">Message Time</th>
        <th class="Header">Message ID</th>
      </tr>
      <xsl:for-each select="MessageFromUser">
        <tr>
          <td><xsl:value-of select="Name" /></td>
          <td><xsl:value-of select="Message" /></td>
          <td><xsl:value-of select="CellPhone" /></td>
          <td><xsl:value-of select="OfficePhone" /></td>
          <td><xsl:value-of select="MessageType" /></td>
          <td><xsl:value-of select="MessageTime" /></td>
          <td><xsl:value-of select="MessageID" /></td>
        </tr>
      </xsl:for-each>
      <xsl:for-each select="MessageToUser">
        <tr>
          <td><xsl:value-of select="Name" /></td>
          <td><xsl:value-of select="Message" /></td>
          <td><xsl:value-of select="CellPhone" /></td>
          <td><xsl:value-of select="OfficePhone" /></td>
          <td><xsl:value-of select="MessageType" /></td>
          <td><xsl:value-of select="MessageTime" /></td>
          <td><xsl:value-of select="MessageID" /></td>
        </tr>
      </xsl:for-each>
    </table>
 </body>
</code>```

Using this XML MessageTime is blank and that column should be removed.

Thanks in advance for any help.

答:
This XSLT:

```<code><?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes"/>

<xsl:key name="notEmptyAll" match="/root/MessageToUser/*" use="local-name()"/>

<xsl:template match="root">
<html>
<head>
  <style type="text/css">
    th {min-width: 100px;background-color:#9acddd;}
  </style>
</head>
<body>
    <table border="1">
        <tr>
            <xsl:apply-templates select="MessageToUser[1]/*" mode="header"/>
        </tr>
        <xsl:apply-templates select="MessageToUser"/>
    </table>
</body>
</html>
</xsl:template>

<xsl:template match="*" mode="header">
<xsl:if test="count( key('notEmptyAll', local-name())[text()] ) != 0">
    <th>
        <xsl:value-of select="local-name()"/>
    </th>
</xsl:if>
</xsl:template>

<xsl:template match="MessageToUser">
<tr>
    <xsl:apply-templates select="*" mode="tbody"/>
</tr>
</xsl:template>

<xsl:template match="*" mode="tbody">
<xsl:if test="count( key('notEmptyAll', local-name())[text()] ) != 0">
    <td>
        <xsl:value-of select="."/>
    </td>
</xsl:if>
</xsl:template>

</xsl:stylesheet>
</code>```

With this XML input:

```<code><root>
<MessageToUser>
    <Name>Bob</Name>
    <MessageType>Text Message</MessageType>
    <MessageID>121223</MessageID>
    <ResponseTo>   </ResponseTo>
    <Message>Call Me Please </Message>
    <OfficePhone></OfficePhone>
    <CellPhone>555-555-5555</CellPhone>
 </MessageToUser>
 <MessageToUser>
    <Name></Name>
    <MessageType>Text Message</MessageType>
    <MessageID>121223</MessageID>
    <ResponseTo>   </ResponseTo>
    <Message>Call Me Please </Message>
    <OfficePhone>555-555-1212</OfficePhone>
    <CellPhone>555-555-5555</CellPhone>
 </MessageToUser>
 </root>
</code>```

will provide this result (excerpt):

```<code><table border="1">
    <tr>
        <th>Name</th>
        <th>MessageType</th>
        <th>MessageID</th>
        <th>Message</th>
        <th>OfficePhone</th>
        <th>CellPhone</th>
    </tr>
    <tr>
        <td>Bob</td>
        <td>Text Message</td>
        <td>121223</td>
        <td>Call Me Please </td>
        <td></td>
        <td>555-555-5555</td>
    </tr>
    <tr>
        <td></td>
        <td>Text Message</td>
        <td>121223</td>
        <td>Call Me Please </td>
        <td>555-555-1212</td>
        <td>555-555-5555</td>
    </tr>
</table>
</code>```

Thus all elements, that have at least one non-empty value, are displayed.

local-name can be unsufficient for you, cause headers will be like OfficePhone. This can be solved with substrings or with "vocabulary". Please free to comment what will suit better, cause it's not obvious from your XML excerpt.

I didn't use MessageFromUser, cause you didn't provide XML sample with it.

ContentLicense: CC BY-SA 2.5

Body:
I have a database field I am pulling xml out of. This field contains the content from multiple XML feeds of which I need two. I am displaying the XML on a page and using XSLT to format it.

My issue is that there could be up to 40 elements per message in the DB, of that I am looking for about 30. However, not all messages will have all 30. I need help figuring out how to remove a column if there is no data to display.

If I can use XSLT then great, if it is JavaScript(Jquery) then that is fine too. There will never be more then one row and one header at a time.

Here is a sample of the XML

<MessageToUser>
  <Name>Bob</Name>
  <MessageType>Text Message</MessageType>
  <MessageID>121223</MessageID>
  <ResponseTo />
  <Message>Call Me Please </Message>
  <OfficePhone>555-555-1212</OfficePhone>
  <CellPhone>555-555-5555</CellPhone>
</MessageToUser>

And here is the XSL I am using

<xsl:template match="/">

        Name
        Message
        Cell Phone
        Office Phone
        Message Type
        Message Time
        Message ID

      <xsl:for-each select="MessageFromUser">

          <xsl:value-of select="Name" />
          <xsl:value-of select="Message" />
          <xsl:value-of select="CellPhone" />
          <xsl:value-of select="OfficePhone" />
          <xsl:value-of select="MessageType" />
          <xsl:value-of select="MessageTime" />
          <xsl:value-of select="MessageID" />

      </xsl:for-each>
      <xsl:for-each select="MessageToUser">

          <xsl:value-of select="Name" />
          <xsl:value-of select="Message" />
          <xsl:value-of select="CellPhone" />
          <xsl:value-of select="OfficePhone" />
          <xsl:value-of select="MessageType" />
          <xsl:value-of select="MessageTime" />
          <xsl:value-of select="MessageID" />

      </xsl:for-each>

Using this XML MessageTime is blank and that column should be removed.

Thanks in advance for any help.

Body:
This XSLT:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes"/>

<xsl:key name="notEmptyAll" match="/root/MessageToUser/*" use="local-name()"/>

<xsl:template match="root">
<html>
<head>
  <style type="text/css">
    th {min-width: 100px;background-color:#9acddd;}
  </style>
</head>
<body>
    <table border="1">
        <tr>
            <xsl:apply-templates select="MessageToUser[1]/*" mode="header"/>
        </tr>
        <xsl:apply-templates select="MessageToUser"/>
    </table>
</body>
</html>
</xsl:template>

<xsl:template match="*" mode="header">
<xsl:if test="count( key('notEmptyAll', local-name())[text()] ) != 0">
    <th>
        <xsl:value-of select="local-name()"/>
    </th>
</xsl:if>
</xsl:template>

<xsl:template match="MessageToUser">
<tr>
    <xsl:apply-templates select="*" mode="tbody"/>
</tr>
</xsl:template>

<xsl:template match="*" mode="tbody">
<xsl:if test="count( key('notEmptyAll', local-name())[text()] ) != 0">
    <td>
        <xsl:value-of select="."/>
    </td>
</xsl:if>
</xsl:template>

</xsl:stylesheet>

With this XML input:

<root>
<MessageToUser>
    <Name>Bob</Name>
    <MessageType>Text Message</MessageType>
    <MessageID>121223</MessageID>
    <ResponseTo>   </ResponseTo>
    <Message>Call Me Please </Message>
    <OfficePhone></OfficePhone>
    <CellPhone>555-555-5555</CellPhone>
 </MessageToUser>
 <MessageToUser>
    <Name></Name>
    <MessageType>Text Message</MessageType>
    <MessageID>121223</MessageID>
    <ResponseTo>   </ResponseTo>
    <Message>Call Me Please </Message>
    <OfficePhone>555-555-1212</OfficePhone>
    <CellPhone>555-555-5555</CellPhone>
 </MessageToUser>
 </root>

will provide this result (excerpt):

<table border="1">
    <tr>
        <th>Name</th>
        <th>MessageType</th>
        <th>MessageID</th>
        <th>Message</th>
        <th>OfficePhone</th>
        <th>CellPhone</th>
    </tr>
    <tr>
        <td>Bob</td>
        <td>Text Message</td>
        <td>121223</td>
        <td>Call Me Please </td>
        <td></td>
        <td>555-555-5555</td>
    </tr>
    <tr>
        <td></td>
        <td>Text Message</td>
        <td>121223</td>
        <td>Call Me Please </td>
        <td>555-555-1212</td>
        <td>555-555-5555</td>
    </tr>
</table>

Thus all elements, that have at least one non-empty value, are displayed.

local-name can be unsufficient for you, cause headers will be like OfficePhone. This can be solved with substrings or with "vocabulary". Please free to comment what will suit better, cause it's not obvious from your XML excerpt.

I didn't use MessageFromUser, cause you didn't provide XML sample with it.


问:
How can I print after each parameter is inputed in a method?
I know my problem but I can't seem to figure out a way to solve it.

What I want to do is after the user gives their preferred username, I want to print the phoneNumber next to it the input, and the problem I'm running into is this.

I would get the user to input,

Username: PhoneNumber: then now they can input

Instead what I want is something like this:

Username: input from the method parameter.....

phoneNumber: same thing as above

UPDATED VERSION:

This is the error I get

userName cannot be resolved to a variable

```<code> public void createCustomer(String userName) {

    System.out.print("Enter username: ");
    this.user = input.nextLine();
    this.user = userName;

    this.password = password;
    this.address = address;
    this.phoneNum = phoneNum;
    this.email = email;
}

public static void main (String args[]) {
    CustomerUI customer = new CustomerUI();
    Scanner input = new Scanner(System.in);

    if(shouldCreate() == true) {
        customer.createCustomer(userName);
    }
}
</code>```

答:
You can scan each line after outputting the prompt to input the username or the phone number. For example:

```<code>Scanner scanner = new Scanner(System.in);
System.out.println("Enter username: ");
String username = scanner.nextLine();
System.out.println("Username: " + username);
</code>```

And then the same for phone number. You can then passed the values to the createCustomer method:

```<code>customer.createCustomer(username, phoneNumber, otherVar, anotherVar, lastVar);
</code>```

Edit to address updated code: you are not defining username in the main method. If we go through your code, this is what is happening:

We enter at the main method where you define customer (a CustomerUI object), and the input (a Scanner object).

If the shouldCreate() method returns true, we will then create the customer using customer.createCustomer(userName). However, at this point, the userName has not bee defined anywhere (e.g. String userName;)

In createCustomer, we print out the line "Enter username: " to the console

We then set the user class variable to the line entered in the console, suing input.nextLine(). However, at this point, we have no variable called input defined in this method. It was defined in main, but as a local variable. Therefore, it cannot be accessed in this other method.

The user class variable is then assigned from the userName method parameter. This would overwrite the input.nextLine() value, rendering that line useless

What I would recommend:

Put the Scanner input = new Scanner(System.in) line into the createCustomer method

Remove the parameters of the createCustomer method, and instead assign the values from the input.nextLine() method each time

Alternatively:

Keep the Scanner input = new Scanner(System.in) line in the main method

Move the input.nextLine() method calls into the main method, and assigning their values to local variables

Pass these variables to the createCustomer method which can then assign this to the class variables

ContentLicense: CC BY-SA 4.0

Body:
I know my problem but I can't seem to figure out a way to solve it.

What I want to do is after the user gives their preferred username, I want to print the phoneNumber next to it the input, and the problem I'm running into is this.

I would get the user to input,

Username: PhoneNumber: then now they can input

Instead what I want is something like this:

Username: input from the method parameter.....

phoneNumber: same thing as above

UPDATED VERSION:

This is the error I get

userName cannot be resolved to a variable

 public void createCustomer(String userName) {

    System.out.print("Enter username: ");
    this.user = input.nextLine();
    this.user = userName;

    this.password = password;
    this.address = address;
    this.phoneNum = phoneNum;
    this.email = email;
}

public static void main (String args[]) {
    CustomerUI customer = new CustomerUI();
    Scanner input = new Scanner(System.in);

    if(shouldCreate() == true) {
        customer.createCustomer(userName);
    }
}

Body:
You can scan each line after outputting the prompt to input the username or the phone number. For example:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter username: ");
String username = scanner.nextLine();
System.out.println("Username: " + username);

And then the same for phone number. You can then passed the values to the createCustomer method:

customer.createCustomer(username, phoneNumber, otherVar, anotherVar, lastVar);

Edit to address updated code: you are not defining username in the main method. If we go through your code, this is what is happening:

We enter at the main method where you define customer (a CustomerUI object), and the input (a Scanner object).

If the shouldCreate() method returns true, we will then create the customer using customer.createCustomer(userName). However, at this point, the userName has not bee defined anywhere (e.g. String userName;)

In createCustomer, we print out the line "Enter username: " to the console

We then set the user class variable to the line entered in the console, suing input.nextLine(). However, at this point, we have no variable called input defined in this method. It was defined in main, but as a local variable. Therefore, it cannot be accessed in this other method.

The user class variable is then assigned from the userName method parameter. This would overwrite the input.nextLine() value, rendering that line useless

What I would recommend:

Put the Scanner input = new Scanner(System.in) line into the createCustomer method

Remove the parameters of the createCustomer method, and instead assign the values from the input.nextLine() method each time

Alternatively:

Keep the Scanner input = new Scanner(System.in) line in the main method

Move the input.nextLine() method calls into the main method, and assigning their values to local variables

Pass these variables to the createCustomer method which can then assign this to the class variables


问:
Connection name on queue
I used redis for task queue in laravel, i want to use connection name per queue to handle config varibales conflict in queue in below code :

```<code>  php artisan queue:work connection-name --deamon --queue=high,medium,low --sleep=3 --tries=3
</code>```

But i dont know what is the connection name in below code to use:

```<code>'default' => env('QUEUE_DRIVER', 'redis'),

'connections' => [

    'sync' => [
        'driver' => 'sync',
    ],

    'database' => [
        'driver' => 'database',
        'table' => 'jobs',
        'queue' => 'default',
        'expire' => 60,
    ],

    'beanstalkd' => [
        'driver' => 'beanstalkd',
        'host' => 'localhost',
        'queue' => 'default',
        'ttr' => 60,
    ],

    'sqs' => [
        'driver' => 'sqs',
        'key' => 'your-public-key',
        'secret' => 'your-secret-key',
        'prefix' => 'https://sqs.us-east-1.amazonaws.com/your-account-id',
        'queue' => 'your-queue-name',
        'region' => 'us-east-1',
    ],

    'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
        'queue' => 'default',
        'expire' => 60,
    ],

],
</code>```

答:
You have several connections configured.

Each connection is an element in the connections array and you just need to pass the relevant key as the name.

e.g.

```<code>php artisan queue:work sqs --daemon --queue=high --sleep=3 --tries=3
</code>```

Title: Connection name on queue

Body:
I used redis for task queue in laravel, i want to use connection name per queue to handle config varibales conflict in queue in below code :

  php artisan queue:work connection-name --deamon --queue=high,medium,low --sleep=3 --tries=3

But i dont know what is the connection name in below code to use:

'default' => env('QUEUE_DRIVER', 'redis'),

'connections' => [

    'sync' => [
        'driver' => 'sync',
    ],

    'database' => [
        'driver' => 'database',
        'table' => 'jobs',
        'queue' => 'default',
        'expire' => 60,
    ],

    'beanstalkd' => [
        'driver' => 'beanstalkd',
        'host' => 'localhost',
        'queue' => 'default',
        'ttr' => 60,
    ],

    'sqs' => [
        'driver' => 'sqs',
        'key' => 'your-public-key',
        'secret' => 'your-secret-key',
        'prefix' => 'https://sqs.us-east-1.amazonaws.com/your-account-id',
        'queue' => 'your-queue-name',
        'region' => 'us-east-1',
    ],

    'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
        'queue' => 'default',
        'expire' => 60,
    ],

],

Body:
You have several connections configured.

Each connection is an element in the connections array and you just need to pass the relevant key as the name.

e.g.

php artisan queue:work sqs --daemon --queue=high --sleep=3 --tries=3


问:
C# Separate GUI from Work logic
I'd like to find how to separate my GUI and work code.
The contrived example code, below, is the smallest starting point that
I can think of that covers the idea.

The example uses a Windows Form as the source of commands and as display
(consumer) of results.  I want the work code to be capable of getting commands from, say, a command line interface instead.  The work code should not depend on knowledge of the Form.  The Form should know little about the work code.  I'd like to have several consumers "see" when the property in the work code changes value.

I'm guessing this means using events for communication, and perhaps Interfaces as well, but I'm open to anything.

There are a million different suggestions out there.  I've read the design pattern books, and I have tried many, and have yet to find a set that is well enough explained that I can fully implement it.

I don't want a universal solution.  I want one as simple as possible
to implement and maintain for small, personal projects.  I'm not
designing for a large corporation.

Most solutions I've found will hint at what to do, but not cover
the specifics like where an event is declared, and how the other
piece of code finds out about the event's existence so it can either issue
the event or respond to the event. I always end up needing, somewhere, what amounts to a global variable to hook things together.

The closest match I can find, here, to my question is this: C# Windows Forms App: Separate GUI from Business Logic But the solution uses the form to create an instance of the worker and returns a value directly, rather than informing any interested observers. The provided solution tightly bound the two classes.

The closest solution I've found anywhere is this: https://www.codeproject.com/Articles/14660/WinForms-Model-View-Presenter
 which does some really cool work with interfaces and reflection, but didn't seem too maintainable nor flexible.

The comment lines in the source code below show the desired interaction
points but without the implementation.

File #1:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // tell an instance of JustCounts to increment by 10
    }

    // Here, allow JustCounts to cause a call to this (or something
    // similar, perhaps a property) to inform this code that the TotalCount
    // property has changed.
    public void ShowNewTotalCount(int NewTotal)
    {
        Console.WriteLine("New Total Count = {0}", NewTotal);
    }
}
</code>```

File #2

```<code>class JustCounts
{
    private int m_TotalCount = 100;
    // Inform other classes when the following property changes value,
    // preferably including the value in the notification.
    public int TotalCount { get => m_TotalCount; }

    // The code in File #1 needs to result in a call to this method
    // along with the correct argument value.
    public void AddThisMuch(int increment)
    {
        m_TotalCount += increment;
    }
}
</code>```

答:
I'm basing this on the current version of .Net (4.6.2).

If we implement INotifyPropertyChanged then we have an event that we can listen to for property changes. A bit like listening for key presses, we can filter then for the specific property that we want.

```<code>public class JustCounts : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private int m_totalCount = 100;

    public int TotalCount
    {
        get { return m_totalCount; }
        set
        {
            if (value != m_totalCount)
            {
                m_totalCount = value;
                NotifyPropertyChanged();
            }
        }
    }
}
</code>```

There's no need to create a method to manipulate the TotalCount property as we're exposing it.

```<code>public class Form1 : Form
{
    // justCounts is a reference to the object wherever it is coming from
    justCounts.PropertyChanged += new PropertyChangedEventHandler(JustCountsChangedHandler);

    private void JustCountsChangedHandler(object sender, PropertyChangingEventArgs e)
    {
        // process on event firing
        Debug.WriteLine($"justCounts TotalCount changed value to {justCounts.TotalCount}");
    }

    // Example of where the handler will fire when called
    private void button1_click(object sender, EventArgs e)
    {
        justCounts.TotalCount++;
    }
}
</code>```

In the code above, we've created an event in JustCounts to which listeners can subscribe.

Using the INotifyPropertyChanged interface, we fire the event each time TotalCount is changed.

In form 1 we create the handler to listen for property changes, and the handler then carries out any processing.

One note. You say

I'd like to have several consumers "see" when the property in the work
  code changes value

so in order for this to work we have to assume that the work code can run independently of it's subscriber (something like a server). Otherwise, we'd have different instances for different subscribers.

You also mention interfaces, and they could be used but are not necessary in this instance.

Title: C# Separate GUI from Work logic

Body:
I'd like to find how to separate my GUI and work code.
The contrived example code, below, is the smallest starting point that
I can think of that covers the idea.

The example uses a Windows Form as the source of commands and as display
(consumer) of results.  I want the work code to be capable of getting commands from, say, a command line interface instead.  The work code should not depend on knowledge of the Form.  The Form should know little about the work code.  I'd like to have several consumers "see" when the property in the work code changes value.

I'm guessing this means using events for communication, and perhaps Interfaces as well, but I'm open to anything.

There are a million different suggestions out there.  I've read the design pattern books, and I have tried many, and have yet to find a set that is well enough explained that I can fully implement it.

I don't want a universal solution.  I want one as simple as possible
to implement and maintain for small, personal projects.  I'm not
designing for a large corporation.

Most solutions I've found will hint at what to do, but not cover
the specifics like where an event is declared, and how the other
piece of code finds out about the event's existence so it can either issue
the event or respond to the event. I always end up needing, somewhere, what amounts to a global variable to hook things together.

The closest match I can find, here, to my question is this: C# Windows Forms App: Separate GUI from Business Logic But the solution uses the form to create an instance of the worker and returns a value directly, rather than informing any interested observers. The provided solution tightly bound the two classes.

The closest solution I've found anywhere is this: https://www.codeproject.com/Articles/14660/WinForms-Model-View-Presenter
 which does some really cool work with interfaces and reflection, but didn't seem too maintainable nor flexible.

The comment lines in the source code below show the desired interaction
points but without the implementation.

File #1:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // tell an instance of JustCounts to increment by 10
    }

    // Here, allow JustCounts to cause a call to this (or something
    // similar, perhaps a property) to inform this code that the TotalCount
    // property has changed.
    public void ShowNewTotalCount(int NewTotal)
    {
        Console.WriteLine("New Total Count = {0}", NewTotal);
    }
}

File #2

class JustCounts
{
    private int m_TotalCount = 100;
    // Inform other classes when the following property changes value,
    // preferably including the value in the notification.
    public int TotalCount { get => m_TotalCount; }

    // The code in File #1 needs to result in a call to this method
    // along with the correct argument value.
    public void AddThisMuch(int increment)
    {
        m_TotalCount += increment;
    }
}

Body:
I'm basing this on the current version of .Net (4.6.2).

If we implement INotifyPropertyChanged then we have an event that we can listen to for property changes. A bit like listening for key presses, we can filter then for the specific property that we want.

public class JustCounts : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private int m_totalCount = 100;

    public int TotalCount
    {
        get { return m_totalCount; }
        set
        {
            if (value != m_totalCount)
            {
                m_totalCount = value;
                NotifyPropertyChanged();
            }
        }
    }
}

There's no need to create a method to manipulate the TotalCount property as we're exposing it.

public class Form1 : Form
{
    // justCounts is a reference to the object wherever it is coming from
    justCounts.PropertyChanged += new PropertyChangedEventHandler(JustCountsChangedHandler);

    private void JustCountsChangedHandler(object sender, PropertyChangingEventArgs e)
    {
        // process on event firing
        Debug.WriteLine($"justCounts TotalCount changed value to {justCounts.TotalCount}");
    }

    // Example of where the handler will fire when called
    private void button1_click(object sender, EventArgs e)
    {
        justCounts.TotalCount++;
    }
}

In the code above, we've created an event in JustCounts to which listeners can subscribe.

Using the INotifyPropertyChanged interface, we fire the event each time TotalCount is changed.

In form 1 we create the handler to listen for property changes, and the handler then carries out any processing.

One note. You say

I'd like to have several consumers "see" when the property in the work
  code changes value

so in order for this to work we have to assume that the work code can run independently of it's subscriber (something like a server). Otherwise, we'd have different instances for different subscribers.

You also mention interfaces, and they could be used but are not necessary in this instance.


问:
Reduce array to sum of elements
I am trying to reduce a vector to a sum of all it elements. Is there an easy way to do this in verilog?

Similar to the systemverilog .sum method.

Thanks

答:
In critiquing the other answers delivered here, there are some comments to make.

The first important thing is to provide space for the sum to be accumulated. statements such as the following, in RTL, won't do that:

sum = sum + array[i]

because each of the unique nets created on the Right Hand Side (RHS) of the expression are all being assigned back to the same signal called "sum", leading to ambiguity in which of the unique nets is actually the driver (called a multiple driver hazard). To compound the problem, this statement also creates a combinational loop issue because sum is used combinationally to drive itself - not good. What would be good would be if something different could be used as the load and as the driver on each successive iteration of the loop....

Back to the argument though, in the above situation, the signal will be driven to an unknown value by most simulator tools (because: which driver should it pick? so assume none of them are right, or all of them are right - unknown!!). That is if it manages to get through the compiler at all (which is unlikely, and it doesn't at least in Cadence IEV).

The right way to do it would be to set up the following. Say you were summing bytes:

```<code>parameter NUM_BYTES = 4;
reg [7:0] array_of_bytes [NUM_BYTES-1:0];
reg [8+$clog2(NUM_BYTES):0] sum [NUM_BYTES-1:1];

always @* begin
    for (int i=1; i<NUM_BYTES; i+=1) begin
         if (i == 1) begin
             sum[i] = array_of_bytes[i] + array_of_bytes[i-1];
         end
         else begin
             sum[i] = sum[i-1] + array_of_bytes[i];
         end
    end
end

// The accumulated value is indexed at sum[NUM_BYTES-1]
</code>```

Title: Reduce array to sum of elements

Body:
In critiquing the other answers delivered here, there are some comments to make.

The first important thing is to provide space for the sum to be accumulated. statements such as the following, in RTL, won't do that:

sum = sum + array[i]

because each of the unique nets created on the Right Hand Side (RHS) of the expression are all being assigned back to the same signal called "sum", leading to ambiguity in which of the unique nets is actually the driver (called a multiple driver hazard). To compound the problem, this statement also creates a combinational loop issue because sum is used combinationally to drive itself - not good. What would be good would be if something different could be used as the load and as the driver on each successive iteration of the loop....

Back to the argument though, in the above situation, the signal will be driven to an unknown value by most simulator tools (because: which driver should it pick? so assume none of them are right, or all of them are right - unknown!!). That is if it manages to get through the compiler at all (which is unlikely, and it doesn't at least in Cadence IEV).

The right way to do it would be to set up the following. Say you were summing bytes:

parameter NUM_BYTES = 4;
reg [7:0] array_of_bytes [NUM_BYTES-1:0];
reg [8+$clog2(NUM_BYTES):0] sum [NUM_BYTES-1:1];

always @* begin
    for (int i=1; i<NUM_BYTES; i+=1) begin
         if (i == 1) begin
             sum[i] = array_of_bytes[i] + array_of_bytes[i-1];
         end
         else begin
             sum[i] = sum[i-1] + array_of_bytes[i];
         end
    end
end

// The accumulated value is indexed at sum[NUM_BYTES-1]


问:
Compare two versions of a text file and find additions/removals with Ruby?
I am tracking changes in a web-page using Ruby. After I removed all html tags and blank lines, I get an array of lines which needs to be checked for additions/removals assuming that there may be repetitions. Could you recommend a good gem if it has been done already?

I could make the array lines unique and then the problem is avoided. But what if I need to track the repeated lines as well with respect to their position in the text?

答:
Sounds like a textbook case of where you'd want to use the Diff algorithm.

There's a 'diff' gem, although to be fair I've never used it: http://rubygems.org/gems/diff


问:
File sink in gnuradio
I am using USRP1 along with gnuradio. I want to store received data in a file using file sink. I would like to have an idea about the flow graph and with what extension I can store the file and how to read the data from the file. Thanks in advance.</p>

答: Did you search online? Pretty common task that many have documented. For example, check out Dynamic file names in GNU Radio, which links back to a page of examples including writing I&Q to file 2</p>

Title: File sink in gnuradio


问:
Pointer arithmetic using cast to "wrong" type
I have an array of structs, and I have a pointer to a member of one of those structs.  I would like to know which element of the array contains the member.  Here are two approaches:

```<code>#include <array>
#include <string>

struct xyz
{
    float x, y;
    std::string name;
};

typedef std::array<xyz, 3> triangle;

// return which vertex the given coordinate is part of
int vertex_a(const triangle& tri, const float* coord)
{
    return reinterpret_cast<const xyz*>(coord) - tri.data();
}

int vertex_b(const triangle& tri, const float* coord)
{
    std::ptrdiff_t offset = reinterpret_cast<const char*>(coord) - reinterpret_cast<const char*>(tri.data());
    return offset / sizeof(xyz);
}
</code>```

Here's a test driver:

```<code>#include <iostream>

int main()
{
    triangle tri{{{12.3, 45.6}, {7.89, 0.12}, {34.5, 6.78}}};
    for (const xyz& coord : tri) {
        std::cout
            << vertex_a(tri, &coord.x) << ' '
            << vertex_b(tri, &coord.x) << ' '
            << vertex_a(tri, &coord.y) << ' '
            << vertex_b(tri, &coord.y) << '\n';
    }
}
</code>```

Both approaches produce the expected results:

```<code>0 0 0 0
1 1 1 1
2 2 2 2
</code>```

But are they valid code?

In particular I wonder if vertex_a() might be invoking undefined behavior by casting float* y to xyz* since the result does not actually point to a struct xyz.  That concern led me to write vertex_b(), which I think is safe (is it?).

Here's the code generated by GCC 6.3 with -O3:

```<code>vertex_a(std::array<xyz, 3ul> const&, float const*):
    movq    %rsi, %rax
    movabsq $-3689348814741910323, %rsi ; 0xCCC...CD
    subq    %rdi, %rax
    sarq    $3, %rax
    imulq   %rsi, %rax

vertex_b(std::array<xyz, 3ul> const&, float const*):
    subq    %rdi, %rsi
    movabsq $-3689348814741910323, %rdx ; 0xCCC...CD
    movq    %rsi, %rax
    mulq    %rdx
    movq    %rdx, %rax
    shrq    $5, %rax
</code>```

答:
Neither is valid per the standard.

In vertex_a, you're allowed to convert a pointer to xyz::x to a pointer to xyz because they're pointer-interconvertible:

Two objects a and b are pointer-interconvertible if [...] one is a standard-layout class object and the other is the first non-static data member of that object [...]

If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a reinterpret_cast.

But you can't do the cast from a pointer to xyz::y to a pointer to xyz. That operation is undefined.

In vertex_b, you're subtracting two pointers to const char. That operation is defined in [expr.add] as:

If the expressions P and Q point to, respectively, elements x[i] and x[j] of the same array object x, the expression P - Q has the value i − j; otherwise, the behavior is undefined

Your expressions don't point to elements of an array of char, so the behavior is undefined.

Body:
I have an array of structs, and I have a pointer to a member of one of those structs.  I would like to know which element of the array contains the member.  Here are two approaches:

#include <array>
#include <string>

struct xyz
{
    float x, y;
    std::string name;
};

typedef std::array<xyz, 3> triangle;

// return which vertex the given coordinate is part of
int vertex_a(const triangle& tri, const float* coord)
{
    return reinterpret_cast<const xyz*>(coord) - tri.data();
}

int vertex_b(const triangle& tri, const float* coord)
{
    std::ptrdiff_t offset = reinterpret_cast<const char*>(coord) - reinterpret_cast<const char*>(tri.data());
    return offset / sizeof(xyz);
}

Here's a test driver:

#include <iostream>

int main()
{
    triangle tri{{{12.3, 45.6}, {7.89, 0.12}, {34.5, 6.78}}};
    for (const xyz& coord : tri) {
        std::cout
            << vertex_a(tri, &coord.x) << ' '
            << vertex_b(tri, &coord.x) << ' '
            << vertex_a(tri, &coord.y) << ' '
            << vertex_b(tri, &coord.y) << '\n';
    }
}

Both approaches produce the expected results:

0 0 0 0
1 1 1 1
2 2 2 2

But are they valid code?

In particular I wonder if vertex_a() might be invoking undefined behavior by casting float* y to xyz* since the result does not actually point to a struct xyz.  That concern led me to write vertex_b(), which I think is safe (is it?).

Here's the code generated by GCC 6.3 with -O3:

vertex_a(std::array<xyz, 3ul> const&, float const*):
    movq    %rsi, %rax
    movabsq $-3689348814741910323, %rsi ; 0xCCC...CD
    subq    %rdi, %rax
    sarq    $3, %rax
    imulq   %rsi, %rax

vertex_b(std::array<xyz, 3ul> const&, float const*):
    subq    %rdi, %rsi
    movabsq $-3689348814741910323, %rdx ; 0xCCC...CD
    movq    %rsi, %rax
    mulq    %rdx
    movq    %rdx, %rax
    shrq    $5, %rax


问:
How do you go into production with polymer project?
Is it common sense to use polymer build and then deploy the Application on your Web Server used for production?
Or does it make sense to actutally use polymer serve / polyserve as the Web Server?</p>

答:
The problem with polymer serve is that if it falls over it doesn't restart, leaving you with no web site.  Its real use is in development because it maps directories for you when you are developing a single element.

Also, how will you be handling ajax calls?

IN the past I have previously run my code (a bespoke node web server) in PM2.  These days I run using docker, and in particular docker-compose which also restarts the application if it fails.

EDIT The following is how I transpile on the fly code is copied (and then altered by me) from Google Polymer Teams "Polymer Server" and is therefore subject to the licence conditions given in that project.

```<code> * Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
</code>```

The code consists of some supporting functions like these

```<code>  const parse5 = require('parse5');
  const dom5 = require('dom5');
  const LRU = require('lru-cache');
  const babelCore = require('babel-core');
  const transformLog = require('debug')('web:transform');

  const babelTransformers = [
    'babel-plugin-transform-es2015-arrow-functions',
    'babel-plugin-transform-es2015-block-scoped-functions',
    'babel-plugin-transform-es2015-block-scoping',
    'babel-plugin-transform-es2015-classes',
    'babel-plugin-transform-es2015-computed-properties',
    'babel-plugin-transform-es2015-destructuring',
    'babel-plugin-transform-es2015-duplicate-keys',
    'babel-plugin-transform-es2015-for-of',
    'babel-plugin-transform-es2015-function-name',
    'babel-plugin-transform-es2015-literals',
    'babel-plugin-transform-es2015-object-super',
    'babel-plugin-transform-es2015-parameters',
    'babel-plugin-transform-es2015-shorthand-properties',
    'babel-plugin-transform-es2015-spread',
    'babel-plugin-transform-es2015-sticky-regex',
    'babel-plugin-transform-es2015-template-literals',
    'babel-plugin-transform-es2015-typeof-symbol',
    'babel-plugin-transform-es2015-unicode-regex',
    'babel-plugin-transform-regenerator',
  ].map((name) => require(name));

  const isInlineJavaScript = dom5.predicates.AND(
    dom5.predicates.hasTagName('script'),
    dom5.predicates.NOT(dom5.predicates.hasAttr('src')));

  const babelCompileCache = LRU({
    length: (n, key) => n.length + key.length
  });

  function compileHtml(source, location) {
    const document = parse5.parse(source);
    const scriptTags = dom5.queryAll(document, isInlineJavaScript);
    for (const scriptTag of scriptTags) {
      try {
        const script = dom5.getTextContent(scriptTag);
        const compiledScriptResult = compileScript(script);
        dom5.setTextContent(scriptTag, compiledScriptResult);
      } catch (e) {
        // By not setting textContent we keep the original script, which
        // might work. We may want to fail the request so a better error
        // shows up in the network panel of dev tools. If this is the main
        // page we could also render a message in the browser.
        //eslint-disable-next-line no-console
        console.warn(`Error compiling script in ${location}: ${e.message}`);
      }
    }
    return parse5.serialize(document);
  }
  function compileScript(script) {
    return babelCore
      .transform(script, {
        plugins: babelTransformers,
      }).code;
  }

  function transform(request, body, isHtml) {
    const source = body;
    const cached = babelCompileCache.get(source);
    if (cached !== undefined) {
      transformLog('using the cache');
      return cached;
    }
    if (isHtml) {
      transformLog('compiling html');
      body = compileHtml(source, request.path);
    } else {
      transformLog('compiling js');
      body = compileScript(source);
    }
    babelCompileCache.set(source, body);
    return body;
  }
</code>```

The meat though is the middleware which effectively inserts itself in the outgoing stream captures all the chunks of outgoing html and js files and transforms them if necessary.

```<code>  function transformResponse(transformNeeded) {
    return (req, res, next) => {
      let ended = false;

      let _shouldTransform = null;
      let isHtml = true;

      // Note: this function memorizes its result.
      function shouldTransform() {
        if (_shouldTransform == null) {
          const successful = res.statusCode >= 200 && res.statusCode < 300;
          if (successful) {
            const result = transformNeeded(req);
            isHtml = result.isHtml;
            _shouldTransform = !!result.transform;
          } else {
            _shouldTransform = false;
          }
        }
        return _shouldTransform;
      }

      const chunks = [];

      const _write = res.write;

      res.write = function( chunk, enc, cb) {
        if (ended) {
          _write.call(this, chunk, enc, cb);
          return false;
        }
        if (shouldTransform()) {
          const buffer = (typeof chunk === 'string') ? new Buffer(chunk,enc) : chunk;
          chunks.push(buffer);
          return true;
        }
        return _write.call(this, chunk, enc, cb);
      }.bind(res);

      const _end = res.end;
      res.end = function (chunk, enc, cb) {
        if (ended)
          return false;
        ended = true;
        if (shouldTransform()) {
          if (chunk) {
            const buffer = (typeof chunk === 'string') ? new Buffer(chunk,enc) : chunk;
            chunks.push(buffer);
          }
          const body = Buffer.concat(chunks).toString('utf8');
          let newBody = body;
          try {
            newBody = transform(req, body, isHtml);
          } catch (e) {
            //eslint-disable-next-line no-console
            console.warn('Error', e);
          }
          // TODO(justinfagnani): re-enable setting of content-length when we know
          // why it was causing truncated files. Could be multi-byte characters.
          // Assumes single-byte code points!
          // res.setHeader('Content-Length', `${newBody.length}`);
          this.removeHeader('Content-Length');
          return _end.call(this, newBody);
        }
        return _end.call(this,chunk, enc, cb);
      }.bind(res);
      next();
    };
  }
</code>```

This routine called transformNeeded which is as follows (this is the bit that detects the brower)

```<code>function transformNeeded(req) {
  const pathname = url.parse(req.url).pathname;
  const isHtml = pathname === '/' || pathname.slice(-5) === '.html';
  if (isHtml || pathname.slice(-3) === '.js') {
    //see if we need to compile as we have a .html or .js file
    const splitPathName = pathname.split('/');
    const isPolyfill = splitPathName.includes('webcomponentsjs') ||
      splitPathName.includes('promise-polyfill');
    if (!isPolyfill) {
      const browser = new UAParser(req.headers['user-agent']).getBrowser();
      const versionSplit = (browser.version || '').split('.');
      const [majorVersion, minorVersion] = versionSplit.map((v) => v ? parseInt(v, 10) : -1);
      const supportsES2015 = (browser.name === 'Chrome' && majorVersion >= 49) ||
        (browser.name === 'Chromium' && majorVersion >= 49) ||
        (browser.name === 'OPR' && majorVersion >= 36) ||
        (browser.name === 'Mobile Safari' && majorVersion >= 10) ||
        (browser.name === 'Safari' && majorVersion >= 10) ||
        // Note: The Edge user agent uses the EdgeHTML version, not the main
        // release version (e.g. EdgeHTML 15 corresponds to Edge 40). See
        // https://en.wikipedia.org/wiki/Microsoft_Edge#Release_history.
        //
        // Versions before 15.15063 may contain a JIT bug affecting ES6
        // constructors (see #161).
        (browser.name === 'Edge' &&
          (majorVersion > 15 || (majorVersion === 15 && minorVersion >= 15063))) ||
        (browser.name === 'Firefox' && majorVersion >= 51);
      requestLog(
        'Browser is %s version %d,%d - supports ES2015? ',
        browser.name,
        majorVersion,
        minorVersion,
        supportsES2015
      );
      return {transform: !supportsES2015, isHtml: isHtml};
    }
  }
  return {transform: false, isHtml: isHtml};
}
</code>```

Finally, I have to set up the routes before I establish the web server and then tell the web server to use the routes I have set up.

```<code>const Router = require('router');
//sets up my API routes
manager.setRoutes(router);
router.use('/', transformResponse(this.transformNeeded));
router.use('/', staticFiles(clientPath));
this._start(router);
</code>```

Body:
The problem with polymer serve is that if it falls over it doesn't restart, leaving you with no web site.  Its real use is in development because it maps directories for you when you are developing a single element.

Also, how will you be handling ajax calls?

IN the past I have previously run my code (a bespoke node web server) in PM2.  These days I run using docker, and in particular docker-compose which also restarts the application if it fails.

EDIT The following is how I transpile on the fly code is copied (and then altered by me) from Google Polymer Teams "Polymer Server" and is therefore subject to the licence conditions given in that project.

 * Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt

The code consists of some supporting functions like these

  const parse5 = require('parse5');
  const dom5 = require('dom5');
  const LRU = require('lru-cache');
  const babelCore = require('babel-core');
  const transformLog = require('debug')('web:transform');

  const babelTransformers = [
    'babel-plugin-transform-es2015-arrow-functions',
    'babel-plugin-transform-es2015-block-scoped-functions',
    'babel-plugin-transform-es2015-block-scoping',
    'babel-plugin-transform-es2015-classes',
    'babel-plugin-transform-es2015-computed-properties',
    'babel-plugin-transform-es2015-destructuring',
    'babel-plugin-transform-es2015-duplicate-keys',
    'babel-plugin-transform-es2015-for-of',
    'babel-plugin-transform-es2015-function-name',
    'babel-plugin-transform-es2015-literals',
    'babel-plugin-transform-es2015-object-super',
    'babel-plugin-transform-es2015-parameters',
    'babel-plugin-transform-es2015-shorthand-properties',
    'babel-plugin-transform-es2015-spread',
    'babel-plugin-transform-es2015-sticky-regex',
    'babel-plugin-transform-es2015-template-literals',
    'babel-plugin-transform-es2015-typeof-symbol',
    'babel-plugin-transform-es2015-unicode-regex',
    'babel-plugin-transform-regenerator',
  ].map((name) => require(name));

  const isInlineJavaScript = dom5.predicates.AND(
    dom5.predicates.hasTagName('script'),
    dom5.predicates.NOT(dom5.predicates.hasAttr('src')));

  const babelCompileCache = LRU({
    length: (n, key) => n.length + key.length
  });

  function compileHtml(source, location) {
    const document = parse5.parse(source);
    const scriptTags = dom5.queryAll(document, isInlineJavaScript);
    for (const scriptTag of scriptTags) {
      try {
        const script = dom5.getTextContent(scriptTag);
        const compiledScriptResult = compileScript(script);
        dom5.setTextContent(scriptTag, compiledScriptResult);
      } catch (e) {
        // By not setting textContent we keep the original script, which
        // might work. We may want to fail the request so a better error
        // shows up in the network panel of dev tools. If this is the main
        // page we could also render a message in the browser.
        //eslint-disable-next-line no-console
        console.warn(`Error compiling script in ${location}: ${e.message}`);
      }
    }
    return parse5.serialize(document);
  }
  function compileScript(script) {
    return babelCore
      .transform(script, {
        plugins: babelTransformers,
      }).code;
  }

  function transform(request, body, isHtml) {
    const source = body;
    const cached = babelCompileCache.get(source);
    if (cached !== undefined) {
      transformLog('using the cache');
      return cached;
    }
    if (isHtml) {
      transformLog('compiling html');
      body = compileHtml(source, request.path);
    } else {
      transformLog('compiling js');
      body = compileScript(source);
    }
    babelCompileCache.set(source, body);
    return body;
  }

The meat though is the middleware which effectively inserts itself in the outgoing stream captures all the chunks of outgoing html and js files and transforms them if necessary.

  function transformResponse(transformNeeded) {
    return (req, res, next) => {
      let ended = false;

      let _shouldTransform = null;
      let isHtml = true;

      // Note: this function memorizes its result.
      function shouldTransform() {
        if (_shouldTransform == null) {
          const successful = res.statusCode >= 200 && res.statusCode < 300;
          if (successful) {
            const result = transformNeeded(req);
            isHtml = result.isHtml;
            _shouldTransform = !!result.transform;
          } else {
            _shouldTransform = false;
          }
        }
        return _shouldTransform;
      }

      const chunks = [];

      const _write = res.write;

      res.write = function( chunk, enc, cb) {
        if (ended) {
          _write.call(this, chunk, enc, cb);
          return false;
        }
        if (shouldTransform()) {
          const buffer = (typeof chunk === 'string') ? new Buffer(chunk,enc) : chunk;
          chunks.push(buffer);
          return true;
        }
        return _write.call(this, chunk, enc, cb);
      }.bind(res);

      const _end = res.end;
      res.end = function (chunk, enc, cb) {
        if (ended)
          return false;
        ended = true;
        if (shouldTransform()) {
          if (chunk) {
            const buffer = (typeof chunk === 'string') ? new Buffer(chunk,enc) : chunk;
            chunks.push(buffer);
          }
          const body = Buffer.concat(chunks).toString('utf8');
          let newBody = body;
          try {
            newBody = transform(req, body, isHtml);
          } catch (e) {
            //eslint-disable-next-line no-console
            console.warn('Error', e);
          }
          // TODO(justinfagnani): re-enable setting of content-length when we know
          // why it was causing truncated files. Could be multi-byte characters.
          // Assumes single-byte code points!
          // res.setHeader('Content-Length', `${newBody.length}`);
          this.removeHeader('Content-Length');
          return _end.call(this, newBody);
        }
        return _end.call(this,chunk, enc, cb);
      }.bind(res);
      next();
    };
  }

This routine called transformNeeded which is as follows (this is the bit that detects the brower)

function transformNeeded(req) {
  const pathname = url.parse(req.url).pathname;
  const isHtml = pathname === '/' || pathname.slice(-5) === '.html';
  if (isHtml || pathname.slice(-3) === '.js') {
    //see if we need to compile as we have a .html or .js file
    const splitPathName = pathname.split('/');
    const isPolyfill = splitPathName.includes('webcomponentsjs') ||
      splitPathName.includes('promise-polyfill');
    if (!isPolyfill) {
      const browser = new UAParser(req.headers['user-agent']).getBrowser();
      const versionSplit = (browser.version || '').split('.');
      const [majorVersion, minorVersion] = versionSplit.map((v) => v ? parseInt(v, 10) : -1);
      const supportsES2015 = (browser.name === 'Chrome' && majorVersion >= 49) ||
        (browser.name === 'Chromium' && majorVersion >= 49) ||
        (browser.name === 'OPR' && majorVersion >= 36) ||
        (browser.name === 'Mobile Safari' && majorVersion >= 10) ||
        (browser.name === 'Safari' && majorVersion >= 10) ||
        // Note: The Edge user agent uses the EdgeHTML version, not the main
        // release version (e.g. EdgeHTML 15 corresponds to Edge 40). See
        // https://en.wikipedia.org/wiki/Microsoft_Edge#Release_history.
        //
        // Versions before 15.15063 may contain a JIT bug affecting ES6
        // constructors (see #161).
        (browser.name === 'Edge' &&
          (majorVersion > 15 || (majorVersion === 15 && minorVersion >= 15063))) ||
        (browser.name === 'Firefox' && majorVersion >= 51);
      requestLog(
        'Browser is %s version %d,%d - supports ES2015? ',
        browser.name,
        majorVersion,
        minorVersion,
        supportsES2015
      );
      return {transform: !supportsES2015, isHtml: isHtml};
    }
  }
  return {transform: false, isHtml: isHtml};
}

Finally, I have to set up the routes before I establish the web server and then tell the web server to use the routes I have set up.

const Router = require('router');
//sets up my API routes
manager.setRoutes(router);
router.use('/', transformResponse(this.transformNeeded));
router.use('/', staticFiles(clientPath));
this._start(router);


问:
PHP find max between variables
I'm trying to find out wich variable is bigger (those are all integers):

```<code><?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;

echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
</code>```

I tried with max but it gives the value and not the $varName.

I want to get the name of the variable and if there are two that are equal I need both.

Thanks for the help.

As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...

```<code>  $confronto = [
    'ectoA' => $ectoA,
    'ectoB' => $ectoB,
    'endoA' => $endoA,
    'endoB' => $endoB,
    'mesoA' => $mesoA,
    'mesoB' => $mesoB,
];

$result= array_keys($confronto,max($confronto));

$neurotipo = $result[0];
echo $neurotipo;
</code>```

I want endoA and endoB to be identified...

答:
As per the documentation,  Since the two values are equal, the order they are provided determines the result $endoA is the biggest here.

But I am not sure your intention is to find the biggest value or which variable is the highest

Title: PHP find max between variables

Body:
I'm trying to find out wich variable is bigger (those are all integers):

<?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;

echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);

I tried with max but it gives the value and not the $varName.

I want to get the name of the variable and if there are two that are equal I need both.

Thanks for the help.

As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...

  $confronto = [
    'ectoA' => $ectoA,
    'ectoB' => $ectoB,
    'endoA' => $endoA,
    'endoB' => $endoB,
    'mesoA' => $mesoA,
    'mesoB' => $mesoB,
];

$result= array_keys($confronto,max($confronto));

$neurotipo = $result[0];
echo $neurotipo;

I want endoA and endoB to be identified...


问:
Iterating over DS.hasMany in Ember data
I have a real struggle with Ember.

In my model I have an attribute:

options: DS.hasMany('UserOptions', {async: false})

In a view linked to this model I can easily access this property by e.g.:

```<code>{{#each options AS |option|}}
    something....
{{/each}}
</code>```

and that works like a charm.

However when I try to access this model value in controller with:
this.get('model.options')
instead of getting a lovely array of payment options, I get an ember model array of objects, and there's no way I can access the actual data.

Do you guys have any idea how do I access this data in controller and process it?

Thanks!

答:
this.get('model.options') will give you RSVP.Promise, so you need to work with asynchronous code. Use:

```<code>this.get('model.options').then(options => {
    options.forEach(option => {
        // do what you need with option
    })
});
</code>```

Title: Iterating over DS.hasMany in Ember data

Body:
I have a real struggle with Ember.

In my model I have an attribute:

options: DS.hasMany('UserOptions', {async: false})

In a view linked to this model I can easily access this property by e.g.:

{{#each options AS |option|}}
    something....
{{/each}}

and that works like a charm.

However when I try to access this model value in controller with:
this.get('model.options')
instead of getting a lovely array of payment options, I get an ember model array of objects, and there's no way I can access the actual data.

Do you guys have any idea how do I access this data in controller and process it?

Thanks!

Body:
this.get('model.options') will give you RSVP.Promise, so you need to work with asynchronous code. Use:

this.get('model.options').then(options => {
    options.forEach(option => {
        // do what you need with option
    })
});


问:
Angular : http Interceptor is not getting injected in config block
I have created a simple http interceptor with which I intend to log the requests and responses made. Issue is that it is undefined in config block which gets executed first and throws error because of which module couldn't get instantiated. Below is the code used :

```<code>authApp
.factory("httpInterceptor",function($log){
    var httpInterceptor = {};

    httpInterceptor.request = function(config){
        $log.info("request is being made to " + config.url);
        return config;
    };

    httpInterceptor.response = function(config){
        $log.info("request to URL : " + config.url + " is completed
        now.");
        return config;
    };

    return httpInterceptor;
})
.config(function($httpProvider){
    // Http Interceptor
    $httpProvider.interceptors.push(httpInterceptor);
 });
</code>```

Thanks in advance !!

答:
Your code seems correct, except a particular line where you are pushing your brand new interceptor to the list of $httpProvider's interceptors.

```<code>$httpProvider.interceptors.push(httpInterceptor);
</code>```

This line doesn't know what httpInterceptor is because it is defined as an angular factory. Change it to

```<code>$httpProvider.interceptors.push('httpInterceptor'); // Note the quotes around it.
</code>```

and retry.

Body:
I have created a simple http interceptor with which I intend to log the requests and responses made. Issue is that it is undefined in config block which gets executed first and throws error because of which module couldn't get instantiated. Below is the code used :

authApp
.factory("httpInterceptor",function($log){
    var httpInterceptor = {};

    httpInterceptor.request = function(config){
        $log.info("request is being made to " + config.url);
        return config;
    };

    httpInterceptor.response = function(config){
        $log.info("request to URL : " + config.url + " is completed
        now.");
        return config;
    };

    return httpInterceptor;
})
.config(function($httpProvider){
    // Http Interceptor
    $httpProvider.interceptors.push(httpInterceptor);
 });

Thanks in advance !!

Body:
Your code seems correct, except a particular line where you are pushing your brand new interceptor to the list of $httpProvider's interceptors.

$httpProvider.interceptors.push(httpInterceptor);

This line doesn't know what httpInterceptor is because it is defined as an angular factory. Change it to

$httpProvider.interceptors.push('httpInterceptor'); // Note the quotes around it.

and retry.