问:
How do I remove a character from strings of different lengths with sql? Intersystems cache sql
I have a column of strings that have an '&' at the beginning and end of each one that I need to remove for a Crystal report I'm creating. I'm writing the SQL code outside of Crystal I am using Intersystems Cache SQL. Below is an example:

```<code>&This&         This
&is&           is
&What&         what
&it&           I
&looks&        need
&like&         it
&now&          to
               look
               like
</code>```

Any suggestions would be greatly appreciated!!!

答:
Assuming the ampersands are always positioned as both the leading and trailing characters, here's at least maybe a start. Use a combination of SUBSTR (or SUBSTRING, if using stream data) and LENGTH, like so:

```<code>SELECT SUBSTR((SELECT column FROM table), 2, LENGTH(SELECT column FROM table) - 2)
</code>```

This should return a substring that starts counting at the 2nd character [of the original string, given by the first sub-expression/argument to SUBSTR], counting up for the total number of characters [of the original string] less 2 (i.e. less the two ampersands).

If you need to including trailing blanks and/or the string termination character, you may need to use a different variation of the LENGTH function. See resources for details on these functions and their variants:

https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls?KEY=RSQL_substr

https://cedocs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=RSQL_length

Body:
I have a column of strings that have an '&' at the beginning and end of each one that I need to remove for a Crystal report I'm creating. I'm writing the SQL code outside of Crystal I am using Intersystems Cache SQL. Below is an example:

&This&         This
&is&           is
&What&         what
&it&           I
&looks&        need
&like&         it
&now&          to
               look
               like

Any suggestions would be greatly appreciated!!!

Body:
Assuming the ampersands are always positioned as both the leading and trailing characters, here's at least maybe a start. Use a combination of SUBSTR (or SUBSTRING, if using stream data) and LENGTH, like so:

SELECT SUBSTR((SELECT column FROM table), 2, LENGTH(SELECT column FROM table) - 2)

This should return a substring that starts counting at the 2nd character [of the original string, given by the first sub-expression/argument to SUBSTR], counting up for the total number of characters [of the original string] less 2 (i.e. less the two ampersands).

If you need to including trailing blanks and/or the string termination character, you may need to use a different variation of the LENGTH function. See resources for details on these functions and their variants:

https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls?KEY=RSQL_substr

https://cedocs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=RSQL_length


来源: stackexchange

问:
Reactive Forms Not Updating Value In Form Field Angular 7
I'm having an issue where the values in my formgroup is not being updated on submission.

I have formgroup that brings in values from an api, (which is working) but when I am trying to update the value and pass it back, the values are not being updated. I'm lost on what I am doing wrong.

I'm using reactive forms with Angular 7.

modify-view-action.component.html

```<code>    <div fxLayout="column" fxLayoutGap="25px" class="modify-view-container">
  <mat-card class="view-settings-descrpition-card">
    <mat-card-content fxLayout="column">

      <form [formGroup]="modifyActionForm">
        <div class="container" fxLayout="row" fxLayoutGap="25px">
          <div class="column1" fxLayout="column">
            <p>Folder: {{dbrAction.FolderTag.Value}}</p>
            <p>Primary Table: {{dbrAction.PrimaryTable}}</p>
            <p>Special Use: {{dbrAction.SpecialUse}}</p>
            <mat-form-field>
              <mat-label>Name</mat-label>
              <input matInput formControlName="ActionName">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Keywords</mat-label>
              <input matInput formControlName="Keywords">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Description</mat-label>
              <input matInput formControlName="Description">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Icon</mat-label>
              <mat-select formControlName="Icon" ngDefaultControl>
                <mat-option formControlName="Icon"
                  ngDefaultControl>
                  {{dbrAction.Icon}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Priority</mat-label>
              <input matInput formControlName="Priority">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Title Font Size</mat-label>
              <mat-select formControlName="TitleFontSize" [value]="dbrAction.TitleFontSize" ngDefaultControl>
                <mat-option formControlName="TitleFontSize" [value]="dbrAction.TitleFontSize" ngDefaultControl>
                  {{dbrAction.TitleFontSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Subtitle Font Size</mat-label>
              <mat-select formControlName="SubtitleFontSize" [value]="dbrAction.SubtitleFontSize" ngDefaultControl>
                <mat-option formControlName="SubtitleFontSize" [value]="dbrAction.SubtitleFontSize" ngDefaultControl>
                  {{dbrAction.SubtitleFontSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Print Title Font Size</mat-label>
              <mat-select formControlName="PrintTitleSize" [value]="dbrAction.PrintTitleSize" ngDefaultControl>
                <mat-option formControlName="PrintTitleSize" [value]="dbrAction.PrintTitleSize" ngDefaultControl>
                  {{dbrAction.PrintTitleSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Print Subtitle Font Size</mat-label>
              <mat-select formControlName="PrintSubtitleSize" [value]="dbrAction.PrintSubtitleSize" ngDefaultControl>
                <mat-option formControlName="PrintSubtitleSize" [value]="dbrAction.PrintSubtitleSize" ngDefaultControl>
                  {{dbrAction.PrintSubtitleSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <!-- <mat-form-field>
              <mat-checkbox matInput formControlName="IsActive" [(ngModel)]="dbrAction.IsActive" [value]="dbrAction.IsActive" [labelPosition]="labelPosition">Is Active: </mat-checkbox>
            </mat-form-field> -->
          </div>
        </div>
      </form>
</code>```

modify-view-action.component.ts

```<code>    import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'modify-view-action',
  templateUrl: './modify-view-action.component.html',
  styleUrls: ['./modify-view-action.component.scss']
})
export class ModifyViewActionComponent implements OnInit {
  objectData: any;

  constructor(private fb: FormBuilder) { }

  dbrAction: any;
  labelPosition: 'before' | 'after' = 'before';
  modifyActionForm: FormGroup;

  ngOnInit() {
    this.initData();
    this.modifyActionForm = this.fb.group({
    FolderTag: new FormControl(this.dbrAction.FolderTag),
    PrimaryTable: new FormControl(this.dbrAction.PrimaryTable),
    SpecialUse: new FormControl(this.dbrAction.SpecialUse),
    ActionName: new FormControl(this.dbrAction.ActionName),
    Keywords: new FormControl(this.dbrAction.Keywords),
    Description: new FormControl(this.dbrAction.Description),
    Icon: new FormControl(this.dbrAction.Icon),
    Priority: new FormControl(this.dbrAction.Priority),
    TitleFontSize: new FormControl(this.dbrAction.TitleFontSize),
    SubtitleFontSize: new FormControl(this.dbrAction.SubtitleFontSize),
    PrintTitleSize: new FormControl(this.dbrAction.PrintTitleSize),
    PrintSubtitleSize: new FormControl(this.dbrAction.PrintSubtitleSize),
    IsActive: new FormControl(this.dbrAction.IsActive)
    });

    this.objectData = this.modifyActionForm.value;
    console.log(this.objectData);
  }

  get f() { return this.modifyActionForm.controls; }

initData() {
    this.dbrAction = JSON.parse(localStorage.getItem('DbrAction'));
  }
}
</code>```

答:
Try this i hope this will help you.</p>

```<code>ngOnInit() {
    this.initData();
    this.modifyActionForm = this.fb.group({
    FolderTag: [this.dbrAction.FolderTag],
    PrimaryTable: [this.dbrAction.PrimaryTable],
    SpecialUse: [this.dbrAction.SpecialUse],
    ActionName:[this.dbrAction.ActionName],
    Keywords: [this.dbrAction.Keywords],
    Description: [this.dbrAction.Description],
    Icon: [this.dbrAction.Icon],
    Priority: [this.dbrAction.Priority],
    TitleFontSize: [this.dbrAction.TitleFontSize],
    SubtitleFontSize: [this.dbrAction.SubtitleFontSize],
    PrintTitleSize: [this.dbrAction.PrintTitleSize],
    PrintSubtitleSize: [this.dbrAction.PrintSubtitleSize],
    IsActive: [this.dbrAction.IsActive]
    });

    this.objectData = this.modifyActionForm.value;
    console.log(this.objectData);
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having an issue where the values in my formgroup is not being updated on submission.

I have formgroup that brings in values from an api, (which is working) but when I am trying to update the value and pass it back, the values are not being updated. I'm lost on what I am doing wrong.

I'm using reactive forms with Angular 7.

modify-view-action.component.html

  <mat-card class="view-settings-descrpition-card">
    <mat-card-content fxLayout="column">

      <form [formGroup]="modifyActionForm">

Folder: {{dbrAction.FolderTag.Value}}

Primary Table: {{dbrAction.PrimaryTable}}

Special Use: {{dbrAction.SpecialUse}}

            <mat-form-field>
              <mat-label>Name</mat-label>
              <input matInput formControlName="ActionName">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Keywords</mat-label>
              <input matInput formControlName="Keywords">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Description</mat-label>
              <input matInput formControlName="Description">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Icon</mat-label>
              <mat-select formControlName="Icon" ngDefaultControl>
                <mat-option formControlName="Icon"
                  ngDefaultControl>
                  {{dbrAction.Icon}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Priority</mat-label>
              <input matInput formControlName="Priority">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Title Font Size</mat-label>
              <mat-select formControlName="TitleFontSize" [value]="dbrAction.TitleFontSize" ngDefaultControl>
                <mat-option formControlName="TitleFontSize" [value]="dbrAction.TitleFontSize" ngDefaultControl>
                  {{dbrAction.TitleFontSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Subtitle Font Size</mat-label>
              <mat-select formControlName="SubtitleFontSize" [value]="dbrAction.SubtitleFontSize" ngDefaultControl>
                <mat-option formControlName="SubtitleFontSize" [value]="dbrAction.SubtitleFontSize" ngDefaultControl>
                  {{dbrAction.SubtitleFontSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Print Title Font Size</mat-label>
              <mat-select formControlName="PrintTitleSize" [value]="dbrAction.PrintTitleSize" ngDefaultControl>
                <mat-option formControlName="PrintTitleSize" [value]="dbrAction.PrintTitleSize" ngDefaultControl>
                  {{dbrAction.PrintTitleSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Print Subtitle Font Size</mat-label>
              <mat-select formControlName="PrintSubtitleSize" [value]="dbrAction.PrintSubtitleSize" ngDefaultControl>
                <mat-option formControlName="PrintSubtitleSize" [value]="dbrAction.PrintSubtitleSize" ngDefaultControl>
                  {{dbrAction.PrintSubtitleSize}}
                </mat-option>
              </mat-select>
            </mat-form-field>

      </form>

modify-view-action.component.ts

    import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'modify-view-action',
  templateUrl: './modify-view-action.component.html',
  styleUrls: ['./modify-view-action.component.scss']
})
export class ModifyViewActionComponent implements OnInit {
  objectData: any;

  constructor(private fb: FormBuilder) { }

  dbrAction: any;
  labelPosition: 'before' | 'after' = 'before';
  modifyActionForm: FormGroup;

  ngOnInit() {
    this.initData();
    this.modifyActionForm = this.fb.group({
    FolderTag: new FormControl(this.dbrAction.FolderTag),
    PrimaryTable: new FormControl(this.dbrAction.PrimaryTable),
    SpecialUse: new FormControl(this.dbrAction.SpecialUse),
    ActionName: new FormControl(this.dbrAction.ActionName),
    Keywords: new FormControl(this.dbrAction.Keywords),
    Description: new FormControl(this.dbrAction.Description),
    Icon: new FormControl(this.dbrAction.Icon),
    Priority: new FormControl(this.dbrAction.Priority),
    TitleFontSize: new FormControl(this.dbrAction.TitleFontSize),
    SubtitleFontSize: new FormControl(this.dbrAction.SubtitleFontSize),
    PrintTitleSize: new FormControl(this.dbrAction.PrintTitleSize),
    PrintSubtitleSize: new FormControl(this.dbrAction.PrintSubtitleSize),
    IsActive: new FormControl(this.dbrAction.IsActive)
    });

    this.objectData = this.modifyActionForm.value;
    console.log(this.objectData);
  }

  get f() { return this.modifyActionForm.controls; }

initData() {
    this.dbrAction = JSON.parse(localStorage.getItem('DbrAction'));
  }
}

Body:
Try this i hope this will help you.

ngOnInit() {
    this.initData();
    this.modifyActionForm = this.fb.group({
    FolderTag: [this.dbrAction.FolderTag],
    PrimaryTable: [this.dbrAction.PrimaryTable],
    SpecialUse: [this.dbrAction.SpecialUse],
    ActionName:[this.dbrAction.ActionName],
    Keywords: [this.dbrAction.Keywords],
    Description: [this.dbrAction.Description],
    Icon: [this.dbrAction.Icon],
    Priority: [this.dbrAction.Priority],
    TitleFontSize: [this.dbrAction.TitleFontSize],
    SubtitleFontSize: [this.dbrAction.SubtitleFontSize],
    PrintTitleSize: [this.dbrAction.PrintTitleSize],
    PrintSubtitleSize: [this.dbrAction.PrintSubtitleSize],
    IsActive: [this.dbrAction.IsActive]
    });

    this.objectData = this.modifyActionForm.value;
    console.log(this.objectData);
  }


问:
Pandas/datetime issue
I have a pandas dataset where by I am trying to relate two columns... One (df['IssueDatetime']) is properly formatted as a date time, the other is only has the %dd/%HH (df['forecastTime']) :

```<code>            IssueDatetime                   Regions forecastTime WindDirSpeed
0     2019-01-01 06:00:00                EAST COAST        01/06         NW25
1     2019-01-01 06:00:00                EAST COAST        01/15         SW15
2     2019-01-01 06:00:00                EAST COAST        02/00         SE25
3     2019-01-01 06:00:00                EAST COAST        02/06      SE35-45
4     2019-01-01 06:00:00                EAST COAST        02/15         SW40
...                   ...                       ...          ...          ...
12292 2019-12-30 06:00:00  SOUTHEASTERN GRAND BANKS        01/00       N15-20
12293 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        30/06      NW15-20
12294 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        31/00          N25
12295 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        31/15       N15-20
12296 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        01/00     VRB10-15
</code>```

Is it possible to relate the df['IssueDatetime'] to the df['forecastTime'], for a result such that:

```<code>            IssueDatetime                   Regions     forecastTime             WindDirSpeed
0     2019-01-01 06:00:00                EAST COAST      2019-01-01 06:00:00             NW25
1     2019-01-01 06:00:00                EAST COAST      2019-01-01 15:00:00             SW15
2     2019-01-01 06:00:00                EAST COAST      2019-01-02 00:00:00             SE25
3     2019-01-01 06:00:00                EAST COAST      2019-01-02 06:00:00          SE35-45
</code>```

The issue arises when relating the columns at the end of the months. Any suggestions would be helpful.

答:
This is like the previous answer, but with 2 modifications:

the forecast dates are now explicitly the issue timestamps but with the days and hours values replaced

in the case of issue dates near the end of the month, a relativedelta ensures that the forecast wraps to the next month (I'm assuming that's what you want?)

```<code>import pandas as pd
from dateutil.relativedelta import relativedelta

#replicating your data
issuetimes = ['2019-01-01 06:00:00']*5 + ['2019-12-30 06:00:00']*5
forecasts = ['01/06','01/15','02/00','02/06','02/15',
             '01/00','30/06','31/00','31/15','01/00',]

def replace_days_hours(row):
    row['forecastTime'] = row['IssueDatetime'].replace(day=row['forecastTime'].day,
                                                       hour=row['forecastTime'].hour,)
    if row['forecastTime'] < row['IssueDatetime']:
        row['forecastTime'] += relativedelta(months=1)
    return row

df = pd.DataFrame({'IssueDatetime':issuetimes,'forecastTime':forecasts})
df['IssueDatetime'] = pd.to_datetime(df['IssueDatetime'])
df['forecastTime'] = pd.to_datetime(df['forecastTime'], format='%d/%H')
df = df.apply(replace_days_hours,axis=1)
</code>```

Output:

```<code>        IssueDatetime        forecastTime
0 2019-01-01 06:00:00 2019-01-01 06:00:00
1 2019-01-01 06:00:00 2019-01-01 15:00:00
2 2019-01-01 06:00:00 2019-01-02 00:00:00
3 2019-01-01 06:00:00 2019-01-02 06:00:00
4 2019-01-01 06:00:00 2019-01-02 15:00:00
5 2019-12-30 06:00:00 2020-01-01 00:00:00
6 2019-12-30 06:00:00 2019-12-30 06:00:00
7 2019-12-30 06:00:00 2019-12-31 00:00:00
8 2019-12-30 06:00:00 2019-12-31 15:00:00
9 2019-12-30 06:00:00 2020-01-01 00:00:00
</code>```

Title: Pandas/datetime issue

Body:
I have a pandas dataset where by I am trying to relate two columns... One (df['IssueDatetime']) is properly formatted as a date time, the other is only has the %dd/%HH (df['forecastTime']) :

            IssueDatetime                   Regions forecastTime WindDirSpeed
0     2019-01-01 06:00:00                EAST COAST        01/06         NW25
1     2019-01-01 06:00:00                EAST COAST        01/15         SW15
2     2019-01-01 06:00:00                EAST COAST        02/00         SE25
3     2019-01-01 06:00:00                EAST COAST        02/06      SE35-45
4     2019-01-01 06:00:00                EAST COAST        02/15         SW40
...                   ...                       ...          ...          ...
12292 2019-12-30 06:00:00  SOUTHEASTERN GRAND BANKS        01/00       N15-20
12293 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        30/06      NW15-20
12294 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        31/00          N25
12295 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        31/15       N15-20
12296 2019-12-30 06:00:00  SOUTHWESTERN GRAND BANKS        01/00     VRB10-15

Is it possible to relate the df['IssueDatetime'] to the df['forecastTime'], for a result such that:

            IssueDatetime                   Regions     forecastTime             WindDirSpeed
0     2019-01-01 06:00:00                EAST COAST      2019-01-01 06:00:00             NW25
1     2019-01-01 06:00:00                EAST COAST      2019-01-01 15:00:00             SW15
2     2019-01-01 06:00:00                EAST COAST      2019-01-02 00:00:00             SE25
3     2019-01-01 06:00:00                EAST COAST      2019-01-02 06:00:00          SE35-45

The issue arises when relating the columns at the end of the months. Any suggestions would be helpful.

Body:
This is like the previous answer, but with 2 modifications:

the forecast dates are now explicitly the issue timestamps but with the days and hours values replaced

in the case of issue dates near the end of the month, a relativedelta ensures that the forecast wraps to the next month (I'm assuming that's what you want?)

import pandas as pd
from dateutil.relativedelta import relativedelta

#replicating your data
issuetimes = ['2019-01-01 06:00:00']*5 + ['2019-12-30 06:00:00']*5
forecasts = ['01/06','01/15','02/00','02/06','02/15',
             '01/00','30/06','31/00','31/15','01/00',]

def replace_days_hours(row):
    row['forecastTime'] = row['IssueDatetime'].replace(day=row['forecastTime'].day,
                                                       hour=row['forecastTime'].hour,)
    if row['forecastTime'] < row['IssueDatetime']:
        row['forecastTime'] += relativedelta(months=1)
    return row

df = pd.DataFrame({'IssueDatetime':issuetimes,'forecastTime':forecasts})
df['IssueDatetime'] = pd.to_datetime(df['IssueDatetime'])
df['forecastTime'] = pd.to_datetime(df['forecastTime'], format='%d/%H')
df = df.apply(replace_days_hours,axis=1)

Output:

        IssueDatetime        forecastTime
0 2019-01-01 06:00:00 2019-01-01 06:00:00
1 2019-01-01 06:00:00 2019-01-01 15:00:00
2 2019-01-01 06:00:00 2019-01-02 00:00:00
3 2019-01-01 06:00:00 2019-01-02 06:00:00
4 2019-01-01 06:00:00 2019-01-02 15:00:00
5 2019-12-30 06:00:00 2020-01-01 00:00:00
6 2019-12-30 06:00:00 2019-12-30 06:00:00
7 2019-12-30 06:00:00 2019-12-31 00:00:00
8 2019-12-30 06:00:00 2019-12-31 15:00:00
9 2019-12-30 06:00:00 2020-01-01 00:00:00


问:
Why doesnt jsch execute the scp command?
I am trying to transfer a file from local to remote with scp. Local is windows(OpenSSH is running as service) and remote is FreeBSD(rsa key are setup).
For this i am using Jsch library.

```<code>try {
        if (ses == null) ses = fsaTo.getSession();
        channel = ses.openChannel("exec");
        String cmd = "scp "+ UserHostIdentity.getTransferUser(fsaFrom.getSystem()) + "@"
                + UserHostIdentity.getTransferHost(fsaFrom.getSystem()) + ":"
                + from + " "
                + to;
        ((ChannelExec)channel).setCommand(cmd);
        ((ChannelExec)channel).setErrStream(System.err);
        channel.connect();
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

The command cmd I tested it manually executing it and it worked. This is how I start up the session:

```<code>JSch jsch = new JSch();
    try {
        sshSession = jsch.getSession(UserHostIdentity.getTransferUser(fs), UserHostIdentity.getTransferHost(fs),22);
        UserInfo lui = UserHostIdentity.getTransferUserInfo(fs);
        sshSession.setUserInfo(lui);
        sshSession.setConfig("StrictHostKeyChecking", "no");
        sshSession.connect();
    } catch (JSchException e) {
        logger.error("Could not access fileserver.");
        throw new RuntimeException(e);
    }
</code>```

The issue is after calling channel.connect() nothing happens, no error, nothing.
In the same context the following code executes "sha256 -q " + filePath and returns correct results:

```<code>public String doCommand(String cmd) {
    if (sshSession == null) {
        initiateConnection();
    }

    Channel channel;
    String result = "";
    try {
        channel = sshSession.openChannel("exec");
        ((ChannelExec)channel).setCommand(cmd);
        channel.setInputStream(null);
        ((ChannelExec)channel).setErrStream(System.err);

        InputStream input = channel.getInputStream();
        channel.connect();
        InputStreamReader inputReader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(inputReader);
        String line = null;

        while((line = bufferedReader.readLine()) != null){
            result = line;
        }
        bufferedReader.close();
        inputReader.close();
        channel.disconnect();
    } catch (JSchException e) {
        logger.error("Problem with communication to Fileserver.");
        throw new RuntimeException(e);
    } catch (IOException e) {
        logger.error("Problem with command stream.");
        throw new RuntimeException(e);
    }
    return result;
}
</code>```

My question is, why doesnt it work with the scp command.

答:
Why not use SFTP if you are already using JSch library?

See the sample code which is uploading file with JSch SFTP:

```<code>public void uploadFile(File file, String location) {
    ChannelSftp channelSftp = null;
    try {
        channelSftp = (ChannelSftp)connect();
        if(location.startsWith(ROOT_DIR)) {
            channelSftp.cd(ROOT_DIR);
        }
        final List<String> directories = Splitter.on(File.separatorChar).omitEmptyStrings().splitToList(location);
        for(String dir : directories) {
            try {
                channelSftp.ls(dir);
            } catch (SftpException e) {
                channelSftp.mkdir(dir);
            }
            channelSftp.cd(dir);
        }
        if(LOGGER.isDebugEnabled()) {
            LOGGER.debug("Uploading file " + file.getPath() + " in " + location);
        }
        channelSftp.put(new FileInputStream(file), file.getName());
    } catch(Throwable e) {
        throw new RuntimeException("Upload file " + file.getPath() + " failed.", e);
    } finally {
        disconnect(channelSftp);
    }
}
</code>```

Body:
I am trying to transfer a file from local to remote with scp. Local is windows(OpenSSH is running as service) and remote is FreeBSD(rsa key are setup).
For this i am using Jsch library.

try {
        if (ses == null) ses = fsaTo.getSession();
        channel = ses.openChannel("exec");
        String cmd = "scp "+ UserHostIdentity.getTransferUser(fsaFrom.getSystem()) + "@"
                + UserHostIdentity.getTransferHost(fsaFrom.getSystem()) + ":"
                + from + " "
                + to;
        ((ChannelExec)channel).setCommand(cmd);
        ((ChannelExec)channel).setErrStream(System.err);
        channel.connect();
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

The command cmd I tested it manually executing it and it worked. This is how I start up the session:

JSch jsch = new JSch();
    try {
        sshSession = jsch.getSession(UserHostIdentity.getTransferUser(fs), UserHostIdentity.getTransferHost(fs),22);
        UserInfo lui = UserHostIdentity.getTransferUserInfo(fs);
        sshSession.setUserInfo(lui);
        sshSession.setConfig("StrictHostKeyChecking", "no");
        sshSession.connect();
    } catch (JSchException e) {
        logger.error("Could not access fileserver.");
        throw new RuntimeException(e);
    }

The issue is after calling channel.connect() nothing happens, no error, nothing.
In the same context the following code executes "sha256 -q " + filePath and returns correct results:

public String doCommand(String cmd) {
    if (sshSession == null) {
        initiateConnection();
    }

    Channel channel;
    String result = "";
    try {
        channel = sshSession.openChannel("exec");
        ((ChannelExec)channel).setCommand(cmd);
        channel.setInputStream(null);
        ((ChannelExec)channel).setErrStream(System.err);

        InputStream input = channel.getInputStream();
        channel.connect();
        InputStreamReader inputReader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(inputReader);
        String line = null;

        while((line = bufferedReader.readLine()) != null){
            result = line;
        }
        bufferedReader.close();
        inputReader.close();
        channel.disconnect();
    } catch (JSchException e) {
        logger.error("Problem with communication to Fileserver.");
        throw new RuntimeException(e);
    } catch (IOException e) {
        logger.error("Problem with command stream.");
        throw new RuntimeException(e);
    }
    return result;
}

My question is, why doesnt it work with the scp command.

Body:
Why not use SFTP if you are already using JSch library?

See the sample code which is uploading file with JSch SFTP:

public void uploadFile(File file, String location) {
    ChannelSftp channelSftp = null;
    try {
        channelSftp = (ChannelSftp)connect();
        if(location.startsWith(ROOT_DIR)) {
            channelSftp.cd(ROOT_DIR);
        }
        final List<String> directories = Splitter.on(File.separatorChar).omitEmptyStrings().splitToList(location);
        for(String dir : directories) {
            try {
                channelSftp.ls(dir);
            } catch (SftpException e) {
                channelSftp.mkdir(dir);
            }
            channelSftp.cd(dir);
        }
        if(LOGGER.isDebugEnabled()) {
            LOGGER.debug("Uploading file " + file.getPath() + " in " + location);
        }
        channelSftp.put(new FileInputStream(file), file.getName());
    } catch(Throwable e) {
        throw new RuntimeException("Upload file " + file.getPath() + " failed.", e);
    } finally {
        disconnect(channelSftp);
    }
}


问:
csrf in react and rails
I want to use csrf token while using post request. For that in api controller I have used protect_from_forgery with: :null_session at the top.

But how should I use that in react.

Also I could not found any good article on this.

```<code>fetch('/api/v1/posts', {
      method: 'post',
      body: JSON.stringify(postdata),
      headers: { 'Content-Type': 'application/json' },
    })
</code>```

答:
As I understand it, you need to pass the X-CSRF-TOKEN as a header to Rails when making the call. You can use document.querySelector('[name="csrf-token"]').content to get the token:

This should be in your componentDidMount method:

```<code>   fetch('/api/v1/posts', {
      method: 'post',
      body: JSON.stringify(postdata),
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('[name="csrf-token"]').content
      },
    })
</code>```

Title: csrf in react and rails

Body:
I want to use csrf token while using post request. For that in api controller I have used protect_from_forgery with: :null_session at the top.

But how should I use that in react.

Also I could not found any good article on this.

fetch('/api/v1/posts', {
      method: 'post',
      body: JSON.stringify(postdata),
      headers: { 'Content-Type': 'application/json' },
    })

Body:
As I understand it, you need to pass the X-CSRF-TOKEN as a header to Rails when making the call. You can use document.querySelector('[name="csrf-token"]').content to get the token:

This should be in your componentDidMount method:

   fetch('/api/v1/posts', {
      method: 'post',
      body: JSON.stringify(postdata),
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('[name="csrf-token"]').content
      },
    })


问:
AWS Lambda - Runtime.ImportModuleError: Error: Cannot find module 'jmespath'
I am working with aws lambda using serverless framework, I changed the runtime from nodejs8.10 to nodejs10.x, then I got an errortrace,

```<code>{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'jmespath'","stack":["Runtime.ImportModuleError: Error: Cannot find module 'jmespath'","    at _loadUserApp (/var/runtime/UserFunction.js:100:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:36:30)","    at Module._compile (internal/modules/cjs/loader.js:701:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)","    at Module.load (internal/modules/cjs/loader.js:600:32)","    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)","    at Function.Module._load (internal/modules/cjs/loader.js:531:3)","    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)","    at startup (internal/bootstrap/node.js:283:19)"]}
</code>```

What is the cause of this issue and how can get it fixed?

答:
I'd also like to add that as a preliminary step before adjusting your path, check and verify your dependencies listed in your package.json(s) files.

I've seen this error "Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'something' occur in the aws cloudwatch logs.
It happened because my project has multiple subprojects/subfolders with their own package.json files.  Ensure that module is properly referenced in the subproject's package.json.

In local dev, you might have the dependency cited in your base/global package.json, and thinking it works -- but when you deploy the lambda the npm install that occurs during build does not include the newly required module because its not referenced in the local subproject's package.json.

Body:
I am working with aws lambda using serverless framework, I changed the runtime from nodejs8.10 to nodejs10.x, then I got an errortrace,

{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'jmespath'","stack":["Runtime.ImportModuleError: Error: Cannot find module 'jmespath'","    at _loadUserApp (/var/runtime/UserFunction.js:100:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:36:30)","    at Module._compile (internal/modules/cjs/loader.js:701:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)","    at Module.load (internal/modules/cjs/loader.js:600:32)","    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)","    at Function.Module._load (internal/modules/cjs/loader.js:531:3)","    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)","    at startup (internal/bootstrap/node.js:283:19)"]}

What is the cause of this issue and how can get it fixed?


问:
Checking array for a value
I have an array as below.

```<code>testgrid = [
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6]]
</code>```

On passing the testgrid into the following function it should return all indexes that do not contain a value of zero currently it returns (0, 0).  I would expect all indexes to be returned on this grid. It seems to be checking the indexes rather than the value stored at that index.  I am a noob so probably am missing something obvious here.

```<code>def not_empty_location(grid):

    # checks if current location is empty and assign location not empty
    for i in range(9):
        for j in range(9):
            if grid[i][j] != 0:
                return (i, j)
    return None
</code>```

答:
try by storing the index tuples in a list and return</p>

```<code>    def not_empty_location(grid):
    result = [] # list to store the index
    # checks if current location is empty and assign location not empty

    for i in range(9):
        for j in range(9):
            if grid[i][j] != 0:
                result.append( (i, j) )   # In your code you are returning at your very first success of getting != 0
    return result
</code>```

Title: Checking array for a value

Body:
I have an array as below.

testgrid = [
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6],
     [9, 1, 2, 4, 3, 8, 7, 5, 6]]

On passing the testgrid into the following function it should return all indexes that do not contain a value of zero currently it returns (0, 0).  I would expect all indexes to be returned on this grid. It seems to be checking the indexes rather than the value stored at that index.  I am a noob so probably am missing something obvious here.

def not_empty_location(grid):

    # checks if current location is empty and assign location not empty
    for i in range(9):
        for j in range(9):
            if grid[i][j] != 0:
                return (i, j)
    return None

Body:
try by storing the index tuples in a list and return

    def not_empty_location(grid):
    result = [] # list to store the index
    # checks if current location is empty and assign location not empty

    for i in range(9):
        for j in range(9):
            if grid[i][j] != 0:
                result.append( (i, j) )   # In your code you are returning at your very first success of getting != 0
    return result


问:
Keras ValueError: Dimensions must be equal - How to pass label-dependent values to custom loss function
I have a keras model with 5 outputs. My labels include 5 values to compare these to, but also 25 additional values representing a correlation matrix for the 5 values. (Specifically, it is the inverse covariance matrix). I want a custom loss function that includes the proper covariance (see formula below). I have written one and tested that it works. Keras has no problem compiling it, but complains when I try to fit it. The issue is that it seems to require the number of model outputs match the number of values in the label.

From what I have seen, most of the issues people have with custom loss functions and extra parameters involve passing additional static parameters (i.e. ones that don't change for each label). Here is my loss function with the testing code at the bottom.

```<code>    def customLoss(y_true, y_pred):

    batch_size = tf.shape(y_pred)[0]  # n.b. y_pred.shape[0] will not work for some reason in tf1
    print('y_pred shape: ' + str(y_pred.shape) )  # y_pred shape is (batch, 5)
    print('y_true shape: ' + str(y_true.shape) )  # y_true shape is (batch, 49)
    print('y_pred type: ' + str(type(y_pred) ) )  # y_pred shape is (batch, 5)
    print('y_true type: ' + str(type(y_true) ) )  # y_true shape is (batch, 49)

    # Note that y_pred only has the 5 state vector parameters while y_true contains
    # all of the labels (event, state vector, covariance matrix, inverse cov., ...)
    # We peel off the state vector and inverse covariance here which are the parts
    # we need.
    y_state = y_true[:,1:6]                         # y_state shape is now (batch, 5)
    invcov  = y_true[:,21:46]                       # invcov  shape is now (batch, 25)

    y_pred  = K.reshape(y_pred,  (batch_size, 5,1)) # y_pred  shape is now (batch, 5,1)
    y_state = K.reshape(y_state, (batch_size, 5,1)) # y_state shape is now (batch, 5,1)
    invcov  = K.reshape(invcov,  (batch_size, 5,5)) # invcov  shape is now (batch, 5,5)

    # n.b. we must use tf.transpose here an not K.transpose since the latter does not allow perm argument
    invcov = tf.transpose(invcov, perm=[0,2,1])     # invcov shape is now (batch, 5,5)

    # Difference between prediction and true state vectors
    y_diff = y_pred - y_state

    # n.b. use "batch_dot" and not "dot"!
    y_dot = K.batch_dot(invcov, y_diff)           # y_dot shape is (batch,5,1)
    y_dot = K.reshape(y_dot, (batch_size, 1, 5))  # y_dot shape is now (batch,1,5)
    y_loss = K.batch_dot(y_dot, y_diff)           # y_loss shape is (batch,1,1)
    y_loss = K.reshape(y_loss, (batch_size,))     # y_loss shape is now (batch)
    return y_loss

    # Test loss function
    xx = np.arange(0.1, 4.9, 0.1).tolist()  # make list of 49 values. This will be y_true (only 5+25=30 are used)
    yy = [1.0, 2.0, 3.0, 4.0, 5.0]          # make list of 5 values. This will be y_pred

    loss = K.eval(customLoss(K.variable([xx,xx,xx]), K.variable([yy,yy,yy])))
    print('loss shape: '    + str(loss.shape)    )
    print(loss)
</code>```

The output from testing the loss is:

```<code>y_pred shape: (3, 5)
y_true shape: (3, 49)
y_pred type: <class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>
y_true type: <class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>
loss shape: (3,)
[644.8 644.8 644.8]
</code>```

Here is the error I get when I try to compile:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-d1d9dff4fee8> in <module>
     36     shuffle=True,
     37     initial_epoch = epoch_loaded,
---> 38     use_multiprocessing=False
     39 )
     40

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in _method_wrapper(self, *args, **kwargs)
     64   def _method_wrapper(self, *args, **kwargs):
     65     if not self._in_multi_worker_mode():  # pylint: disable=protected-access
---> 66       return method(self, *args, **kwargs)
     67
     68     # Running inside `run_distribute_coordinator` already.

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
    846                 batch_size=batch_size):
    847               callbacks.on_train_batch_begin(step)
--> 848               tmp_logs = train_function(iterator)
    849               # Catch OutOfRangeError for Datasets of unknown size.
    850               # This blocks until the batch has finished executing.

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
    578         xla_context.Exit()
    579     else:
--> 580       result = self._call(*args, **kwds)
    581
    582     if tracing_count == self._get_tracing_count():

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
    625       # This is the first call of __call__, so we have to initialize.
    626       initializers = []
--> 627       self._initialize(args, kwds, add_initializers_to=initializers)
    628     finally:
    629       # At this point we know that the initialization is complete (or less

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
    504     self._concrete_stateful_fn = (
    505         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
--> 506             *args, **kwds))
    507
    508     def invalid_creator_scope(*unused_args, **unused_kwds):

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   2444       args, kwargs = None, None
   2445     with self._lock:
-> 2446       graph_function, _, _ = self._maybe_define_function(args, kwargs)
   2447     return graph_function
   2448

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   2775
   2776       self._function_cache.missed.add(call_context_key)
-> 2777       graph_function = self._create_graph_function(args, kwargs)
   2778       self._function_cache.primary[cache_key] = graph_function
   2779       return graph_function, args, kwargs

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   2665             arg_names=arg_names,
   2666             override_flat_arg_shapes=override_flat_arg_shapes,
-> 2667             capture_by_value=self._capture_by_value),
   2668         self._function_attributes,
   2669         # Tell the ConcreteFunction to clean up its graph once it goes out of

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    979         _, original_func = tf_decorator.unwrap(python_func)
    980
--> 981       func_outputs = python_func(*func_args, **func_kwargs)
    982
    983       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
    439         # __wrapped__ allows AutoGraph to swap in a converted function. We give
    440         # the function a weak reference to itself to avoid a reference cycle.
--> 441         return weak_wrapped_fn().__wrapped__(*args, **kwds)
    442     weak_wrapped_fn = weakref.ref(wrapped_fn)
    443

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    966           except Exception as e:  # pylint:disable=broad-except
    967             if hasattr(e, "ag_error_metadata"):
--> 968               raise e.ag_error_metadata.to_exception(e)
    969             else:
    970               raise

ValueError: in user code:

    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:543 train_step  **
        self.compiled_metrics.update_state(y, y_pred, sample_weight)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/engine/compile_utils.py:411 update_state
        metric_obj.update_state(y_t, y_p)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/utils/metrics_utils.py:90 decorated
        update_op = update_state_fn(*args, **kwargs)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/metrics.py:603 update_state
        matches = self._fn(y_true, y_pred, **self._fn_kwargs)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/losses.py:1230 mean_absolute_error
        return K.mean(math_ops.abs(y_pred - y_true), axis=-1)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py:984 binary_op_wrapper
        return func(x, y, name=name)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/ops/gen_math_ops.py:10103 sub
        "Sub", x=x, y=y, name=name)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:744 _apply_op_helper
        attrs=attr_protos, op_def=op_def)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py:595 _create_op_internal
        compute_device)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:3327 _create_op_internal
        op_def=op_def)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:1817 __init__
        control_input_ops, op_def)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:1657 _create_c_op
        raise ValueError(str(e))

    ValueError: Dimensions must be equal, but are 5 and 49 for '{{node sub}} = Sub[T=DT_FLOAT](model/outputs/Relu, Cast_2)' with input shapes: [1000,5], [1000,49].
</code>```

So the question is how to pass additional parameters to the custom loss function that vary for each set of inputs?

答:
these are the workaround to pass additional parameters to the custom loss function that vary for each set of inputs

I provide a dummy example in a regression problem

```<code>def mse(y_true, y_pred, external):

    score = K.mean(K.sqrt(y_true-y_pred))
    # make something with external...
    # I simply add to final score (no sense)

    return score + K.mean(external)

X = np.random.uniform(0,1, (1000,10))
y = np.random.uniform(0,3, (1000,49))

inp = Input((10))
true = Input((5))
external_arg = Input((49-5))
x = Dense(32, activation='relu')(inp)
pred = Dense(5)(x)

m = Model([inp,external_arg,true], pred)
m.add_loss( mse( true, pred, external_arg ) )
m.compile(loss=None, optimizer='adam')
history = m.fit([X, y[:,5:], y[:,:5]], y[:,:5], epochs=10)

# final fitted model to compute predictions
final_m = Model(inp, pred)
</code>```

Body:
I have a keras model with 5 outputs. My labels include 5 values to compare these to, but also 25 additional values representing a correlation matrix for the 5 values. (Specifically, it is the inverse covariance matrix). I want a custom loss function that includes the proper covariance (see formula below). I have written one and tested that it works. Keras has no problem compiling it, but complains when I try to fit it. The issue is that it seems to require the number of model outputs match the number of values in the label.

From what I have seen, most of the issues people have with custom loss functions and extra parameters involve passing additional static parameters (i.e. ones that don't change for each label). Here is my loss function with the testing code at the bottom.

    def customLoss(y_true, y_pred):

    batch_size = tf.shape(y_pred)[0]  # n.b. y_pred.shape[0] will not work for some reason in tf1
    print('y_pred shape: ' + str(y_pred.shape) )  # y_pred shape is (batch, 5)
    print('y_true shape: ' + str(y_true.shape) )  # y_true shape is (batch, 49)
    print('y_pred type: ' + str(type(y_pred) ) )  # y_pred shape is (batch, 5)
    print('y_true type: ' + str(type(y_true) ) )  # y_true shape is (batch, 49)

    # Note that y_pred only has the 5 state vector parameters while y_true contains
    # all of the labels (event, state vector, covariance matrix, inverse cov., ...)
    # We peel off the state vector and inverse covariance here which are the parts
    # we need.
    y_state = y_true[:,1:6]                         # y_state shape is now (batch, 5)
    invcov  = y_true[:,21:46]                       # invcov  shape is now (batch, 25)

    y_pred  = K.reshape(y_pred,  (batch_size, 5,1)) # y_pred  shape is now (batch, 5,1)
    y_state = K.reshape(y_state, (batch_size, 5,1)) # y_state shape is now (batch, 5,1)
    invcov  = K.reshape(invcov,  (batch_size, 5,5)) # invcov  shape is now (batch, 5,5)

    # n.b. we must use tf.transpose here an not K.transpose since the latter does not allow perm argument
    invcov = tf.transpose(invcov, perm=[0,2,1])     # invcov shape is now (batch, 5,5)

    # Difference between prediction and true state vectors
    y_diff = y_pred - y_state

    # n.b. use "batch_dot" and not "dot"!
    y_dot = K.batch_dot(invcov, y_diff)           # y_dot shape is (batch,5,1)
    y_dot = K.reshape(y_dot, (batch_size, 1, 5))  # y_dot shape is now (batch,1,5)
    y_loss = K.batch_dot(y_dot, y_diff)           # y_loss shape is (batch,1,1)
    y_loss = K.reshape(y_loss, (batch_size,))     # y_loss shape is now (batch)
    return y_loss

    # Test loss function
    xx = np.arange(0.1, 4.9, 0.1).tolist()  # make list of 49 values. This will be y_true (only 5+25=30 are used)
    yy = [1.0, 2.0, 3.0, 4.0, 5.0]          # make list of 5 values. This will be y_pred

    loss = K.eval(customLoss(K.variable([xx,xx,xx]), K.variable([yy,yy,yy])))
    print('loss shape: '    + str(loss.shape)    )
    print(loss)

The output from testing the loss is:

y_pred shape: (3, 5)
y_true shape: (3, 49)
y_pred type: <class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>
y_true type: <class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>
loss shape: (3,)
[644.8 644.8 644.8]

Here is the error I get when I try to compile:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-d1d9dff4fee8> in <module>
     36     shuffle=True,
     37     initial_epoch = epoch_loaded,
---> 38     use_multiprocessing=False
     39 )
     40

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in _method_wrapper(self, *args, **kwargs)
     64   def _method_wrapper(self, *args, **kwargs):
     65     if not self._in_multi_worker_mode():  # pylint: disable=protected-access
---> 66       return method(self, *args, **kwargs)
     67
     68     # Running inside `run_distribute_coordinator` already.

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
    846                 batch_size=batch_size):
    847               callbacks.on_train_batch_begin(step)
--> 848               tmp_logs = train_function(iterator)
    849               # Catch OutOfRangeError for Datasets of unknown size.
    850               # This blocks until the batch has finished executing.

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
    578         xla_context.Exit()
    579     else:
--> 580       result = self._call(*args, **kwds)
    581
    582     if tracing_count == self._get_tracing_count():

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
    625       # This is the first call of __call__, so we have to initialize.
    626       initializers = []
--> 627       self._initialize(args, kwds, add_initializers_to=initializers)
    628     finally:
    629       # At this point we know that the initialization is complete (or less

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
    504     self._concrete_stateful_fn = (
    505         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
--> 506             *args, **kwds))
    507
    508     def invalid_creator_scope(*unused_args, **unused_kwds):

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   2444       args, kwargs = None, None
   2445     with self._lock:
-> 2446       graph_function, _, _ = self._maybe_define_function(args, kwargs)
   2447     return graph_function
   2448

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   2775
   2776       self._function_cache.missed.add(call_context_key)
-> 2777       graph_function = self._create_graph_function(args, kwargs)
   2778       self._function_cache.primary[cache_key] = graph_function
   2779       return graph_function, args, kwargs

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   2665             arg_names=arg_names,
   2666             override_flat_arg_shapes=override_flat_arg_shapes,
-> 2667             capture_by_value=self._capture_by_value),
   2668         self._function_attributes,
   2669         # Tell the ConcreteFunction to clean up its graph once it goes out of

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    979         _, original_func = tf_decorator.unwrap(python_func)
    980
--> 981       func_outputs = python_func(*func_args, **func_kwargs)
    982
    983       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
    439         # __wrapped__ allows AutoGraph to swap in a converted function. We give
    440         # the function a weak reference to itself to avoid a reference cycle.
--> 441         return weak_wrapped_fn().__wrapped__(*args, **kwds)
    442     weak_wrapped_fn = weakref.ref(wrapped_fn)
    443

/w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    966           except Exception as e:  # pylint:disable=broad-except
    967             if hasattr(e, "ag_error_metadata"):
--> 968               raise e.ag_error_metadata.to_exception(e)
    969             else:
    970               raise

ValueError: in user code:

    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:543 train_step  **
        self.compiled_metrics.update_state(y, y_pred, sample_weight)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/engine/compile_utils.py:411 update_state
        metric_obj.update_state(y_t, y_p)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/utils/metrics_utils.py:90 decorated
        update_op = update_state_fn(*args, **kwargs)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/metrics.py:603 update_state
        matches = self._fn(y_true, y_pred, **self._fn_kwargs)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/keras/losses.py:1230 mean_absolute_error
        return K.mean(math_ops.abs(y_pred - y_true), axis=-1)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py:984 binary_op_wrapper
        return func(x, y, name=name)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/ops/gen_math_ops.py:10103 sub
        "Sub", x=x, y=y, name=name)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:744 _apply_op_helper
        attrs=attr_protos, op_def=op_def)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py:595 _create_op_internal
        compute_device)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:3327 _create_op_internal
        op_def=op_def)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:1817 __init__
        control_input_ops, op_def)
    /w/halld-scifs17exp/halld2/home/davidl/builds/Python_VENV/venv_2020.06.02/lib/python3.7/site-packages/tensorflow/python/framework/ops.py:1657 _create_c_op
        raise ValueError(str(e))

    ValueError: Dimensions must be equal, but are 5 and 49 for '{{node sub}} = Sub[T=DT_FLOAT](model/outputs/Relu, Cast_2)' with input shapes: [1000,5], [1000,49].

So the question is how to pass additional parameters to the custom loss function that vary for each set of inputs?

Body:
these are the workaround to pass additional parameters to the custom loss function that vary for each set of inputs

I provide a dummy example in a regression problem

def mse(y_true, y_pred, external):

    score = K.mean(K.sqrt(y_true-y_pred))
    # make something with external...
    # I simply add to final score (no sense)

    return score + K.mean(external)

X = np.random.uniform(0,1, (1000,10))
y = np.random.uniform(0,3, (1000,49))

inp = Input((10))
true = Input((5))
external_arg = Input((49-5))
x = Dense(32, activation='relu')(inp)
pred = Dense(5)(x)

m = Model([inp,external_arg,true], pred)
m.add_loss( mse( true, pred, external_arg ) )
m.compile(loss=None, optimizer='adam')
history = m.fit([X, y[:,5:], y[:,:5]], y[:,:5], epochs=10)

# final fitted model to compute predictions
final_m = Model(inp, pred)


问:
Using only part of a function in R
Is there any way to use only part of a function in R?
For example:

```<code>My.function <- function(x)
{
  m = mean(x)
  q.1 = quantile(x, 1/4)
  q.3 = quantile(x, 3/4)
  rbind(m, q.1, q.3)
}
</code>```

I want to use only q.1 and q.3 and not m for any reason. Is it possible? If it is, then how?

Thanks

答:
You could use if statements in the body of the function and add booleans in the function argument. Then the function won't evaluate if statements that are false. For your case, it would be something like</p>

```<code> My.function <- function(x,getmean = F)
{
  q.1 = quantile(x, 1/4)
  q.3 = quantile(x, 3/4)

  if (getmean) {
    m = mean(x)
    return(rbind(m, q.1, q.3))
  } else {
    return(rbind(q.1,q.3))
  }
}

#test
My.function(rnorm(100))
My.function(rnorm(100), getmean = T)
</code>```

Title: Using only part of a function in R

Body:
Is there any way to use only part of a function in R?
For example:

My.function <- function(x)
{
  m = mean(x)
  q.1 = quantile(x, 1/4)
  q.3 = quantile(x, 3/4)
  rbind(m, q.1, q.3)
}

I want to use only q.1 and q.3 and not m for any reason. Is it possible? If it is, then how?

Thanks

Body:
You could use if statements in the body of the function and add booleans in the function argument. Then the function won't evaluate if statements that are false. For your case, it would be something like

 My.function <- function(x,getmean = F)
{
  q.1 = quantile(x, 1/4)
  q.3 = quantile(x, 3/4)

  if (getmean) {
    m = mean(x)
    return(rbind(m, q.1, q.3))
  } else {
    return(rbind(q.1,q.3))
  }
}

#test
My.function(rnorm(100))
My.function(rnorm(100), getmean = T)


问:
Semantic Diff Utilities
I'm trying to find some good examples of semantic diff/merge utilities.  The traditional paradigm of comparing source code files works by comparing lines and characters.. but are there any utilities out there (for any language) that actually consider the structure of code when comparing files?

For example, existing diff programs will report "difference found at character 2 of line 125. File x contains v-o-i-d, where file y contains b-o-o-l".  A specialized tool should be able to report "Return type of method doSomething() changed from void to bool".

I would argue that this type of semantic information is actually what the user is looking for when comparing code, and should be the goal of next-generation progamming tools.  Are there any examples of this in available tools?

答:
Eclipse has had this feature for a long time. It's called "Structure Compare", and it's very nice. Here is a sample screenshot for Java, followed by another for an XML file:

(Note the minus and plus icons on methods in the upper pane.)

ContentLicense: CC BY-SA 2.5

Title: Semantic Diff Utilities

OwnerDisplayName: Hosam Aly

LastEditorDisplayName: Hosam Aly


问:
Does caching the return value of typeof(MyControl) provide any optimization?
I see code similar to the following sprinkled about some native WPF controls:

```<code>static MyControl {
    Type typeFromHandle = typeof(MyControl);

    // Which is used in various places
    SomeProperty.OverrideMetadata(typeFromHandle, ...);
    CommandManager.RegisterClassInputBinding(typeFromHandle, ...);
    EventManager.RegisterClassHandler(typeFromHandle, ...);
}
</code>```

Seems like the following code would have the same performance:

```<code>static MyControl {
    SomeProperty.OverrideMetadata(typeof(MyControl), ...);
    CommandManager.RegisterClassInputBinding(typeof(MyControl), ...);
    EventManager.RegisterClassHandler(typeof(MyControl), ...);
}
</code>```

Does this approach offer any benefit performance wise when JIT-ing the code or during runtime?

答:
Caching of typeof will give you a small performance boost. The following page gives the benchmarks:

```<code>Typeof expression used: 2.55 ns
Type object cached:     0.64 ns
</code>```

If you typeof a lot, or care about nanoseconds, then this might matter to you!

ContentLicense: CC BY-SA 3.0

Body:
I see code similar to the following sprinkled about some native WPF controls:

static MyControl {
    Type typeFromHandle = typeof(MyControl);

    // Which is used in various places
    SomeProperty.OverrideMetadata(typeFromHandle, ...);
    CommandManager.RegisterClassInputBinding(typeFromHandle, ...);
    EventManager.RegisterClassHandler(typeFromHandle, ...);
}

Seems like the following code would have the same performance:

static MyControl {
    SomeProperty.OverrideMetadata(typeof(MyControl), ...);
    CommandManager.RegisterClassInputBinding(typeof(MyControl), ...);
    EventManager.RegisterClassHandler(typeof(MyControl), ...);
}

Does this approach offer any benefit performance wise when JIT-ing the code or during runtime?

Body:
Caching of typeof will give you a small performance boost. The following page gives the benchmarks:

Typeof expression used: 2.55 ns
Type object cached:     0.64 ns

If you typeof a lot, or care about nanoseconds, then this might matter to you!


问:
Error 3358 : The InitiatedType field is missing
Have been using SagePay integration v4 for some months now and since midnight tonight suddenly receiving lots of:

"Error 3358 : The InitiatedType field is missing".

What have SagePay changed?  The Direct Integration document I've got is dated 24/05/19, so over a year old so it's possible that this has been updated but not communicated out

答:
Interestingly I just got off the phone from Sagepay and they told me a different story, apparently it's an error in a release they put live today.

Really annoying considering only V4 supports 3DSv2


问:
Cannot return Promise
I'm using Typeorm so I've created a method that return a connection:

```<code>public static async getConnection(): Promise<Connection> {
    if (DatabaseProvider.connection) {
        return DatabaseProvider.connection;
    }

    const { type, host, port, username, password, database, extra, entities, migrations } = DatabaseProvider.configuration;
    DatabaseProvider.connection = await createConnection({
        type, host, port, username, password, database,
        extra,
        entities: [
            entities
        ],
        migrations: [
            migrations
        ]
    } as any);

    return DatabaseProvider.connection;
}
</code>```

I want assign the connection to a bot instance of Telegraf so I have created a .d.ts file for specify the type:

```<code>export interface TelegrafContext extends Context {
    db: Connection
}
</code>```

then:

```<code>bot.context.db = DatabaseProvider.getConnection().then((conn) => { return conn; });
</code>```

and I get:

Type 'Promise' is missing the following properties from type 'Connection': name, options, isConnected, driver, and 32 more.

What I did wrong?

答:
Probably because you're trying to assign Promise<Connection> to bot.context.db and it should be a Connection.

so you can either:

```<code>DatabaseProvider.getConnection().then((conn) => {
  bot.context.db = conn
});
</code>```

or:

```<code>bot.context.db = await DatabaseProvider.getConnection()
</code>```

Title: Cannot return Promise

Body:
I'm using Typeorm so I've created a method that return a connection:

public static async getConnection(): Promise<Connection> {
    if (DatabaseProvider.connection) {
        return DatabaseProvider.connection;
    }

    const { type, host, port, username, password, database, extra, entities, migrations } = DatabaseProvider.configuration;
    DatabaseProvider.connection = await createConnection({
        type, host, port, username, password, database,
        extra,
        entities: [
            entities
        ],
        migrations: [
            migrations
        ]
    } as any);

    return DatabaseProvider.connection;
}

I want assign the connection to a bot instance of Telegraf so I have created a .d.ts file for specify the type:

export interface TelegrafContext extends Context {
    db: Connection
}

then:

bot.context.db = DatabaseProvider.getConnection().then((conn) => { return conn; });

and I get:

Type 'Promise' is missing the following properties from type 'Connection': name, options, isConnected, driver, and 32 more.

What I did wrong?

Body:
Probably because you're trying to assign Promise<Connection> to bot.context.db and it should be a Connection.

so you can either:

DatabaseProvider.getConnection().then((conn) => {
  bot.context.db = conn
});

or:

bot.context.db = await DatabaseProvider.getConnection()


问:
Why is my RecyclerViewAdapter not showing in View?
I tried to migrate my Chat Bot from ScrollView to a RecyclerView for performance, but unfortunally every method in my Adapter is called correctly but nothing is showed.

My Custom RecyclerView Adapter:

```<code>public class ChatViewAdapter extends RecyclerView.Adapter<ChatViewAdapter.ChatViewHolder> {
    private LinkedList<ChatBubbleModel> bubbles;
    private ViewGroup group;

    public ChatViewAdapter() {
        this(new LinkedList<ChatBubbleModel>());
    }

    public ChatViewAdapter(LinkedList<ChatBubbleModel> bubbles) {
        this.bubbles = bubbles;
    }

    public LinkedList<ChatBubbleModel> getBubbles() {
        return bubbles;
    }

    public void addBubble(ChatBubbleModel bubble) {
        this.bubbles.add(bubble);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        this.group = parent;
        return new ChatViewHolder(new TextView(parent.getContext()));
    }

    @Override
    public void onBindViewHolder(@NonNull ChatViewHolder holder, int position) {
        final ChatBubbleModel instance = this.bubbles.get(position);
        if (instance.getUserType() == ChatBubbleModel.UserType.USER) {
            holder.setTextView(new RightChatBubble(instance.getOwner(), instance.getMessage(), group.getContext()));
        } else {
            holder.setTextView(new LeftChatBubble(instance.getOwner(), instance.getMessage(), group.getContext()));
        }
    }

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

    public static class ChatViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        private TextView textView;

        public ChatViewHolder(TextView v) {
            super(v);
            textView = v;
        }

        public void setTextView(TextView view) {
            this.textView = view;
        }

    }
}

</code>```

And in the Fragmnet where I use it:

```<code>final View root = inflater.inflate(R.layout.fragment_chatview, container, false);
        chatView = root.findViewById(R.id.chatView);
        chatView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        chatView.setLayoutManager(layoutManager);
        this.chatAdapter = new ChatViewAdapter(new LinkedList<ChatBubbleModel>());
        chatView.setAdapter(chatAdapter);
</code>```

The Impl of the View I use:

```<code>public class LeftChatBubble extends androidx.appcompat.widget.AppCompatTextView {

    private final static int leftRightPadding = 50;
    private final static int topBottomPadding = 20;

    public LeftChatBubble(Context context) {
        this(context, null, -1);

    }

    @SuppressLint("SetTextI18n")
    public LeftChatBubble(String owner, String text, Context context) {
        super(context);
        setText(owner + "\n" + text);
        setBackground(ContextCompat.getDrawable(context, R.drawable.inset));

        setPadding(pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context), pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context));
        setTextAlignment(TEXT_ALIGNMENT_VIEW_START);
        setTextColor(Color.WHITE);

    }

    public LeftChatBubble(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public LeftChatBubble(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setBackground(ContextCompat.getDrawable(context, R.drawable.ic_chatbubleleft));

        setPadding(pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context), pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context));
        setTextAlignment(TEXT_ALIGNMENT_VIEW_START);
        setTextColor(Color.WHITE);

    }

    private int pixelToDp(int px, Context context) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px * scale + 0.5f);

    }

}
</code>```

Does anyone have an Idea why there is nothing showed on the device? The Used Layout is correct bc it worked before.

答:
You did not seem to inflate your item view in the onCreateViewHolder like

```<code>@NonNull
@Override
public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    this.group = parent;
    LayoutInflater inflater = LayoutInflater.from(this);
    View view = inflater.inflate(R.layout.item_view, parent, false);
    return new ChatViewHolder(view);
}
</code>```

Also, change your ViewHolder args to be a View.

Body:
I tried to migrate my Chat Bot from ScrollView to a RecyclerView for performance, but unfortunally every method in my Adapter is called correctly but nothing is showed.

My Custom RecyclerView Adapter:

public class ChatViewAdapter extends RecyclerView.Adapter<ChatViewAdapter.ChatViewHolder> {
    private LinkedList<ChatBubbleModel> bubbles;
    private ViewGroup group;

    public ChatViewAdapter() {
        this(new LinkedList<ChatBubbleModel>());
    }

    public ChatViewAdapter(LinkedList<ChatBubbleModel> bubbles) {
        this.bubbles = bubbles;
    }

    public LinkedList<ChatBubbleModel> getBubbles() {
        return bubbles;
    }

    public void addBubble(ChatBubbleModel bubble) {
        this.bubbles.add(bubble);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        this.group = parent;
        return new ChatViewHolder(new TextView(parent.getContext()));
    }

    @Override
    public void onBindViewHolder(@NonNull ChatViewHolder holder, int position) {
        final ChatBubbleModel instance = this.bubbles.get(position);
        if (instance.getUserType() == ChatBubbleModel.UserType.USER) {
            holder.setTextView(new RightChatBubble(instance.getOwner(), instance.getMessage(), group.getContext()));
        } else {
            holder.setTextView(new LeftChatBubble(instance.getOwner(), instance.getMessage(), group.getContext()));
        }
    }

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

    public static class ChatViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        private TextView textView;

        public ChatViewHolder(TextView v) {
            super(v);
            textView = v;
        }

        public void setTextView(TextView view) {
            this.textView = view;
        }

    }
}

And in the Fragmnet where I use it:

final View root = inflater.inflate(R.layout.fragment_chatview, container, false);
        chatView = root.findViewById(R.id.chatView);
        chatView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        chatView.setLayoutManager(layoutManager);
        this.chatAdapter = new ChatViewAdapter(new LinkedList<ChatBubbleModel>());
        chatView.setAdapter(chatAdapter);

The Impl of the View I use:

public class LeftChatBubble extends androidx.appcompat.widget.AppCompatTextView {

    private final static int leftRightPadding = 50;
    private final static int topBottomPadding = 20;

    public LeftChatBubble(Context context) {
        this(context, null, -1);

    }

    @SuppressLint("SetTextI18n")
    public LeftChatBubble(String owner, String text, Context context) {
        super(context);
        setText(owner + "\n" + text);
        setBackground(ContextCompat.getDrawable(context, R.drawable.inset));

        setPadding(pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context), pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context));
        setTextAlignment(TEXT_ALIGNMENT_VIEW_START);
        setTextColor(Color.WHITE);

    }

    public LeftChatBubble(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public LeftChatBubble(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setBackground(ContextCompat.getDrawable(context, R.drawable.ic_chatbubleleft));

        setPadding(pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context), pixelToDp(leftRightPadding, context), pixelToDp(topBottomPadding, context));
        setTextAlignment(TEXT_ALIGNMENT_VIEW_START);
        setTextColor(Color.WHITE);

    }

    private int pixelToDp(int px, Context context) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px * scale + 0.5f);

    }

}

Does anyone have an Idea why there is nothing showed on the device? The Used Layout is correct bc it worked before.

Body:
You did not seem to inflate your item view in the onCreateViewHolder like

@NonNull
@Override
public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    this.group = parent;
    LayoutInflater inflater = LayoutInflater.from(this);
    View view = inflater.inflate(R.layout.item_view, parent, false);
    return new ChatViewHolder(view);
}

Also, change your ViewHolder args to be a View.


问:
Original list doesn't show up after a search is made in planets list
I added a searchbar that can search for planets. The searching works. The problem is when I remove the text in the search field it doesn't update the list of planets (they don't come back on the screen).

How can I fix this?

```<code>import React, { PureComponent } from 'react'
import axios from 'axios'

class Home extends PureComponent {
  constructor(props) {
    super(props)

    this.state = {
      planets: [],
    }

    this.handleChange = this.handleChange.bind(this)
  }

  componentDidMount() {
    axios({
      method: 'GET',
      url: 'https://swapi.dev/api/planets/',
    })
      .then(response => {
        console.log(response)
        let planetslist = response.data.results
        this.setState({ planets: planetslist })
      })
      .catch(error => {
        console.log("You've made an error with the planets load charles: ", error)
      })
  }

  handleChange(e) {
    // eslint-disable-next-line
    let planetssearchlist = this.state.planets.filter(planet => {
      if (planet.name) {
        if (planet.name.toLowerCase().includes(e.target.value.toLowerCase())) {
          return true
        }
      }
    })
    this.setState({
      planets: planetssearchlist,
    })
  }

  render() {
    return (
      <div>
        <h1>Star Wars Planets</h1>

        <form>
          <input
            placeholder="searchbar"
            type="text"
            onChange={this.handleChange}
          ></input>
        </form>

        {this.state.planets.map((planet, i) => (
          <p key={i}>{planet.name}</p>
        ))}
      </div>
    )
  }
}

export default Home
</code>```

答:
You could store the initial planets differently from the ones you filtered. In this case I stored them in filteredPlanets which is initially set after the response is received, while being updated on the desired event. This way it is always using the initially fetched planets to apply the filter on.

```<code>import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: [],
            filteredPlanets: []
        }

        this.handleChange = this.handleChange.bind(this)
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/"
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data.results;
            this.setState({planets: planetslist, filteredPlanets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    handleChange(e){ // eslint-disable-next-line
        let planetssearchlist = this.state.planets.filter(planet => {
             if(planet.name){
                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true
                }
            }
        })
        this.setState({
            filteredPlanets: planetssearchlist
        })
    }

    render() {
        return (

        <div>
            <h1>Star Wars Planets</h1>

            <form>
                <input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
            </form>

            {
                this.state.filteredPlanets.map((planet,i) => (
                        <p key={i}>{planet.name}</p>
                ))
            }

        </div>

        )
    }
}

export default Home
</code>```

Body:
I added a searchbar that can search for planets. The searching works. The problem is when I remove the text in the search field it doesn't update the list of planets (they don't come back on the screen).

How can I fix this?

import React, { PureComponent } from 'react'
import axios from 'axios'

class Home extends PureComponent {
  constructor(props) {
    super(props)

    this.state = {
      planets: [],
    }

    this.handleChange = this.handleChange.bind(this)
  }

  componentDidMount() {
    axios({
      method: 'GET',
      url: 'https://swapi.dev/api/planets/',
    })
      .then(response => {
        console.log(response)
        let planetslist = response.data.results
        this.setState({ planets: planetslist })
      })
      .catch(error => {
        console.log("You've made an error with the planets load charles: ", error)
      })
  }

  handleChange(e) {
    // eslint-disable-next-line
    let planetssearchlist = this.state.planets.filter(planet => {
      if (planet.name) {
        if (planet.name.toLowerCase().includes(e.target.value.toLowerCase())) {
          return true
        }
      }
    })
    this.setState({
      planets: planetssearchlist,
    })
  }

  render() {
    return (

Star Wars Planets

        <form>
          <input
            placeholder="searchbar"
            type="text"
            onChange={this.handleChange}
          ></input>
        </form>

        {this.state.planets.map((planet, i) => (

{planet.name}

        ))}

    )
  }
}

export default Home

Body:
You could store the initial planets differently from the ones you filtered. In this case I stored them in filteredPlanets which is initially set after the response is received, while being updated on the desired event. This way it is always using the initially fetched planets to apply the filter on.

import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: [],
            filteredPlanets: []
        }

        this.handleChange = this.handleChange.bind(this)
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/"
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data.results;
            this.setState({planets: planetslist, filteredPlanets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    handleChange(e){ // eslint-disable-next-line
        let planetssearchlist = this.state.planets.filter(planet => {
             if(planet.name){
                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true
                }
            }
        })
        this.setState({
            filteredPlanets: planetssearchlist
        })
    }

    render() {
        return (

        <div>
            <h1>Star Wars Planets</h1>

            <form>
                <input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
            </form>

            {
                this.state.filteredPlanets.map((planet,i) => (
                        <p key={i}>{planet.name}</p>
                ))
            }

        </div>

        )
    }
}

export default Home


问:
How can I add a jpg saved on my computer to the code that i have written
It is a java program that is designed to look like a Windows 10 Blue Screen Of Death, but I can not figure out how to add an image to it.<br>
I have tried many different methods, but they did not work out for me, maybe I was doing them wrong. The Image is the QR code that is going to be on the lower left hand corner. </p>

```<code>import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;

public class BSODJava {
 public static void main(String[] args) {
  JFrame frame = new JFrame("Lab00");
  frame.setSize(1366, 768);
  frame.setLocation(0, 0);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setContentPane(new Panel1());
  frame.setVisible(true);
  frame.setBackground(Color.black);
 }
}
class Panel1 extends JPanel {
 public void paintComponent(Graphics g) {
  g.setColor(new Color(6, 117, 170));
  g.fillRect(1, 1, 1366, 768);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 200));
  g.drawString(";)", 50, 165);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 52));
  g.drawString("Your PC ran into a problem and needs to restart.  We'll", 50, 270);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 52));
  g.drawString("restart for you.", 50, 330);
 }
}
</code>```

答:
There is no need to do all that custom painting. Swing has components to do the painting for you.

Start by using a JLabel. You can display a JLabel with text and/or Icon. Read the section from the Swing tutorial on How to Use Icons for examples to get you started.

Then also learn how to use Layout Managers to position the components on the panel.

Body:
It is a java program that is designed to look like a Windows 10 Blue Screen Of Death, but I can not figure out how to add an image to it.

I have tried many different methods, but they did not work out for me, maybe I was doing them wrong. The Image is the QR code that is going to be on the lower left hand corner.

import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;

public class BSODJava {
 public static void main(String[] args) {
  JFrame frame = new JFrame("Lab00");
  frame.setSize(1366, 768);
  frame.setLocation(0, 0);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setContentPane(new Panel1());
  frame.setVisible(true);
  frame.setBackground(Color.black);
 }
}
class Panel1 extends JPanel {
 public void paintComponent(Graphics g) {
  g.setColor(new Color(6, 117, 170));
  g.fillRect(1, 1, 1366, 768);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 200));
  g.drawString(";)", 50, 165);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 52));
  g.drawString("Your PC ran into a problem and needs to restart.  We'll", 50, 270);

  g.setColor(new Color(255, 255, 255));
  g.setFont(new Font("Segoe UI", Font.PLAIN, 52));
  g.drawString("restart for you.", 50, 330);
 }
}


问:
how do i get a specific attribute from an inherited class when using an array from another class?
I am new to Java programming and have encountered a slight problem.

I wrote tow Classes the first named Human and the second called Student which extends Human

So, in short, I created an array with the type Human and now I want to output a specific  attribute of Student and I want to check if the value of the array entered is a Student. The problem is that the array type  is Human, I can't ask for an exclusive Student attribute.

Thanks for your answers in advance.

The Code:

```<code>for (int i = 0; i < 4; i++) {
    if (Menschen[i] instanceof Student) {
        System.out.println("Name: " + Menschen[i].getName() + ", Geschlecht"
                           + Menschen[i].getGeschlecht() + ", Matrikelnummer: "
                           + ", Typ: " + Menschen[i].getTyp());
    } else {
        System.out.println("Name; " + Menschen[i].getName() + ", Geschlecht"
                       + Menschen[i].getGeschlecht()+", Typ: "+Menschen[i].getTyp() + ".");
    }
}
</code>```

答:
If using Java 14 you can do:

```<code>if (Menschen[i] instanceof Student student) {
    student.studentSpecificMethod();
} else {
  ...
}
</code>```

EDIT: for earlier Java versions see Mario MG's answer

But generally it's rare that you should need instanceof. It's best to try coming up with a design for a general method that would be overridden in specific subclasses, whenever possible.

EDIT2: you can get rid of the i counter completely

```<code>for (Human mensch : Menschen) { //please name variables in lowercase, so Menschen -> menschen
    if (mensch instanceof Student student) {
       ...
    } else {
       ...
    }
}
</code>```

Body:
I am new to Java programming and have encountered a slight problem.

I wrote tow Classes the first named Human and the second called Student which extends Human

So, in short, I created an array with the type Human and now I want to output a specific  attribute of Student and I want to check if the value of the array entered is a Student. The problem is that the array type  is Human, I can't ask for an exclusive Student attribute.

Thanks for your answers in advance.

The Code:

for (int i = 0; i < 4; i++) {
    if (Menschen[i] instanceof Student) {
        System.out.println("Name: " + Menschen[i].getName() + ", Geschlecht"
                           + Menschen[i].getGeschlecht() + ", Matrikelnummer: "
                           + ", Typ: " + Menschen[i].getTyp());
    } else {
        System.out.println("Name; " + Menschen[i].getName() + ", Geschlecht"
                       + Menschen[i].getGeschlecht()+", Typ: "+Menschen[i].getTyp() + ".");
    }
}

Body:
If using Java 14 you can do:

if (Menschen[i] instanceof Student student) {
    student.studentSpecificMethod();
} else {
  ...
}

EDIT: for earlier Java versions see Mario MG's answer

But generally it's rare that you should need instanceof. It's best to try coming up with a design for a general method that would be overridden in specific subclasses, whenever possible.

EDIT2: you can get rid of the i counter completely

for (Human mensch : Menschen) { //please name variables in lowercase, so Menschen -> menschen
    if (mensch instanceof Student student) {
       ...
    } else {
       ...
    }
}


问:
Idiomatic way to modify a member variable
I know Haskell isn't OO so it isn't strictly a 'member variable'.

```<code>data Foo = Foo {
    bar :: Int,
    moo :: Int,
    meh :: Int,
    yup :: Int
}

modifyBar (Foo b m me y) = (Foo b' m me y)
    where b' = 2
</code>```

This is how my code looks at the moment. The problem is I am now making data types with 16 or more members. When I need to modify a single member it results in very verbose code. Is there a way around this?

答:
```<code>modifyBar foo = foo { bar = 2 }
</code>```

This syntax will copy foo, and then modify the bar field of that copy to 2. This could be naturally extended to more fields, so you don't need to write that modifyBar function at all.

(See http://book.realworldhaskell.org/read/code-case-study-parsing-a-binary-data-format.html#id625467)

Body:
I know Haskell isn't OO so it isn't strictly a 'member variable'.

data Foo = Foo {
    bar :: Int,
    moo :: Int,
    meh :: Int,
    yup :: Int
}

modifyBar (Foo b m me y) = (Foo b' m me y)
    where b' = 2

This is how my code looks at the moment. The problem is I am now making data types with 16 or more members. When I need to modify a single member it results in very verbose code. Is there a way around this?

Body:
modifyBar foo = foo { bar = 2 }

This syntax will copy foo, and then modify the bar field of that copy to 2. This could be naturally extended to more fields, so you don't need to write that modifyBar function at all.

(See http://book.realworldhaskell.org/read/code-case-study-parsing-a-binary-data-format.html#id625467)