问:
Query Performance Optimization
I have this mysql query :

```<code>SELECT tbl.userid, tbl.name, tbl.courseid, tbl.fullname, IFNULL(tbl.instance, '-') instance, IFNULL(tbl.activityname, '-') activityname,
    IFNULL(tbl.module, '-') module, IFNULL(tbl.attempt, '-') attempt, IFNULL(tbl.score, '-') score,
    CASE tbl.module WHEN 'quiz' THEN (
        CASE WHEN (tbl.attempt IS NULL AND tbl.score IS NULL) THEN 'NOT YET'
        WHEN (tbl.attempt IS NOT NULL AND tbl.score IS NULL) THEN 'ATTEMPT'
        WHEN (tbl.attempt IS NOT NULL AND tbl.score IS NOT NULL) THEN 'FINISH'
        END)
    WHEN 'scorm' THEN (
        CASE WHEN tbl.attempt IS NULL THEN 'NOT YET'
        ELSE (SELECT `status` FROM mdl_scorm_logs WHERE scormid = tbl.instance AND userid = tbl.userid)
        END)
    ELSE '-'
    END `status`
FROM (
    SELECT tbl1.userid, tbl1.name, tbl1.courseid, tbl1.fullname, tbl2.instance,
        CASE tbl2.module WHEN 'quiz' THEN (SELECT `name` FROM mdl_quiz WHERE id = tbl2.instance AND course = tbl1.courseid)
        WHEN 'scorm' THEN (SELECT `name` FROM mdl_scorm WHERE id = tbl2.instance AND course = tbl1.courseid)
        END activityname
        , tbl2.module,
        CASE tbl2.module WHEN 'quiz' THEN (SELECT MAX(attempt) FROM mdl_quiz_attempts WHERE quiz = tbl2.instance AND userid = tbl1.userid)
        WHEN 'scorm' THEN (SELECT MAX(attempt) FROM mdl_scorm_scoes_track WHERE scormid = tbl2.instance AND userid = tbl1.userid )
        END attempt,
        (SELECT CONCAT(TRUNCATE(ROUND(gg.finalgrade / gi.grademax * 100, 2), 2), ' %')
        FROM mdl_grade_grades gg
        JOIN mdl_grade_items gi ON gg.itemid = gi.id
        WHERE gg.userid = tbl1.userid AND gi.courseid = tbl1.courseid AND gi.itemname = activityname AND gi.itemtype = 'mod'
            AND gi.itemmodule = tbl2.module AND gi.iteminstance = tbl2.instance) score
    FROM (
        SELECT u.id userid, CONCAT(u.firstname, ' ', u.lastname) `name`, c.id courseid, c.fullname
        FROM mdl_user u
        JOIN mdl_role_assignments ra ON u.id = ra.userid
        JOIN mdl_context co ON ra.contextid = co.id
        JOIN mdl_role r ON ra.roleid = r.id
        JOIN mdl_course c ON co.instanceid = c.id
        JOIN mdl_enrol e ON c.id = e.courseid
        JOIN mdl_user_enrolments ue ON e.id = ue.enrolid AND u.id = ue.userid
        WHERE r.archetype = 'student') tbl1
    LEFT JOIN (
        SELECT cm.course, m.name module, cm.instance FROM mdl_course_modules cm
        JOIN mdl_modules m ON cm.module = m.id
        WHERE m.name IN ('quiz', 'scorm')
        ) tbl2
    ON tbl1.courseid = tbl2.course) tbl
WHERE tbl.userid = '4' AND tbl.courseid = '8'
GROUP BY tbl.courseid, tbl.instance
ORDER BY tbl.name, tbl.fullname, tbl.activityname
</code>```

Result after I use EXPLAIN :

```<code>id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY <derived3>  ALL                 122 Using where; Using temporary; Using filesort
3   DERIVED <derived9>  ALL                 42
3   DERIVED <derived10> ALL                 23
10  DERIVED m   range   PRIMARY,mdl_modu_nam_ix mdl_modu_nam_ix 62      2   Using where; Using index
10  DERIVED cm  ref mdl_courmodu_mod_ix mdl_courmodu_mod_ix 8   moodle.m.id 4
9   DERIVED r   ref PRIMARY,mdl_role_arc_ix mdl_role_arc_ix 92      1   Using where; Using index
9   DERIVED ra  ref mdl_roleassi_rol_ix,mdl_roleassi_con_ix,mdl_roleassi_use_ix mdl_roleassi_rol_ix 8   moodle.r.id 5
9   DERIVED u   eq_ref  PRIMARY PRIMARY 8   moodle.ra.userid    1
9   DERIVED co  eq_ref  PRIMARY,mdl_cont_ins_ix PRIMARY 8   moodle.ra.contextid 1
9   DERIVED e   ref PRIMARY,mdl_enro_cou_ix mdl_enro_cou_ix 8   moodle.co.instanceid    1   Using index
9   DERIVED c   eq_ref  PRIMARY PRIMARY 8   moodle.co.instanceid    1
9   DERIVED ue  eq_ref  mdl_userenro_enruse_uix,mdl_userenro_enr_ix,mdl_userenro_use_ix mdl_userenro_enruse_uix 16  moodle.e.id,moodle.ra.userid    1   Using index
8   DEPENDENT SUBQUERY  gi  ref PRIMARY,mdl_graditem_itenee_ix,mdl_graditem_cou_ix  mdl_graditem_cou_ix 9   tbl1.courseid   1   Using where
8   DEPENDENT SUBQUERY  gg  eq_ref  mdl_gradgrad_useite_uix,mdl_gradgrad_ite_ix,mdl_gradgrad_use_ix mdl_gradgrad_useite_uix 16  tbl1.userid,moodle.gi.id    1   Using where
7   DEPENDENT SUBQUERY  mdl_scorm_scoes_track   ref mdl_scorscoetrac_usescosco_uix,mdl_scorscoetrac_use_ix,mdl_scorscoetrac_sco_ix  mdl_scorscoetrac_usescosco_uix  16  tbl1.userid,tbl2.instance   6   Using where; Using index
6   DEPENDENT SUBQUERY  mdl_quiz_attempts   ref mdl_quizatte_use_ix,mdl_quizatte_qui_ix mdl_quizatte_qui_ix 8   tbl2.instance   2   Using where
5   DEPENDENT SUBQUERY  mdl_scorm   eq_ref  PRIMARY,mdl_scor_cou_ix PRIMARY 8   tbl2.instance   1   Using where
4   DEPENDENT SUBQUERY  mdl_quiz    eq_ref  PRIMARY,mdl_quiz_cou_ix PRIMARY 8   tbl2.instance   1   Using where
2   DEPENDENT SUBQUERY  mdl_scorm_logs  eq_ref  PRIMARY PRIMARY 16  func,func   1   Using where
</code>```

Any idea to optimize it?
Thank You.

答:
OMG. Denormalization is the only way to handle this situation. Ok, you will optimize this query. What will you do next time, when you will have to join 15 tables in single query?

Your query looks like report. You should design your database for reporting. Check out following links, it may be useful for you.

http://en.wikipedia.org/wiki/Denormalization

http://en.wikipedia.org/wiki/Star_schema

Title: Query Performance Optimization

Body:
I have this mysql query :

SELECT tbl.userid, tbl.name, tbl.courseid, tbl.fullname, IFNULL(tbl.instance, '-') instance, IFNULL(tbl.activityname, '-') activityname,
    IFNULL(tbl.module, '-') module, IFNULL(tbl.attempt, '-') attempt, IFNULL(tbl.score, '-') score,
    CASE tbl.module WHEN 'quiz' THEN (
        CASE WHEN (tbl.attempt IS NULL AND tbl.score IS NULL) THEN 'NOT YET'
        WHEN (tbl.attempt IS NOT NULL AND tbl.score IS NULL) THEN 'ATTEMPT'
        WHEN (tbl.attempt IS NOT NULL AND tbl.score IS NOT NULL) THEN 'FINISH'
        END)
    WHEN 'scorm' THEN (
        CASE WHEN tbl.attempt IS NULL THEN 'NOT YET'
        ELSE (SELECT `status` FROM mdl_scorm_logs WHERE scormid = tbl.instance AND userid = tbl.userid)
        END)
    ELSE '-'
    END `status`
FROM (
    SELECT tbl1.userid, tbl1.name, tbl1.courseid, tbl1.fullname, tbl2.instance,
        CASE tbl2.module WHEN 'quiz' THEN (SELECT `name` FROM mdl_quiz WHERE id = tbl2.instance AND course = tbl1.courseid)
        WHEN 'scorm' THEN (SELECT `name` FROM mdl_scorm WHERE id = tbl2.instance AND course = tbl1.courseid)
        END activityname
        , tbl2.module,
        CASE tbl2.module WHEN 'quiz' THEN (SELECT MAX(attempt) FROM mdl_quiz_attempts WHERE quiz = tbl2.instance AND userid = tbl1.userid)
        WHEN 'scorm' THEN (SELECT MAX(attempt) FROM mdl_scorm_scoes_track WHERE scormid = tbl2.instance AND userid = tbl1.userid )
        END attempt,
        (SELECT CONCAT(TRUNCATE(ROUND(gg.finalgrade / gi.grademax * 100, 2), 2), ' %')
        FROM mdl_grade_grades gg
        JOIN mdl_grade_items gi ON gg.itemid = gi.id
        WHERE gg.userid = tbl1.userid AND gi.courseid = tbl1.courseid AND gi.itemname = activityname AND gi.itemtype = 'mod'
            AND gi.itemmodule = tbl2.module AND gi.iteminstance = tbl2.instance) score
    FROM (
        SELECT u.id userid, CONCAT(u.firstname, ' ', u.lastname) `name`, c.id courseid, c.fullname
        FROM mdl_user u
        JOIN mdl_role_assignments ra ON u.id = ra.userid
        JOIN mdl_context co ON ra.contextid = co.id
        JOIN mdl_role r ON ra.roleid = r.id
        JOIN mdl_course c ON co.instanceid = c.id
        JOIN mdl_enrol e ON c.id = e.courseid
        JOIN mdl_user_enrolments ue ON e.id = ue.enrolid AND u.id = ue.userid
        WHERE r.archetype = 'student') tbl1
    LEFT JOIN (
        SELECT cm.course, m.name module, cm.instance FROM mdl_course_modules cm
        JOIN mdl_modules m ON cm.module = m.id
        WHERE m.name IN ('quiz', 'scorm')
        ) tbl2
    ON tbl1.courseid = tbl2.course) tbl
WHERE tbl.userid = '4' AND tbl.courseid = '8'
GROUP BY tbl.courseid, tbl.instance
ORDER BY tbl.name, tbl.fullname, tbl.activityname

Result after I use EXPLAIN :

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   PRIMARY <derived3>  ALL                 122 Using where; Using temporary; Using filesort
3   DERIVED <derived9>  ALL                 42
3   DERIVED <derived10> ALL                 23
10  DERIVED m   range   PRIMARY,mdl_modu_nam_ix mdl_modu_nam_ix 62      2   Using where; Using index
10  DERIVED cm  ref mdl_courmodu_mod_ix mdl_courmodu_mod_ix 8   moodle.m.id 4
9   DERIVED r   ref PRIMARY,mdl_role_arc_ix mdl_role_arc_ix 92      1   Using where; Using index
9   DERIVED ra  ref mdl_roleassi_rol_ix,mdl_roleassi_con_ix,mdl_roleassi_use_ix mdl_roleassi_rol_ix 8   moodle.r.id 5
9   DERIVED u   eq_ref  PRIMARY PRIMARY 8   moodle.ra.userid    1
9   DERIVED co  eq_ref  PRIMARY,mdl_cont_ins_ix PRIMARY 8   moodle.ra.contextid 1
9   DERIVED e   ref PRIMARY,mdl_enro_cou_ix mdl_enro_cou_ix 8   moodle.co.instanceid    1   Using index
9   DERIVED c   eq_ref  PRIMARY PRIMARY 8   moodle.co.instanceid    1
9   DERIVED ue  eq_ref  mdl_userenro_enruse_uix,mdl_userenro_enr_ix,mdl_userenro_use_ix mdl_userenro_enruse_uix 16  moodle.e.id,moodle.ra.userid    1   Using index
8   DEPENDENT SUBQUERY  gi  ref PRIMARY,mdl_graditem_itenee_ix,mdl_graditem_cou_ix  mdl_graditem_cou_ix 9   tbl1.courseid   1   Using where
8   DEPENDENT SUBQUERY  gg  eq_ref  mdl_gradgrad_useite_uix,mdl_gradgrad_ite_ix,mdl_gradgrad_use_ix mdl_gradgrad_useite_uix 16  tbl1.userid,moodle.gi.id    1   Using where
7   DEPENDENT SUBQUERY  mdl_scorm_scoes_track   ref mdl_scorscoetrac_usescosco_uix,mdl_scorscoetrac_use_ix,mdl_scorscoetrac_sco_ix  mdl_scorscoetrac_usescosco_uix  16  tbl1.userid,tbl2.instance   6   Using where; Using index
6   DEPENDENT SUBQUERY  mdl_quiz_attempts   ref mdl_quizatte_use_ix,mdl_quizatte_qui_ix mdl_quizatte_qui_ix 8   tbl2.instance   2   Using where
5   DEPENDENT SUBQUERY  mdl_scorm   eq_ref  PRIMARY,mdl_scor_cou_ix PRIMARY 8   tbl2.instance   1   Using where
4   DEPENDENT SUBQUERY  mdl_quiz    eq_ref  PRIMARY,mdl_quiz_cou_ix PRIMARY 8   tbl2.instance   1   Using where
2   DEPENDENT SUBQUERY  mdl_scorm_logs  eq_ref  PRIMARY PRIMARY 16  func,func   1   Using where

Any idea to optimize it?
Thank You.


来源: stackexchange

问:
Div height according to content
I am working on a Modal with fixed header and footer.

Here is the Jsfiddle example

Currently the scrollable-stuff class height is 80%. If the content is less and there is no scrolling then i need to reduce the height and take the height of the content.

For example this example has a less content and there is no scroller but there is a empty space. I need to take the height of the content in case if there is no scrolling.

Any help or suggestion would be appreciated

Thanks in advace.

答:
Instead of using height: 300px;

you can use max-height: 300px;

Because max-height tells the browser that the height can be less if the content is less but not greater than the specified height which in your case is 300px.

ContentLicense: CC BY-SA 4.0

Title: Div height according to content


问:
ReactNative Webview
React js : I am trying to open my react js production build folder under which the one html file is placed after run npm run build.

React Native: I am using react-native-webview Plugin for open the same index.html file. For android I placed this folder under assets.

The codebase giving me error File_Not_Found.

The build html file is minify html file. When I try to use any url here or any development plain html it is working fine. For this minify file it is not working.

Please help.

I am using this code for android react native.

if(isAndroid){
      console.log(isAndroid);
      return (

      )
    }

I want to open production this react js build folder html file in react native webview.

答:
Create an object

```<code>const index = require('./assets/index.html');
</code>```

set your source to the object instead of using a uri.

Title: ReactNative Webview

Body:
Create an object

const index = require('./assets/index.html');

set your source to the object instead of using a uri.


问:
Material table not sorting records
I can't find what is wrong with my script, the list loads OK but when clicking on the table headers the sorting does not work.

I have tried putting the sorting part inside a TimeOut on the response and also moving it to the ngAfterViewInit() function. Everything else on my app works fine except for this.

Heres is the ts code:

```<code>import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CatalogosService } from 'src/app/services/catalogos.service';
import { MatPaginator, MatSort, MatTableDataSource, MatTableModule, MatTable,
  MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Response } from 'src/app/classes/response';

@Component({
  selector: 'app-lista-proveedores',
  templateUrl: './lista-proveedores.component.html',
  styleUrls: ['./lista-proveedores.component.css']
})
export class ListaProveedoresComponent implements OnInit {

  proveedores: any[];
  listData: MatTableDataSource<any>;
  displayColumns: string[]=['id','nombre','acciones'];
  searchKey: string;
  //spinner: SpinnerComponent= new SpinnerComponent;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(private proveedorService: CatalogosService,
              private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.getRecords();
  }

  getRecords(): void{
    this.proveedorService.getItems()
    .subscribe(
      (response: Response) => {
        //this.proveedores = response.object;
        this.listData= new MatTableDataSource(response.object);
        this.listData.sort= this.sort;
        this.listData.paginator= this.paginator;
        console.log("List data: ", this.sort);
      });
      this.changeDetectorRefs.detectChanges();
  }

}
</code>```

And here is the html:

```<code><div class="col-lg-12">
  <div class="row">
      <div class="col-lg-9 text-center">
          <h3 class="title-divider">
              <span>List</span>
          </h3>
      </div>
      <div class="col-lg-3 text-center">

      </div>
  </div>
  <div class="row">
      <div class="col-lg-12">
          <div class="mat-elevation-z8">
              <mat-table #table [dataSource]="listData" matSort>
                  <ng-container matColumnDef="id">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.ID}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="nombre">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>Nombre</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.Name}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="acciones">
                      <mat-header-cell *matHeaderCellDef>Acciones</mat-header-cell>
                      <mat-cell *matCellDef="let row">
                          <button mat-icon-button (click)="onDetail(row)"><mat-icon>details</mat-icon></button>
                          <button mat-icon-button (click)="onEdit(row)"><mat-icon>launch</mat-icon></button>
                          <button mat-icon-button color="warn" (click)="onDelete(row)"><mat-icon>delete_outline</mat-icon></button>
                      </mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="loading">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          Loading data
                      </mat-footer-cell>
                  </ng-container>
                  <ng-container matColumnDef="noData">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          No data
                      </mat-footer-cell>
                  </ng-container>
                  <mat-header-row *matHeaderRowDef="displayColumns; sticky:true "></mat-header-row>
                  <mat-row *matRowDef="let row; columns: displayColumns"></mat-row>
                  <mat-footer-row *matFooterRowDef="['loading']" [ngClass]="{'hide':listData!=null}"></mat-footer-row>
                  <mat-footer-row *matFooterRowDef="['noData']" [ngClass]="{'hide':!(listData!=null && listData.data.length==0)}"></mat-footer-row>
              </mat-table>
              <mat-paginator [pageSizeOptions]="[5, 10, 15, 25]" [pageSize]="5" showFirstLastButtons></mat-paginator>
          </div>
      </div>
  </div>

</div>
</code>```

Here's also the console log displaying the MatSort object:

```<code>MatSort {_disabled: false, _isInitialized: true, _pendingSubscribers: null, initialized: Observable, sortables: Map(2), …}
direction: (...)
disableClear: (...)
disabled: (...)
initialized: Observable
_isScalar: false
_subscribe: ƒ (subscriber)
arguments: (...)
caller: (...)
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: core.es5.js:474
[[Scopes]]: Scopes[4]
__proto__: Object
sortChange: EventEmitter
closed: false
hasError: false
isStopped: false
observers: (3) [Subscriber, Subscriber, Subscriber]
thrownError: null
__isAsync: false
_isScalar: false
__proto__: Subject
sortables: Map(2)
size: (...)
__proto__: Map
[[Entries]]: Array(2)
0: {"id" => MatSortHeader}
1: {"nombre" => MatSortHeader}
length: 2
start: "asc"
_direction: ""
_disabled: false
_isInitialized: true
_pendingSubscribers: null
_stateChanges: Subject {_isScalar: false, observers: Array(2), closed: false, isStopped: false, hasError: false, …}
__proto__: class_1
</code>```

I've imported MatSortModule and MatTableModule on the AppModule and I have no errors displayed by the JS console.

答: As both comments stated, the problem was that the column names (matColumnDef) didn't match the model from the server.</p>

Title: Material table not sorting records

Body:
I can't find what is wrong with my script, the list loads OK but when clicking on the table headers the sorting does not work.

I have tried putting the sorting part inside a TimeOut on the response and also moving it to the ngAfterViewInit() function. Everything else on my app works fine except for this.

Heres is the ts code:

import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CatalogosService } from 'src/app/services/catalogos.service';
import { MatPaginator, MatSort, MatTableDataSource, MatTableModule, MatTable,
  MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Response } from 'src/app/classes/response';

@Component({
  selector: 'app-lista-proveedores',
  templateUrl: './lista-proveedores.component.html',
  styleUrls: ['./lista-proveedores.component.css']
})
export class ListaProveedoresComponent implements OnInit {

  proveedores: any[];
  listData: MatTableDataSource<any>;
  displayColumns: string[]=['id','nombre','acciones'];
  searchKey: string;
  //spinner: SpinnerComponent= new SpinnerComponent;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(private proveedorService: CatalogosService,
              private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.getRecords();
  }

  getRecords(): void{
    this.proveedorService.getItems()
    .subscribe(
      (response: Response) => {
        //this.proveedores = response.object;
        this.listData= new MatTableDataSource(response.object);
        this.listData.sort= this.sort;
        this.listData.paginator= this.paginator;
        console.log("List data: ", this.sort);
      });
      this.changeDetectorRefs.detectChanges();
  }

}

And here is the html:

              List

              <mat-table #table [dataSource]="listData" matSort>
                  <ng-container matColumnDef="id">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.ID}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="nombre">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>Nombre</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.Name}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="acciones">
                      <mat-header-cell *matHeaderCellDef>Acciones</mat-header-cell>
                      <mat-cell *matCellDef="let row">
                          <button mat-icon-button (click)="onDetail(row)"><mat-icon>details</mat-icon></button>
                          <button mat-icon-button (click)="onEdit(row)"><mat-icon>launch</mat-icon></button>
                          <button mat-icon-button color="warn" (click)="onDelete(row)"><mat-icon>delete_outline</mat-icon></button>
                      </mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="loading">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          Loading data
                      </mat-footer-cell>
                  </ng-container>
                  <ng-container matColumnDef="noData">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          No data
                      </mat-footer-cell>
                  </ng-container>
                  <mat-header-row *matHeaderRowDef="displayColumns; sticky:true "></mat-header-row>
                  <mat-row *matRowDef="let row; columns: displayColumns"></mat-row>
                  <mat-footer-row *matFooterRowDef="['loading']" [ngClass]="{'hide':listData!=null}"></mat-footer-row>
                  <mat-footer-row *matFooterRowDef="['noData']" [ngClass]="{'hide':!(listData!=null && listData.data.length==0)}"></mat-footer-row>
              </mat-table>
              <mat-paginator [pageSizeOptions]="[5, 10, 15, 25]" [pageSize]="5" showFirstLastButtons></mat-paginator>

Here's also the console log displaying the MatSort object:

MatSort {_disabled: false, _isInitialized: true, _pendingSubscribers: null, initialized: Observable, sortables: Map(2), …}
direction: (...)
disableClear: (...)
disabled: (...)
initialized: Observable
_isScalar: false
_subscribe: ƒ (subscriber)
arguments: (...)
caller: (...)
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: core.es5.js:474
[[Scopes]]: Scopes[4]
__proto__: Object
sortChange: EventEmitter
closed: false
hasError: false
isStopped: false
observers: (3) [Subscriber, Subscriber, Subscriber]
thrownError: null
__isAsync: false
_isScalar: false
__proto__: Subject
sortables: Map(2)
size: (...)
__proto__: Map
[[Entries]]: Array(2)
0: {"id" => MatSortHeader}
1: {"nombre" => MatSortHeader}
length: 2
start: "asc"
_direction: ""
_disabled: false
_isInitialized: true
_pendingSubscribers: null
_stateChanges: Subject {_isScalar: false, observers: Array(2), closed: false, isStopped: false, hasError: false, …}
__proto__: class_1

I've imported MatSortModule and MatTableModule on the AppModule and I have no errors displayed by the JS console.


问:
Geting SIGBUS (Bus error) @ 0 (0)killed by SIGBUS (core dumped) in Redhat
I have process that works perfectly in the same machine in 2 accounts but when i copy the process to other account and run the process im getting core dump.
when i run the process with strace in the end im getting :

--- SIGBUS (Bus error) @ 0 (0) ---
  +++ killed by SIGBUS (core dumped) +++

when i open the core dump im getting :

```<code>#0  0x000000360046fed3 in malloc_consolidate () from /lib64/libc.so.6
#1  0x00000036004723fd in _int_malloc () from /lib64/libc.so.6
#2  0x000000360047402a in malloc () from /lib64/libc.so.6
#3  0x00000036004616ba in __fopen_internal () from /lib64/libc.so.6
#4  0x0000000000fe9652 in LogMngr::OpenFile (this=0x2aaaaad17010, iLogIndex=0) at LogMngr.c:801
</code>```

i can see it something with opening the file for logging , but why it only in one account and in the other is fine ?

答: You can get a SIGBUS from an unaligned memory access .  Are you using something  like mmap, shared memory regions, or something similar ?</p>

ContentLicense: CC BY-SA 3.0

Body:
I have process that works perfectly in the same machine in 2 accounts but when i copy the process to other account and run the process im getting core dump.
when i run the process with strace in the end im getting :

--- SIGBUS (Bus error) @ 0 (0) ---
  +++ killed by SIGBUS (core dumped) +++

when i open the core dump im getting :

#0  0x000000360046fed3 in malloc_consolidate () from /lib64/libc.so.6
#1  0x00000036004723fd in _int_malloc () from /lib64/libc.so.6
#2  0x000000360047402a in malloc () from /lib64/libc.so.6
#3  0x00000036004616ba in __fopen_internal () from /lib64/libc.so.6
#4  0x0000000000fe9652 in LogMngr::OpenFile (this=0x2aaaaad17010, iLogIndex=0) at LogMngr.c:801

i can see it something with opening the file for logging , but why it only in one account and in the other is fine ?


问:
Use a python package in the same project folder in visual studio code

I created my customized package called 'dto' in my project folder.
But It does not recognize this package and module.

How can I make my visual studio code to find it?

In Pycharm, if I create new package, it automatically detects that.

I executed my simulator.py script in my simulation package.

答:
I have encountered the same problem. It seems visual studio code cannot automatically detect new python package. It has something to do with $PYTHONPATH configuration. I found an official reference from visual studio code documentation. Please have a look at this doc.

adding a dev.env file inside your project

```<code>PYTHONPATH=${workspaceFolder}:${PYTHONPATH}
</code>```

adding the following in your workspace settings.json config file

```<code>"python.envFile": "${workspaceFolder}/dev.env"
</code>```

This works for me. The debugger can find modules in the new package. Hopefully, this will help you.

Body:
I have encountered the same problem. It seems visual studio code cannot automatically detect new python package. It has something to do with $PYTHONPATH configuration. I found an official reference from visual studio code documentation. Please have a look at this doc.

adding a dev.env file inside your project

PYTHONPATH=${workspaceFolder}:${PYTHONPATH}

adding the following in your workspace settings.json config file

"python.envFile": "${workspaceFolder}/dev.env"

This works for me. The debugger can find modules in the new package. Hopefully, this will help you.


问:
How to predict encounters between a ship and a body's sphere of influence in 2D
Long time listener, first time caller. I'm making a little hobby game in XNA, its about transport ships in space, analogous to container ships at sea. I need to be able to predict the encounter between a Ship and a planet/moons gravitational sphere of influence in a restricted 2D environment. The positions at time of the Ship and planet/moon, Body for short, are determined from keplerian orbital elements. The Ship and Body both orbit the same centre of attraction.

The approach I have devised so far is first to do some preliminary checks on the apoapsis and periapsis (farthest and closest points from centre of attraction) to see if an encounter is possible. Between checks such as this and if the Ship's orbit is open (hyperbolic, I approximate the parabola case to a hyperbola), it can rule out many scenarios where there could not be an encounter.

If these checks determine an encounter is possible, I determine the minimum and maximum distance from centre of attraction that the Ship is eligible for an encounter. I then get the intersection points of the ships orbit with the two circles defined by that minimum and maximum. This results in zero, two, or four, points on the Ship's orbit, defining zero, one, or two periods where it could encounter the sphere of the Body. At this point if there are zero intersections it is possible the whole of the Ship orbit is in the encounter zone, this is probably an uncommon extreme case but would need to be covered.

I can get the times that the Ship will pass those points on it's orbit, giving one or two windows of time to check for encounter, but from there my best solution is searching the time span by dividing it into steps, calculating the Body's position at those times, and then testing for encounter.

The trouble with that approach is knowing the size to make the steps to efficiently find the encounter. Getting the Body's position at time is somewhat expensive so I'd rather do it as little as possible, but steps too large could potentially miss the encounter.

Are there any properties of confocal conic shapes that could help reduce the search space? Or are there other ways to predict encounter/collision between what is effectively a point moving along a conic path and a circle moving along an ellipse sharing a focal point.

答:
Since this hasn't got an accepted answer yet and I don't see the below calculations I'll add these in the hopes that it will help someone.
I've not figured out how to get a date time, I have however figured out how to get angles.
This will get you the distance between the orbiting body and the soi (or ship) if you know the angle:

```<code>public static double RadiusAtAngle(double angle, double semiLatusRectum, double eccentricity)
{
    return semiLatusRectum / (1 + eccentricity * Math.Cos(angle));
}
</code>```

More importantly, flipping that calc gets you the angle to the soi edge if you know the semiLatusRectum and the eccentricity (radius here will be the distance from the body to the soi edge):

```<code>public static double AngleAtRadus(double radius, double semiLatusRectum, double eccentricity)
{
    //r = p / (1 + e * cos(θ))
    //1 + e * cos(θ) = p/r
    //((p / r) -1) / e = cos(θ)
    return Math.Acos((semiLatusRectum / radius - 1) / eccentricity);
}
</code>```

For reference, semiLatusRectum can be found from the semiMajorAxis and eccentricity:

```<code>public static double SemiLatusRectum(double SemiMajorAxis, double eccentricity)
{
    if (eccentricity == 0)//ie a circle
        return SemiMajorAxis;
    return SemiMajorAxis * (1 - eccentricity * eccentricity);
}
</code>```

Note that these calcs will also work for hyperbolic trajectories.

Body:
Since this hasn't got an accepted answer yet and I don't see the below calculations I'll add these in the hopes that it will help someone.
I've not figured out how to get a date time, I have however figured out how to get angles.
This will get you the distance between the orbiting body and the soi (or ship) if you know the angle:

public static double RadiusAtAngle(double angle, double semiLatusRectum, double eccentricity)
{
    return semiLatusRectum / (1 + eccentricity * Math.Cos(angle));
}

More importantly, flipping that calc gets you the angle to the soi edge if you know the semiLatusRectum and the eccentricity (radius here will be the distance from the body to the soi edge):

public static double AngleAtRadus(double radius, double semiLatusRectum, double eccentricity)
{
    //r = p / (1 + e * cos(θ))
    //1 + e * cos(θ) = p/r
    //((p / r) -1) / e = cos(θ)
    return Math.Acos((semiLatusRectum / radius - 1) / eccentricity);
}

For reference, semiLatusRectum can be found from the semiMajorAxis and eccentricity:

public static double SemiLatusRectum(double SemiMajorAxis, double eccentricity)
{
    if (eccentricity == 0)//ie a circle
        return SemiMajorAxis;
    return SemiMajorAxis * (1 - eccentricity * eccentricity);
}

Note that these calcs will also work for hyperbolic trajectories.


问:
How to fix "symbolic tensors" use "steps_per_epoch" but not "batch_size" bug in a simple conv2d+liquid state machine net
I am making a simple conv2d + dynamic reservoir (a customized recurrent layer with random / fixed connections that only outputs the last time step node states). The reservoir is written as a lambda layer to implement a simple equation as shown in the code. The model can be constructed by Keras.

I hope the model to be trained to classify some image sequences with a given batch size. (e.g. batch_size = 2) So ideally Keras should allocate batches of size 2x3x8x8x1 since the dataset is of the size 10x3x8x8x1. The time distributed Conv2d layer is supposed to return 2x3x6x6x3. The subsequent customized flatten layer should flat non-time dimensions and return 2x3x108. The reservior layer with 108 nodes should return 2x108. And the last read-out layer should return 2x5.

import keras
from keras.layers import Dense, Convolution2D, Activation, Lambda
from keras.layers.wrappers import TimeDistributed
from keras.models import Sequential

from keras import backend as K
import tensorflow as tf

import numpy as np

# Flatten the non-time dimensions
def flatten_tstep(x_in): # Input shape (None, 3, 6, 6, 3), Output shape (None, 3, 108)
    shape = K.shape( x_in ) # tensor shape
    x_out = K.reshape( x_in, [shape[0], shape[1], K.prod(shape[1:])] )
    return x_out

def flatten_tstep_shape( x_shape ) :
    n_batch, n_tsteps, n_rows, n_cols, n_filters = x_shape
    output_shape = ( n_batch, n_tsteps, n_rows * n_cols * n_filters ) # Flatten
    return output_shape

# Simple Reservior
# Use a single batch as an example, the input (size 3x108) is of 3 time steps to the 108 nodes in the reserivor.
# The states of the nodes are stat_neuron (size 1x108)
# For t in range(3)
#   stat_neuron = stat_neuron * decay_coefficient + input[t, :] + recurrent_connection_matrix * stat_neuron
# End
# This layer effectively returns the states of the node in the last time step
def ag_reservior(x_in): # Input shape (None, 3, 108), Output shape (None, 108)
    shape = K.shape( x_in ) # tensor shape
    stat_neuron = K.zeros([shape[0], shape[2]]) # initialize Neuron states
    t_step = tf.constant(0) # Initialize time counter, shifted by 1
    t_max = tf.subtract(shape[1], tf.constant(1)) # Maximum time steps, shifted by 1
    x = x_in
    def cond(t_step, t_max, stat_neuron, x):
        return tf.less(t_step, t_max)
    def body(t_step, t_max, stat_neuron, x):
        global RC_MATRIX, C_DECAY # Connection matrix, decay constant
        temp = tf.scalar_mul(C_DECAY, stat_neuron) #  stat_neuron * decay_coefficient
        temp = tf.add(temp, x[:, t_step, :]) # stat_neuron * decay_coefficient + input[t, :]
        temp = tf.add(temp, tf.einsum('ij,bj->bi', RC_MATRIX, stat_neuron)) # out[batch,i]=sum_j RC_MATRIX[i,j]*stat_neuron[batch,j]
        return [tf.add(t_step, 1), t_max, temp, x]
    res = tf.while_loop(cond, body, [t_step, t_max, stat_neuron, x])
    return res[2]

def ag_reservior_shape( x_shape ) :
    in_batch, in_tsteps, in_nodes = x_shape
    output_shape = ( in_batch, in_nodes )
    return output_shape

#%% Parameters

n_sample = 10; # number of samples;
n_tstep = 3; # number of time steps per sample
n_row = 8; # number of rows per frame
n_col = 8; # number of columns per frame
n_channel = 1; # number of channel

RC_MATRIX = K.random_normal([108, 108]) # Reservior layer node recurrent connection matrix, note there are 108 nodes
C_DECAY = K.constant(0.9) # Recurrent layer node time-to-time decay coefficient

data = K.random_normal([n_sample, n_tstep, n_row, n_col, 1]) # Some random dataset
# data = np.random.randn(n_sample, n_tstep, n_row, n_col, 1)
label = np.random.randint(5, size=n_sample) # Some random dataset labels
label_onehot = K.one_hot(label, 5)

x_train = data
y_train = label_onehot

x_test = data
y_test = label_onehot

#%% Model

model=Sequential();

# Convolution Kernels: Input shape (batch_size, 3, 8, 8, 1), Output shape (batch_size, 3, 6, 6, 3)
model.add(TimeDistributed(Convolution2D(3, (3, 3), strides=1, padding='valid', use_bias=False,
                                        kernel_initializer='random_uniform', trainable=False), input_shape = (n_tstep, n_row, n_col, n_channel)))

# Flatten non-time dimensions: Input shape (batch_size, 3, 6, 6, 3), Output shape (batch_size, 3, 108)
model.add(Lambda(flatten_tstep, output_shape = flatten_tstep_shape))

# Reservior: Input shape (batch_size 3, 108), Output shape (batch_size, 108)
model.add(Lambda(ag_reservior, output_shape = ag_reservior_shape))

# Reservior Read-out: Input shape (batch_size, 108), Output shape (batch_size, 5)
model.add(Dense(5, use_bias=False))
model.add(Activation('softmax'))

# Check model
model.summary()

#%% Training
opt = keras.optimizers.rmsprop(lr = 0.01, decay = 1e-6)
model.compile(loss='categorical_crossentropy', optimizer = opt, metrics = ['acc'])
history = model.fit(x_train, y_train, epochs = 50, validation_data = (x_test, y_test), batch_size = 2)
```

However, Keras said "If your data is in the form of symbolic tensors, you should specify the steps_per_epoch argument (instead of the batch_size argument, because symbolic tensors are expected to produce batches of input data)."

Could you advise on how to let Keras correctly recognize the batch size and proceed to the training? (Note that the Conv2d layer is fixed, the lambda layers are also fixed, only the last dense layer needs training.)

Thank you in advance.

答:
It's resolved by using this code...

import keras
from keras.datasets import mnist
from keras.layers import Convolution2D, Dense, Flatten, Activation, Lambda
from keras.layers.wrappers import TimeDistributed
from keras.models import Sequential
import scipy.io

from keras import backend as K
import tensorflow as tf

import numpy as np
import matplotlib.pyplot as plt

# Simple Reservior
# Use a single batch as an example, the input (size 3x108) is of 3 time steps to the 108 nodes in the reserivor.
# The states of the nodes are stat_neuron (size 1x108)
# For t in range(3)
#   stat_neuron = stat_neuron * decay_coefficient + input[t, :] + recurrent_connection_matrix * stat_neuron
# End
# This layer effectively returns the states of the node in the last time step
def ag_reservior(x_in): # Input shape (None, 3, 108), Output shape (None, 108)
    shape = K.shape( x_in ) # tensor shape
    stat_neuron = K.zeros([shape[0], shape[2]]) # initialize Neuron states
    t_step = tf.constant(0) # Initialize time counter, shifted by 1
    t_max = shape[1] # Maximum time steps, shifted by 1
    x = x_in
    def cond(t_step, t_max, stat_neuron, x):
        return tf.less(t_step, t_max)
    def body(t_step, t_max, stat_neuron, x):
        global RC_MATRIX, C_DECAY # Connection matrix, decay constant
        temp = tf.scalar_mul(C_DECAY, stat_neuron) #  stat_neuron * decay_coefficient
        temp = tf.add(temp, x[:, t_step, :]) # stat_neuron * decay_coefficient + input[t, :]
        temp = tf.add(temp, tf.einsum('ij,bj->bi', RC_MATRIX, stat_neuron)) # out[batch,i]=sum_j RC_MATRIX[i,j]*stat_neuron[batch,j]
        return [tf.add(t_step, 1), t_max, temp, x]
    res = tf.while_loop(cond, body, [t_step, t_max, stat_neuron, x])
    return res[2]

def ag_reservior_shape( x_shape ) :
    in_batch, in_tsteps, in_nodes = x_shape
    output_shape = ( in_batch, in_nodes )
    return output_shape

#%% Parameters

n_neurons = 4096; # number of neurons in the reservoir (same with the last dim of the flatten layer);

RC_MATRIX = K.random_normal([n_neurons, n_neurons], mean=0, stddev=1/n_neurons) # Reservior layer node recurrent connection matrix
C_DECAY = K.constant(0.5) # Diffusive memristor time-to-time decay coefficient

# Load training data from the .mat file
mat_contents = scipy.io.loadmat('mnist_sequence_kerasimport.mat')
x_train = mat_contents['xs_train']
x_test = mat_contents['xs_test']
y_train = mat_contents['ys_train']
y_test = mat_contents['ys_test']
# Reshape x_train, x_test into 5D array
x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], x_train.shape[2], x_train.shape[3], 1)
x_test = x_test.reshape(x_test.shape[0], x_test.shape[1], x_test.shape[2], x_test.shape[3], 1)

#%% Model

model=Sequential();

# Convolution Kernels: Input shape (batch_size, 3, 8, 8, 1), Output shape (batch_size, 3, 8, 8, 64)
model.add(TimeDistributed(Convolution2D(64, (3, 3), strides=1, padding='same', use_bias=False,
                                        kernel_initializer='random_uniform', trainable=False), input_shape = (x_train.shape[1:])))

model.add(TimeDistributed(Flatten()))

# Reservior: Input shape (batch_size 3, 108), Output shape (batch_size, 108)
model.add(Lambda(ag_reservior, output_shape = ag_reservior_shape))

# Reservior Read-out: Input shape (batch_size, 108), Output shape (batch_size, 5)
model.add(Dense(6, use_bias=False))
model.add(Activation('softmax'))

# Check model
model.summary()

#%% Training
opt = keras.optimizers.rmsprop(lr = 0.01, decay = 1e-6)
model.compile(loss='categorical_crossentropy', optimizer = opt, metrics = ['acc'])
history = model.fit(x_train, y_train, epochs = 2, validation_data = (x_test, y_test), batch_size = 50)
```

Body:
I am making a simple conv2d + dynamic reservoir (a customized recurrent layer with random / fixed connections that only outputs the last time step node states). The reservoir is written as a lambda layer to implement a simple equation as shown in the code. The model can be constructed by Keras.

I hope the model to be trained to classify some image sequences with a given batch size. (e.g. batch_size = 2) So ideally Keras should allocate batches of size 2x3x8x8x1 since the dataset is of the size 10x3x8x8x1. The time distributed Conv2d layer is supposed to return 2x3x6x6x3. The subsequent customized flatten layer should flat non-time dimensions and return 2x3x108. The reservior layer with 108 nodes should return 2x108. And the last read-out layer should return 2x5.

import keras
from keras.layers import Dense, Convolution2D, Activation, Lambda
from keras.layers.wrappers import TimeDistributed
from keras.models import Sequential

from keras import backend as K
import tensorflow as tf

import numpy as np

# Flatten the non-time dimensions
def flatten_tstep(x_in): # Input shape (None, 3, 6, 6, 3), Output shape (None, 3, 108)
    shape = K.shape( x_in ) # tensor shape
    x_out = K.reshape( x_in, [shape[0], shape[1], K.prod(shape[1:])] )
    return x_out

def flatten_tstep_shape( x_shape ) :
    n_batch, n_tsteps, n_rows, n_cols, n_filters = x_shape
    output_shape = ( n_batch, n_tsteps, n_rows * n_cols * n_filters ) # Flatten
    return output_shape

# Simple Reservior
# Use a single batch as an example, the input (size 3x108) is of 3 time steps to the 108 nodes in the reserivor.
# The states of the nodes are stat_neuron (size 1x108)
# For t in range(3)
#   stat_neuron = stat_neuron * decay_coefficient + input[t, :] + recurrent_connection_matrix * stat_neuron
# End
# This layer effectively returns the states of the node in the last time step
def ag_reservior(x_in): # Input shape (None, 3, 108), Output shape (None, 108)
    shape = K.shape( x_in ) # tensor shape
    stat_neuron = K.zeros([shape[0], shape[2]]) # initialize Neuron states
    t_step = tf.constant(0) # Initialize time counter, shifted by 1
    t_max = tf.subtract(shape[1], tf.constant(1)) # Maximum time steps, shifted by 1
    x = x_in
    def cond(t_step, t_max, stat_neuron, x):
        return tf.less(t_step, t_max)
    def body(t_step, t_max, stat_neuron, x):
        global RC_MATRIX, C_DECAY # Connection matrix, decay constant
        temp = tf.scalar_mul(C_DECAY, stat_neuron) #  stat_neuron * decay_coefficient
        temp = tf.add(temp, x[:, t_step, :]) # stat_neuron * decay_coefficient + input[t, :]
        temp = tf.add(temp, tf.einsum('ij,bj->bi', RC_MATRIX, stat_neuron)) # out[batch,i]=sum_j RC_MATRIX[i,j]*stat_neuron[batch,j]
        return [tf.add(t_step, 1), t_max, temp, x]
    res = tf.while_loop(cond, body, [t_step, t_max, stat_neuron, x])
    return res[2]

def ag_reservior_shape( x_shape ) :
    in_batch, in_tsteps, in_nodes = x_shape
    output_shape = ( in_batch, in_nodes )
    return output_shape

#%% Parameters

n_sample = 10; # number of samples;
n_tstep = 3; # number of time steps per sample
n_row = 8; # number of rows per frame
n_col = 8; # number of columns per frame
n_channel = 1; # number of channel

RC_MATRIX = K.random_normal([108, 108]) # Reservior layer node recurrent connection matrix, note there are 108 nodes
C_DECAY = K.constant(0.9) # Recurrent layer node time-to-time decay coefficient

data = K.random_normal([n_sample, n_tstep, n_row, n_col, 1]) # Some random dataset
# data = np.random.randn(n_sample, n_tstep, n_row, n_col, 1)
label = np.random.randint(5, size=n_sample) # Some random dataset labels
label_onehot = K.one_hot(label, 5)

x_train = data
y_train = label_onehot

x_test = data
y_test = label_onehot

#%% Model

model=Sequential();

# Convolution Kernels: Input shape (batch_size, 3, 8, 8, 1), Output shape (batch_size, 3, 6, 6, 3)
model.add(TimeDistributed(Convolution2D(3, (3, 3), strides=1, padding='valid', use_bias=False,
                                        kernel_initializer='random_uniform', trainable=False), input_shape = (n_tstep, n_row, n_col, n_channel)))

# Flatten non-time dimensions: Input shape (batch_size, 3, 6, 6, 3), Output shape (batch_size, 3, 108)
model.add(Lambda(flatten_tstep, output_shape = flatten_tstep_shape))

# Reservior: Input shape (batch_size 3, 108), Output shape (batch_size, 108)
model.add(Lambda(ag_reservior, output_shape = ag_reservior_shape))

# Reservior Read-out: Input shape (batch_size, 108), Output shape (batch_size, 5)
model.add(Dense(5, use_bias=False))
model.add(Activation('softmax'))

# Check model
model.summary()

#%% Training
opt = keras.optimizers.rmsprop(lr = 0.01, decay = 1e-6)
model.compile(loss='categorical_crossentropy', optimizer = opt, metrics = ['acc'])
history = model.fit(x_train, y_train, epochs = 50, validation_data = (x_test, y_test), batch_size = 2)

However, Keras said "If your data is in the form of symbolic tensors, you should specify the steps_per_epoch argument (instead of the batch_size argument, because symbolic tensors are expected to produce batches of input data)."

Could you advise on how to let Keras correctly recognize the batch size and proceed to the training? (Note that the Conv2d layer is fixed, the lambda layers are also fixed, only the last dense layer needs training.)

Thank you in advance.


问:
EF Core - code first migration: Incorrect syntax near the keyword 'NOT'
I am following this tutorial.

Added Rating property and when run 'update-database' I got this error:

Tried to revert to previous migration but that says no migrations applied as DB up to date. Dropped DB table and rerun migration but still getting this. When I added another migration after, UP and DOWN methods are empty. Anyone has any idea? Thanks

答:
Well, you haven't shared any code, so based purely off what the tutorial says and the image you posted, it looks like instead of:

```<code>[Column(TypeName = "decimal(18, 2)")]
</code>```

You most likely have

```<code>[Column(TypeName = "decimal(18, 2")]
</code>```

since it's missing a bracket in the alter clause (i.e, you need a bracket after the 2 inside the string).

Body:
Well, you haven't shared any code, so based purely off what the tutorial says and the image you posted, it looks like instead of:

[Column(TypeName = "decimal(18, 2)")]

You most likely have

[Column(TypeName = "decimal(18, 2")]

since it's missing a bracket in the alter clause (i.e, you need a bracket after the 2 inside the string).


问:
How to save input values on server using puppeteer?
How to save input fields value on server ? i want to save form value after i submit the values disappears  when i reopen the form . </p>

```<code> await page.$$eval("input[data-bind='value: SyringeOut']",el=>{
            for(i=0; i<el.length; i++){
                el[i].value=3;
            }
        });
</code>```

答:
page.$$eval does the following,

Runs a querySelectorAll inside the page.

Creates an array from the result.

Maps over the array for you. So it returns a single element and runs your function through it.

Consider rewriting your example like below,

```<code>await page.$$eval("input[data-bind='value: SyringeOut']", element => element.value = 3)
</code>```

So you should not do a for loop inside the el => {} block. Since it's a single element.

Body:
How to save input fields value on server ? i want to save form value after i submit the values disappears  when i reopen the form .

 await page.$$eval("input[data-bind='value: SyringeOut']",el=>{
            for(i=0; i<el.length; i++){
                el[i].value=3;
            }
        });

Body:
page.$$eval does the following,

Runs a querySelectorAll inside the page.

Creates an array from the result.

Maps over the array for you. So it returns a single element and runs your function through it.

Consider rewriting your example like below,

await page.$$eval("input[data-bind='value: SyringeOut']", element => element.value = 3)

So you should not do a for loop inside the el => {} block. Since it's a single element.


问:
Programming joint legend in ggplot2 for multiple regressions with grouping variable
I have four regression plots which are not only based on a x and y variable but also grouped by a grouping variable z (v_187_corr). So, the legend contains all the groups which are stored in v_187. I now want to have all my 4 graphs in a 2x2 window and place one common legend with all the group names. </p>

<p>(I found some examples which were however still quite different to my example). </p>

```<code>par(mfrow = c(2, 2))

# First Plot: Passung auf Zufriedenheit
p1 <- ggplot(df.hlm_cc_select, aes(zPssg_sd, zZufri))

p1 + geom_jitter(aes(colour = v_187_corr))+
  labs(title="Zufriedenheit erklärt durch Direktheit",x="Direktheit", y = "Zufriedenheit") +
    scale_color_viridis(discrete = TRUE, option = "A")+
    scale_fill_viridis(discrete = TRUE) +
    theme_dark() +
    theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
         axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
    #geom_smooth(aes(x = zagree_group_withinmeet_levelrat, y = zZufri), inherit.aes = FALSE, se = FALSE)+
    geom_smooth(method=lm, color="black")

# Second Plot: Homogenität Problemart auf Zufriedenheit

p2 <- ggplot(df.hlm_cc_select, aes(zmean.aggr.prb_sd, zZufri))

p2 + geom_jitter(aes(colour = v_187_corr))+
  labs(title="Zufriedenheit erklärt durch Homogenität (Problemart)",x="Homogenität (Problemart)", y = "Zufriedenheit") +
    scale_color_viridis(discrete = TRUE, option = "A")+
    scale_fill_viridis(discrete = TRUE) +
    theme_dark() +
    theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
         axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
    #geom_smooth(aes(x = zagree_group_withinmeet_levelrat, y = zZufri), inherit.aes = FALSE, se = FALSE)+
    geom_smooth(method=lm, color="black")

# Third Plot: Homogenität Level auf Zufriedenheit
p3 <- ggplot(df.hlm_cc_select, aes(zagree_group_withinmeet_levelrat, zZufri))

p3 + geom_jitter(aes(colour = v_187_corr))+
  labs(title="Satisfaction explained by Homogeneity (Level)",x="Homogeneity (Level)", y = "Satisfaction") +
    scale_color_viridis(discrete = TRUE, option = "A")+
    scale_fill_viridis(discrete = TRUE) +
    theme_dark() +
    theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
         axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
    #geom_smooth(aes(x = zagree_group_withinmeet_levelrat, y = zZufri), inherit.aes = FALSE, se = FALSE)+
    geom_smooth(method=lm, color="black")

# Forth Plot: Intensität auf Zufriedenheit
p4 <- ggplot(df.hlm_cc_select, aes(zmeans_levelsums, zZufri))

p4 + geom_jitter(aes(colour = v_187_corr))+
  labs(title="Zufriedenheit erklärt durch Intensität",x="Intensität", y = "Zufriedenheit") +
    scale_color_viridis(discrete = TRUE, option = "A")+
    scale_fill_viridis(discrete = TRUE) +
    theme_dark() +
    theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
         axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
    #geom_smooth(aes(x = zagree_group_withinmeet_levelrat, y = zZufri), inherit.aes = FALSE, se = FALSE)+
    geom_smooth(method=lm, color="black")
</code>```

答:
Assuming your data looks something like the following:

```<code>df.hlm_cc_select <- data.frame(zZufri = runif(10,0,1),
                               zmeans_levelsums = runif(10,0,1),
                               zagree_group_withinmeet_levelrat = runif(10,0,1),
                               zmean.aggr.prb_sd = runif(10,0,1),
                               zPssg_sd = runif(10,0,1),
                               v_187_corr = runif(10,0,1))
</code>```

You can use the tidyr package (among other options such as reshape2::melt and data.table::melt) to gather all variables into one column (we will call this value).

In this process, you must exclude zZufri (your x axis?) and your colour variable v_187_corr using -zZufri, -v_187_corr. The key column indicates which variable is associated with each value.

```<code>df <- gather(df.hlm_cc_select,key="key",value="value",-zZufri, -v_187_corr)
</code>```

Then using ggplot you can just add facet_wrap(~key) which says create a facet plot one for each unique value in key

```<code>ggplot(df,aes(x=value,y=zZufri,col=v_187_corr))+
  geom_jitter()+
  scale_color_viridis(discrete = TRUE, option = "A")+
  scale_fill_viridis(discrete = TRUE) +
  theme_dark() +
  theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
        axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
  inherit.aes = FALSE, se = FALSE)+
  geom_smooth(method=lm, color="black")+
  facet_wrap(~key)
</code>```

There will only be one legend for all plots.

Body:
I have four regression plots which are not only based on a x and y variable but also grouped by a grouping variable z (v_187_corr). So, the legend contains all the groups which are stored in v_187. I now want to have all my 4 graphs in a 2x2 window and place one common legend with all the group names.

(I found some examples which were however still quite different to my example).

par(mfrow = c(2, 2))

# First Plot: Passung auf Zufriedenheit
p1 <- ggplot(df.hlm_cc_select, aes(zPssg_sd, zZufri))

p1 + geom_jitter(aes(colour = v_187_corr))+
  labs(title="Zufriedenheit erklärt durch Direktheit",x="Direktheit", y = "Zufriedenheit") +
    scale_color_viridis(discrete = TRUE, option = "A")+
    scale_fill_viridis(discrete = TRUE) +
    theme_dark() +
    theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
         axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
    #geom_smooth(aes(x = zagree_group_withinmeet_levelrat, y = zZufri), inherit.aes = FALSE, se = FALSE)+
    geom_smooth(method=lm, color="black")

# Second Plot: Homogenität Problemart auf Zufriedenheit

p2 <- ggplot(df.hlm_cc_select, aes(zmean.aggr.prb_sd, zZufri))

p2 + geom_jitter(aes(colour = v_187_corr))+
  labs(title="Zufriedenheit erklärt durch Homogenität (Problemart)",x="Homogenität (Problemart)", y = "Zufriedenheit") +
    scale_color_viridis(discrete = TRUE, option = "A")+
    scale_fill_viridis(discrete = TRUE) +
    theme_dark() +
    theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
         axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
    #geom_smooth(aes(x = zagree_group_withinmeet_levelrat, y = zZufri), inherit.aes = FALSE, se = FALSE)+
    geom_smooth(method=lm, color="black")

# Third Plot: Homogenität Level auf Zufriedenheit
p3 <- ggplot(df.hlm_cc_select, aes(zagree_group_withinmeet_levelrat, zZufri))

p3 + geom_jitter(aes(colour = v_187_corr))+
  labs(title="Satisfaction explained by Homogeneity (Level)",x="Homogeneity (Level)", y = "Satisfaction") +
    scale_color_viridis(discrete = TRUE, option = "A")+
    scale_fill_viridis(discrete = TRUE) +
    theme_dark() +
    theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
         axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
    #geom_smooth(aes(x = zagree_group_withinmeet_levelrat, y = zZufri), inherit.aes = FALSE, se = FALSE)+
    geom_smooth(method=lm, color="black")

# Forth Plot: Intensität auf Zufriedenheit
p4 <- ggplot(df.hlm_cc_select, aes(zmeans_levelsums, zZufri))

p4 + geom_jitter(aes(colour = v_187_corr))+
  labs(title="Zufriedenheit erklärt durch Intensität",x="Intensität", y = "Zufriedenheit") +
    scale_color_viridis(discrete = TRUE, option = "A")+
    scale_fill_viridis(discrete = TRUE) +
    theme_dark() +
    theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
         axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
    #geom_smooth(aes(x = zagree_group_withinmeet_levelrat, y = zZufri), inherit.aes = FALSE, se = FALSE)+
    geom_smooth(method=lm, color="black")

Body:
Assuming your data looks something like the following:

df.hlm_cc_select <- data.frame(zZufri = runif(10,0,1),
                               zmeans_levelsums = runif(10,0,1),
                               zagree_group_withinmeet_levelrat = runif(10,0,1),
                               zmean.aggr.prb_sd = runif(10,0,1),
                               zPssg_sd = runif(10,0,1),
                               v_187_corr = runif(10,0,1))

You can use the tidyr package (among other options such as reshape2::melt and data.table::melt) to gather all variables into one column (we will call this value).

In this process, you must exclude zZufri (your x axis?) and your colour variable v_187_corr using -zZufri, -v_187_corr. The key column indicates which variable is associated with each value.

df <- gather(df.hlm_cc_select,key="key",value="value",-zZufri, -v_187_corr)

Then using ggplot you can just add facet_wrap(~key) which says create a facet plot one for each unique value in key

ggplot(df,aes(x=value,y=zZufri,col=v_187_corr))+
  geom_jitter()+
  scale_color_viridis(discrete = TRUE, option = "A")+
  scale_fill_viridis(discrete = TRUE) +
  theme_dark() +
  theme(axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'),
        axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid')) +
  inherit.aes = FALSE, se = FALSE)+
  geom_smooth(method=lm, color="black")+
  facet_wrap(~key)

There will only be one legend for all plots.


问:
Eclipse plugin open document
I need to write an Eclipse plugin which uses the SOA BPMN modeler (http://www.eclipse.org/bpmn/) to model a diagram in Eclipse's main view (the central one).

My idea is: what if I create a hello.bpmn_diagram file and load it into eclipse? That would make my life easier when the user saves the file (it is already on disk)

Any other idea or suggestion is very appreciated

答: Alexey Kalmykov gave the right insight: the extension points (useless unfortunately), were in the MF file of the source code</p>

ContentLicense: CC BY-SA 2.5

Title: Eclipse plugin open document


问:
The application doesn't receive push notification after updating a new release with Firebase token. iOS / Swift
I have problem with Firebase FCM token.

In the previous version of the application, users registered, but without the implemented FCM token for Push notification. And now I implemented a new version with the FCM token and after the users updated the new release they did not get the Push notification.

So I run the old version of the application without implementing the PN on my phone and then I run again, but version of the application with the implemented PN and on the console I see the FCM token in didReceiveRegistrationToken method, but I can not send the PN. But if I run the application for the third time, I can get PN.

For the record if I run new version of the app with implemented PN, it works perfectly.

Does anyone have any advice or solution to this problem?

Maybe some advice in global, or if I have already installed the app and re run that app again with new updates for Push Notification?

Thanks in advance.

答:
I faced a similar problem recently with FCM.

Set Messaging.messaging().apnsToken = deviceToken after receiving deviceToken from APNS. Although not necessary if swizzling is enabled, it is better to include it to ensure token is updated reliably.


问:
How can I pass the current post taxonomy term using ajax?
I'm creating a filter for a wordpress custom post type.  I want to be able to dynamically display more posts using a dropdown.  This works fine.  The issue is that I'm only getting it to work if I hard code the taxonomy term.  I'd like to be able to pass the term dynamically with the number of posts per page that the use has selected.

I've already tried to pass it using a hidden input.  I was able to create the variable and add it to the name attribute but couldn't pull it out on the server side.  I also think that was a hacky way of doing it.

```<code>$args = array(
            'post_type' => 'products',
            'posts_per_page' => $_POST['ppp'],
            'tax_query' => array(
                array(
                    'taxonomy' => 'product-category',
                    'field'    => 'slug',
                    'terms'    => 'terminals'
                ),
            ),
        );
</code>```

```<code><form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
    <select name="ppp">
        <option value="1">Show 12 Per Page</option>
        <option value="2">Show 24 Per Page</option>
        <option value="3">Show 48 Per Page</option>
        <option value="-1">Show All</option>
    </select>
    <!-- <div id = "spinner"></div> -->
    <input type="hidden" name="action" value="myfilter">
</form>
</code>```

```<code>$('#filter').change(function() {
        var filter = $('#filter');
        $.ajax({
            url:filter.attr('action'),
            data:filter.serialize(),
            type:filter.attr('method'),
            beforeSend:function(xhr){
                //show the spinner
            },
            success:function(data){
                //hide the spinner
                $('#response').html(data);
            }
        });
        return false;
    });
</code>```

I'd like to be able to grab the taxonomy term from the current post and pass it to the function through ajax.

答:
I think your selector is a bit off. Please consider the following:

$(function() {
  $("#filter select").change(function() {
    $(this).parent().submit();
  });
  $("#filter").submit(function(e) {
    e.preventDefault();
    var $f = $(this);
    $.ajax({
      url: $f.attr("action"),
      data: {
        ppp: parseInt($("select", $f).val())
      },
      dataType: "html",
      method: "POST",
      beforeSend: function(xhr) {
        //show the spinner
      },
      success: function(data) {
        //hide the spinner
        $('#response').html(data);
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="./wp-admin/admin-ajax.php" method="POST" id="filter">
  <select name="ppp">
    <option value="1" selected>Show 12 Per Page</option>
    <option value="2">Show 24 Per Page</option>
    <option value="3">Show 48 Per Page</option>
    <option value="-1">Show All</option>
  </select>
  <!-- <div id = "spinner"></div> -->
  <input type="hidden" name="action" value="myfilter">
</form></code>```

When the User changes the select, the form is submitted. Form submission executes the AJAX.

Hope this helps.

Body:
I'm creating a filter for a wordpress custom post type.  I want to be able to dynamically display more posts using a dropdown.  This works fine.  The issue is that I'm only getting it to work if I hard code the taxonomy term.  I'd like to be able to pass the term dynamically with the number of posts per page that the use has selected.

I've already tried to pass it using a hidden input.  I was able to create the variable and add it to the name attribute but couldn't pull it out on the server side.  I also think that was a hacky way of doing it.

$args = array(
            'post_type' => 'products',
            'posts_per_page' => $_POST['ppp'],
            'tax_query' => array(
                array(
                    'taxonomy' => 'product-category',
                    'field'    => 'slug',
                    'terms'    => 'terminals'
                ),
            ),
        );

<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
    <select name="ppp">
        <option value="1">Show 12 Per Page</option>
        <option value="2">Show 24 Per Page</option>
        <option value="3">Show 48 Per Page</option>
        <option value="-1">Show All</option>
    </select>

    <input type="hidden" name="action" value="myfilter">
</form>

$('#filter').change(function() {
        var filter = $('#filter');
        $.ajax({
            url:filter.attr('action'),
            data:filter.serialize(),
            type:filter.attr('method'),
            beforeSend:function(xhr){
                //show the spinner
            },
            success:function(data){
                //hide the spinner
                $('#response').html(data);
            }
        });
        return false;
    });

I'd like to be able to grab the taxonomy term from the current post and pass it to the function through ajax.

Body:
I think your selector is a bit off. Please consider the following:

$(function() {
  $("#filter select").change(function() {
    $(this).parent().submit();
  });
  $("#filter").submit(function(e) {
    e.preventDefault();
    var $f = $(this);
    $.ajax({
      url: $f.attr("action"),
      data: {
        ppp: parseInt($("select", $f).val())
      },
      dataType: "html",
      method: "POST",
      beforeSend: function(xhr) {
        //show the spinner
      },
      success: function(data) {
        //hide the spinner
        $('#response').html(data);
      }
    });
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="./wp-admin/admin-ajax.php" method="POST" id="filter">
  <select name="ppp">
    <option value="1" selected>Show 12 Per Page</option>
    <option value="2">Show 24 Per Page</option>
    <option value="3">Show 48 Per Page</option>
    <option value="-1">Show All</option>
  </select>
  <!-- <div id = "spinner"></div> -->
  <input type="hidden" name="action" value="myfilter">
</form>

When the User changes the select, the form is submitted. Form submission executes the AJAX.

Hope this helps.


问:
Saving HABTM records when not all join table columns are foreign keys
I am trying to update tables with a has and belongs to many (HABTM) relationship.

When my join table looked like this:

```<code>CREATE TABLE IF NOT EXISTS `items_labels` (
  `item_id` int(11) NOT NULL,
  `label_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code>```

I use CakePHP, so I could update the tables with $this->Item->save($data) where $data was:

```<code>Array
(
    [Item] => Array
        (
            [id] => 1
        )
    [Label] => Array
        (
            [Label] => Array
                (
                    [0] => 4
                    [1] => 5
                    [2] => 7
                    [3] => 8
                )
        )
)
</code>```

I've added a column to my join table, so it now looks like:

```<code>CREATE TABLE IF NOT EXISTS `items_labels` (
  `item_id` int(11) NOT NULL,
  `label_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code>```

When I am saving $data, I also want to save a user id. The user id will be the same for all records in a single save operation.

Can someone help me understand what the $data array needs to look like in order to incorporate the user id? Thanks.

答:
This should work:

```<code>Array
(
    [Item] => Array
        (
            [id] => 1
        )

    [Label] => Array
        (
            [Label] => Array
                (
                    [0] => Array
                        (
                            [label_id] => 4
                            [user_id] => 1
                        )

                    [1] => Array
                        (
                            [label_id] => 5
                            [user_id] => 1
                        )

                    [2] => Array
                        (
                            [label_id] => 7
                            [user_id] => 1
                        )

                    [3] => Array
                        (
                            [label_id] => 8
                            [user_id] => 1
                        )

                )

        )

)
</code>```

It will generate multiple INSERTs, but will work with one save call.

OwnerDisplayName: RyOnLife

Body:
I am trying to update tables with a has and belongs to many (HABTM) relationship.

When my join table looked like this:

CREATE TABLE IF NOT EXISTS `items_labels` (
  `item_id` int(11) NOT NULL,
  `label_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

I use CakePHP, so I could update the tables with $this->Item->save($data) where $data was:

Array
(
    [Item] => Array
        (
            [id] => 1
        )
    [Label] => Array
        (
            [Label] => Array
                (
                    [0] => 4
                    [1] => 5
                    [2] => 7
                    [3] => 8
                )
        )
)

I've added a column to my join table, so it now looks like:

CREATE TABLE IF NOT EXISTS `items_labels` (
  `item_id` int(11) NOT NULL,
  `label_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

When I am saving $data, I also want to save a user id. The user id will be the same for all records in a single save operation.

Can someone help me understand what the $data array needs to look like in order to incorporate the user id? Thanks.

LastEditorDisplayName: RyOnLife

Body:
This should work:

Array
(
    [Item] => Array
        (
            [id] => 1
        )

    [Label] => Array
        (
            [Label] => Array
                (
                    [0] => Array
                        (
                            [label_id] => 4
                            [user_id] => 1
                        )

                    [1] => Array
                        (
                            [label_id] => 5
                            [user_id] => 1
                        )

                    [2] => Array
                        (
                            [label_id] => 7
                            [user_id] => 1
                        )

                    [3] => Array
                        (
                            [label_id] => 8
                            [user_id] => 1
                        )

                )

        )

)

It will generate multiple INSERTs, but will work with one save call.

OwnerDisplayName: Matt Curry


问:
Getting started with SSL
After reading articles about SSL online (a while ago, sources forgotten) - I've come to the conclusion that half of SSL related articles are full of . While the other half seem to suggest that SSL is a must if you're selling stuff on your site.

My question is, after trying to find this out on Google, is How do you actually use SSL, like how do you put it on your site?

I'm not sure why, but I was always under the impression that to make SSL work with your website you just pay for an SSL Certificate and just enter your website's details on your SSL providers site and it just get sets up somehow by the SSL service?

Is there any programming involved?

答:
Find a hosting provider, that provides root access.

Install openSSL

Install web server

Follow instructions to generate certificate signing request PKCS#12 (from memory) for web server

Have request signed by verisign or other trusted authority. $$$

Install signed cert into web server

Good to go. Instructions are from memory, 3am in the morning. Mostly right, but no programming required. Detailed instructions should be available from your hosting provider. Follow them.

You could skip step 5 and install your own Certificate Authority, but then your users will get alert messages when they try and establish a secure connection with your site. Bad UX if you actually want to sell something or establish secure connection with standard browsers.

Title: Getting started with SSL


问:
Fread reads double from a file
I am new to C programming and I am trying to compare blocks of 1024 bytes (I'm testing with 10 for now) from 2 txt files, and check how many of those blocks are identical.

I am reading blocks with fread and comparing them with strcmp, but fread reads double from the first file, even if I read in the same way from both. So this is my compare function:

```<code>void compareFiles(FILE *fp1, FILE *fp2)
{
char fp1_content[10]; //should be 1024
char fp2_content[10]; //should be 1024

fread(fp1_content, 10, 1, fp1); //should be 1024
fread(fp2_content, 10, 1, fp2); //should be 1024

printf("content of 81.txt %s \n", fp1_content);
printf("content of 82.txt %s \n", fp2_content);

char ch1 = getc(fp1);
char ch2 = getc(fp2);
int eqBlocks = 0;

while (ch1 != EOF && ch2 != EOF)
{
    if (strcmp(fp1_content, fp2_content) == 0) {
        eqBlocks++;
    }

    ch1 = getc(fp1);
    ch2 = getc(fp2);

    fread(fp1_content, 10, 1, fp1);
    fread(fp2_content, 10, 1, fp2);
}
printf("Nb of identical blocks: %d\n", eqBlocks);
}
</code>```

Here comes the issue: I have lorem ipsum text, same text in both files. But the first two printfs are outputing:

```<code>content of 81.txt Lorem ipsuLorem ipsu
content of 82.txt Lorem ipsu
</code>```

Why is the first one doubled? How am I fixing this?

答:
OP's code needs a few fixes.

Return value

Functions like fread() return useful info.  Use them.  It this case, it tells how much was read. @Weather Vane

"%s" expectes a string pointer

printf("content of 81.txt %s \n", fp1_content); expects fp1_content is a string.  In C, a string always has a null character, else, it is not a string.  To print text that may not have a '\0', use "%.*s", which accepts an argument to limit print length.  "%s" with a non-string is undefined behavior.  Unexpected things may happen. @Tom Karzes

Compare non-strings with memcmp()

Unnecessary code

char ch1 = getc(fp1); is not need to detect the end, use the fread() return value.  @Jean-François Fabre Aside: use int ch1 to distinguish the 257 different return values from fgets().

Avoid naked magic numbers

Rather than litter code with 10 here and there, use a named constant.

Think big

Files can be larger than INT_MAX blocks.  Suggest long long eqBlocks.

```<code>#include <limits.h>
#define COMPAREFILES_N 10
#if COMPAREFILES_N > INT_MAX
#error Use smaller block
#endif

void compareFiles(FILE *fp1, FILE *fp2) {
  char fp1_content[COMPAREFILES_N];
  char fp2_content[COMPAREFILES_N];
  long long eqBlocks = 0;

  for (;;) {
    size_t len1 = fread(fp1_content, COMPAREFILES_N, 1, fp1);
    size_t len2 = fread(fp2_content, COMPAREFILES_N, 1, fp2);
    if (len1 < 1 || len2 < 1) {
      break;  // failed to read a block in each file
    }
    if (memcmp(fp1_content, fp2_content, COMPAREFILES_N) == 0) {
      eqBlocks++;
      printf("Common content `%.*s`\n", COMPAREFILES_N, fp1_content);
    }
  }

  printf("Nb of identical blocks: %lld\n", eqBlocks);
}
</code>```

Title: Fread reads double from a file

Body:
I am new to C programming and I am trying to compare blocks of 1024 bytes (I'm testing with 10 for now) from 2 txt files, and check how many of those blocks are identical.

I am reading blocks with fread and comparing them with strcmp, but fread reads double from the first file, even if I read in the same way from both. So this is my compare function:

void compareFiles(FILE *fp1, FILE *fp2)
{
char fp1_content[10]; //should be 1024
char fp2_content[10]; //should be 1024

fread(fp1_content, 10, 1, fp1); //should be 1024
fread(fp2_content, 10, 1, fp2); //should be 1024

printf("content of 81.txt %s \n", fp1_content);
printf("content of 82.txt %s \n", fp2_content);

char ch1 = getc(fp1);
char ch2 = getc(fp2);
int eqBlocks = 0;

while (ch1 != EOF && ch2 != EOF)
{
    if (strcmp(fp1_content, fp2_content) == 0) {
        eqBlocks++;
    }

    ch1 = getc(fp1);
    ch2 = getc(fp2);

    fread(fp1_content, 10, 1, fp1);
    fread(fp2_content, 10, 1, fp2);
}
printf("Nb of identical blocks: %d\n", eqBlocks);
}

Here comes the issue: I have lorem ipsum text, same text in both files. But the first two printfs are outputing:

content of 81.txt Lorem ipsuLorem ipsu
content of 82.txt Lorem ipsu

Why is the first one doubled? How am I fixing this?

Body:
OP's code needs a few fixes.

Return value

Functions like fread() return useful info.  Use them.  It this case, it tells how much was read. @Weather Vane

"%s" expectes a string pointer

printf("content of 81.txt %s \n", fp1_content); expects fp1_content is a string.  In C, a string always has a null character, else, it is not a string.  To print text that may not have a '\0', use "%.*s", which accepts an argument to limit print length.  "%s" with a non-string is undefined behavior.  Unexpected things may happen. @Tom Karzes

Compare non-strings with memcmp()

Unnecessary code

char ch1 = getc(fp1); is not need to detect the end, use the fread() return value.  @Jean-François Fabre Aside: use int ch1 to distinguish the 257 different return values from fgets().

Avoid naked magic numbers

Rather than litter code with 10 here and there, use a named constant.

Think big

Files can be larger than INT_MAX blocks.  Suggest long long eqBlocks.

#include <limits.h>
#define COMPAREFILES_N 10
#if COMPAREFILES_N > INT_MAX
#error Use smaller block
#endif

void compareFiles(FILE *fp1, FILE *fp2) {
  char fp1_content[COMPAREFILES_N];
  char fp2_content[COMPAREFILES_N];
  long long eqBlocks = 0;

  for (;;) {
    size_t len1 = fread(fp1_content, COMPAREFILES_N, 1, fp1);
    size_t len2 = fread(fp2_content, COMPAREFILES_N, 1, fp2);
    if (len1 < 1 || len2 < 1) {
      break;  // failed to read a block in each file
    }
    if (memcmp(fp1_content, fp2_content, COMPAREFILES_N) == 0) {
      eqBlocks++;
      printf("Common content `%.*s`\n", COMPAREFILES_N, fp1_content);
    }
  }

  printf("Nb of identical blocks: %lld\n", eqBlocks);
}


问:
How to remove Failed to create chart: can't acquire context from the given item error while using it with Ruby on Rails?
I installed frappe charts for ruby on rails through gem.

Then I tried to run one of the frappe-chart code which is given in their website:

 let data = {
    labels: ["12am-3am", "3am-6am", "6am-9am", "9am-12pm",
      "12pm-3pm", "3pm-6pm", "6pm-9pm", "9pm-12am"],

    datasets: [
      {
        title: "Some Data",
        values: [25, 40, 30, 35, 8, 52, 17, -4]
      },
      {
        title: "Another Set",
        values: [25, 50, -10, 15, 18, 32, 27, 14]
      },
      {
        title: "Yet Another",
        values: [15, 20, -3, -15, 58, 12, -17, 37]
      }
    ]
  };

  let chart = new Chart({
    parent: "#note-graph", // or a DOM element
    title: "My Awesome Chart",
    data: data,
    type: 'bar', // or 'line', 'scatter', 'pie', 'percentage'
    height: 250,

    colors: ['#7cd6fd', 'violet', 'blue'],
    // hex-codes or these preset colors;
    // defaults (in order):
    // ['light-blue', 'blue', 'violet', 'red',
    // 'orange', 'yellow', 'green', 'light-green',
    // 'purple', 'magenta', 'grey', 'dark-grey']

    format_tooltip_x: d => (d + '').toUpperCase(),
    format_tooltip_y: d => d + ' pts'
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="note-graph"></canvas></code>```

I also tried with div instead of canvas but it's always showing the same error.

答:
Im using laravel + vuejs.

this solved my problem with "Error: No parent element to render on was provided." with frapped

with the sample data that the npm provided,

in de data just declare the data varible like this:

<template>

CHARTS

</template>

```

Body:
I installed frappe charts for ruby on rails through gem.

Then I tried to run one of the frappe-chart code which is given in their website:

 let data = {
    labels: ["12am-3am", "3am-6am", "6am-9am", "9am-12pm",
      "12pm-3pm", "3pm-6pm", "6pm-9pm", "9pm-12am"],

    datasets: [
      {
        title: "Some Data",
        values: [25, 40, 30, 35, 8, 52, 17, -4]
      },
      {
        title: "Another Set",
        values: [25, 50, -10, 15, 18, 32, 27, 14]
      },
      {
        title: "Yet Another",
        values: [15, 20, -3, -15, 58, 12, -17, 37]
      }
    ]
  };

  let chart = new Chart({
    parent: "#note-graph", // or a DOM element
    title: "My Awesome Chart",
    data: data,
    type: 'bar', // or 'line', 'scatter', 'pie', 'percentage'
    height: 250,

    colors: ['#7cd6fd', 'violet', 'blue'],
    // hex-codes or these preset colors;
    // defaults (in order):
    // ['light-blue', 'blue', 'violet', 'red',
    // 'orange', 'yellow', 'green', 'light-green',
    // 'purple', 'magenta', 'grey', 'dark-grey']

    format_tooltip_x: d => (d + '').toUpperCase(),
    format_tooltip_y: d => d + ' pts'
  });

<canvas id="note-graph"></canvas>

I also tried with div instead of canvas but it's always showing the same error.

Body:
Im using laravel + vuejs.

this solved my problem with "Error: No parent element to render on was provided." with frapped

with the sample data that the npm provided,

in de data just declare the data varible like this:

<template>
    <div>
        <h1>CHARTS</h1>
            <div id="chart"></div>
    </div>
</template>

<script>
import { Chart } from 'frappe-charts/dist/frappe-charts.esm.js'
// import css
import 'frappe-charts/dist/frappe-charts.min.css'

export default{
data(){
    return{
         data : {
    labels: ["12am-3am", "3am-6pm", "6am-9am", "9am-12am",
        "12pm-3pm", "3pm-6pm", "6pm-9pm", "9am-12am"
    ],
    datasets: [
        {
            name: "Some Data", type: "bar",
            values: [25, 40, 30, 35, 8, 52, 17, -4]
        },
        {
            name: "Another Set", type: "line",
            values: [25, 50, -10, 15, 18, 32, 27, 14]
        }
    ]
},

chart : null // THIS IS WHAT YOU NEED TO SET NULL
    }
},
methods:{
    setChart(){ // IN METHOD YOU SET A NEW CHART
     this.chart=new Chart("#chart", {
    title: "My Awesome Chart",
    data: this.data,
    type: 'axis-mixed',
    height: 250,
    colors: ['#7cd6fd', '#743ee2']
})
    }
},
mounted(){
    this.setChart(); // CALL THE METHOD IN A lifecycle hook
}
}

</script>


问:
Recursive menu in laravel
I am building a recursive menu in the following way:

```<code>public static function tree()
{
    return static::with(implode('.', array_fill(0, 100, 'children')))->where('parent_id', '=', '0')
        ->join('company_components', 'id', '=', 'company_components.component_id')
        ->where('company_components.company_id', '=', auth('api')->user()->with('company')->first()->company_id)
        ->orderBy('id')
        ->get();
}
</code>```

I get something like this:

```<code>[
  {
    "id":1,
    "parent_id":0,
    "name":"Cuentas",
    "url":"",
    "icon":"fa fa-user",
    "deleted_at":null,
    "created_at":"2019-05-26 18:57:02",
    "updated_at":"2019-05-26 18:57:02",
    "company_id":1,
    "component_id":1,
    "children":[
        {
          "id":2,
          "parent_id":1,
          "name":"Crear Cuenta",
          "url":"/account/create",
          "icon":"fa fa-circle-o",
          "deleted_at":null,
          "created_at":null,
          "updated_at":null,
          "children":[]
        }
     ]
  }
]
</code>```

How can I avoid the empty array of the last elements (which no longer have children)?

Is there any way that the element is not created if "children" if it does not have more children?

答:
```<code>    $this->cleanMenu($menu);

    public function cleanMenu($tree)
    {
        foreach($tree as $t) {
            if (!$t->children->count() > 0) {
                unset($t['children']);
            } else {
                $this->cleanMenu($t->children);
            }
        }
    }
</code>```

If there is a solution solving from the model without the need to iterate again, it would be phenomenal!

I hope help

Title: Recursive menu in laravel

Body:
I am building a recursive menu in the following way:

public static function tree()
{
    return static::with(implode('.', array_fill(0, 100, 'children')))->where('parent_id', '=', '0')
        ->join('company_components', 'id', '=', 'company_components.component_id')
        ->where('company_components.company_id', '=', auth('api')->user()->with('company')->first()->company_id)
        ->orderBy('id')
        ->get();
}

I get something like this:

[
  {
    "id":1,
    "parent_id":0,
    "name":"Cuentas",
    "url":"",
    "icon":"fa fa-user",
    "deleted_at":null,
    "created_at":"2019-05-26 18:57:02",
    "updated_at":"2019-05-26 18:57:02",
    "company_id":1,
    "component_id":1,
    "children":[
        {
          "id":2,
          "parent_id":1,
          "name":"Crear Cuenta",
          "url":"/account/create",
          "icon":"fa fa-circle-o",
          "deleted_at":null,
          "created_at":null,
          "updated_at":null,
          "children":[]
        }
     ]
  }
]

How can I avoid the empty array of the last elements (which no longer have children)?

Is there any way that the element is not created if "children" if it does not have more children?

Body:
    $this->cleanMenu($menu);

    public function cleanMenu($tree)
    {
        foreach($tree as $t) {
            if (!$t->children->count() > 0) {
                unset($t['children']);
            } else {
                $this->cleanMenu($t->children);
            }
        }
    }

If there is a solution solving from the model without the need to iterate again, it would be phenomenal!

I hope help


问:
Minimum difference based on group-index on two data frame
I have two data frame

```<code>A
            X1     Year_month
1          19.3945   1999_1
2          19.379    1999_1
3          19.2073   1999_1
4          19.267    2000_1
5          18.760    2000_1
6          19.3505   2000_1
</code>```

and B

```<code> Longitude   Year_month      CHL
1   12.3125     1999_1    12.70245
2    12.375     1999_1    12.63853
3   12.4375     1999_1    12.58700
4      12.5     2000_1    12.61019
5   12.5625     2000_1    12.75727
6    12.625     2000_1    13.06914
</code>```

I would like to calculate the minimum difference between each value of A$X1 and all values of B$Longitude, based on group-index Year_month, and report in a new column of A the value of B$CHL

Let's say when A$X1, minus each value of B$longitude, values for values, for the same Year_month group is the minimum difference, I put in a column A$res the values of B$CHL
Example, for the first row of df A:

```<code>A[1,1]-B[1,1]
A[1,1]-B[2,1]
A[1,1]-B[3,1] ---> this is the minimum difference
</code>```

in the column A$res I put the result 12.58 (value of B[3,3]), and so on for each row of A$X1

```<code>I tried this code:
A$res<- as.data.frame(lapply(A, function(x){
  if(as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))){
    return(B$CHL[unlist(lapply(as.numeric(as.character(B$Longitude)), function(t) which.min(abs(A$X1-t))))])
  } else{
    return(NA)
  }
}))
</code>```

But I have the error:

```<code>Error in if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  missing values where is required TRUE/FALSE
Furthermore Warning messages:
1: In FUN(X[[i]], ...) :  NA for coercion
2: In FUN(X[[i]], ...) : NA for coercion
3: In if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  the condition of length > 1 only the first element is used
</code>```

Any idea???

P.S:

```<code>sapply(A,class)
        X1 Year_month
  "factor"   "factor"

sapply(B,class)
 Longitude Year_month        CHL
  "factor"   "factor"  "numeric"
</code>```

答:
I use the varhandle package to easily convert factor to real.

Here the code:

```<code>library(varhandle)

# The data
A <- data.frame("X1"=c("19.3945","19.379", "19.2073", "19.267", "18.760", "19.3505"),
                "Year_month" = c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1"))
sapply(A, class)
#        X1 Year_month
#  "factor"   "factor"

B <- data.frame( "Longitude"=c("12.3125", "12.375", "12.4375","12.5", "12.5625", "12.625"  ),
                 "Year_month"=c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1"),
                 "CHL"=c( 12.70245, 12.63853, 12.58700, 12.61019, 12.75727, 13.06914))
sapply(B, class)
#  Longitude Year_month        CHL
#   "factor"   "factor"  "numeric"

# Convert factor to real
A$X1 = unfactor(A$X1)
B$Longitude = unfactor(B$Longitude)

# Function to apply
getCHL <- function(row){
  # Select matching row on "Year_month"
  sub_df <- B[B$Year_month == row["Year_month"], ]
  # Select indice
  ind <- which.min(as.double(row["X1"]) - sub_df$Longitude)
  return( sub_df$CHL[ind] )
}
# Apply the function
A["CHL"] <- apply(A, MARGIN = 1, getCHL)
</code>```

Body:
I have two data frame

A
            X1     Year_month
1          19.3945   1999_1
2          19.379    1999_1
3          19.2073   1999_1
4          19.267    2000_1
5          18.760    2000_1
6          19.3505   2000_1

and B

 Longitude   Year_month      CHL
1   12.3125     1999_1    12.70245
2    12.375     1999_1    12.63853
3   12.4375     1999_1    12.58700
4      12.5     2000_1    12.61019
5   12.5625     2000_1    12.75727
6    12.625     2000_1    13.06914

I would like to calculate the minimum difference between each value of A$X1 and all values of B$Longitude, based on group-index Year_month, and report in a new column of A the value of B$CHL

Let's say when A$X1, minus each value of B$longitude, values for values, for the same Year_month group is the minimum difference, I put in a column A$res the values of B$CHL
Example, for the first row of df A:

A[1,1]-B[1,1]
A[1,1]-B[2,1]
A[1,1]-B[3,1] ---> this is the minimum difference

in the column A$res I put the result 12.58 (value of B[3,3]), and so on for each row of A$X1

I tried this code:
A$res<- as.data.frame(lapply(A, function(x){
  if(as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))){
    return(B$CHL[unlist(lapply(as.numeric(as.character(B$Longitude)), function(t) which.min(abs(A$X1-t))))])
  } else{
    return(NA)
  }
}))

But I have the error:

Error in if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  missing values where is required TRUE/FALSE
Furthermore Warning messages:
1: In FUN(X[[i]], ...) :  NA for coercion
2: In FUN(X[[i]], ...) : NA for coercion
3: In if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  the condition of length > 1 only the first element is used

Any idea???

P.S:

sapply(A,class)
        X1 Year_month
  "factor"   "factor"

sapply(B,class)
 Longitude Year_month        CHL
  "factor"   "factor"  "numeric"

Body:
I use the varhandle package to easily convert factor to real.

Here the code:

library(varhandle)

# The data
A <- data.frame("X1"=c("19.3945","19.379", "19.2073", "19.267", "18.760", "19.3505"),
                "Year_month" = c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1"))
sapply(A, class)
#        X1 Year_month
#  "factor"   "factor"

B <- data.frame( "Longitude"=c("12.3125", "12.375", "12.4375","12.5", "12.5625", "12.625"  ),
                 "Year_month"=c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1"),
                 "CHL"=c( 12.70245, 12.63853, 12.58700, 12.61019, 12.75727, 13.06914))
sapply(B, class)
#  Longitude Year_month        CHL
#   "factor"   "factor"  "numeric"

# Convert factor to real
A$X1 = unfactor(A$X1)
B$Longitude = unfactor(B$Longitude)

# Function to apply
getCHL <- function(row){
  # Select matching row on "Year_month"
  sub_df <- B[B$Year_month == row["Year_month"], ]
  # Select indice
  ind <- which.min(as.double(row["X1"]) - sub_df$Longitude)
  return( sub_df$CHL[ind] )
}
# Apply the function
A["CHL"] <- apply(A, MARGIN = 1, getCHL)


问:
Calculated field Sub total in pivot table is not displaying correct value
I am working on QuickSight in AWS. I am trying to achieve weighted average value in a Pivot table.

I am using SPICE data to create this analysis.

I have created a calculate field (WAM) in analysis with formula "percentOfTotal(sum(upb),[{pool_num}]) * sum({remaining_terms})".

This gives me the desired value on each row level, but the sub total of a particular column is not reflecting the total of values in the calculate field, rather it displays the sum of original values in the "remaining_terms" field.

Please see below image for the same. Can some one please through some light on this ?

Thanks in advance for your help

Please note that I have tried the same in Excel pivot table and it works perfectly.

答:
Try to remove the 2nd argument from the percentOfTotal function.  For example, just do:

percentOfTotal(sum(upb))

I am not 100% this will work but one thought it that it would match the remaining_terms value if the percentageOfTotal was 1 (i.e. 100%) and you may not need to provide a partition argument in a pivot table since pivot tables implicitly provide partitions.


问:
Angular Nginx Docker 404
Been driving myself nuts trying to figure this out.

I have a very simple Angular project with routing, below is the app.module.ts, nginx.conf and docker file.

I start up by container

```<code>docker run --rm -d -p 80:80/tcp demo:latest
</code>```

browse to http://localhost and site works all routes render

If I am on http://localhost/contact and refresh page or type Url in directly I get 404 from Nginx.

The nginx.conf has try_files $uri /index.html; this is what all the posts with similar issues have said needs to be set.

Any idea what I am doing wrong.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ContactComponent } from './contact/contact.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'about', component: AboutComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
```

<p>nginx.conf</p>

```server {
    listen   80;

    root /usr/share/nginx/html;
    index index.html;

    server_name _;

    location / {
        try_files $uri /index.html;
    }
}
```

<p>dockerfile</p>

```FROM nginx

COPY nginx.conf /etc/nginx/conf.d/

RUN rm -rf /usr/share/nginx/html/*

COPY ./dist /usr/share/nginx/html
```

答:
Silly me, I was not overwriting the default docker conf in the docker file</p>

```<code>COPY nginx.conf /etc/nginx/conf.d/default.conf
</code>```

Title: Angular Nginx Docker 404

Body:
Been driving myself nuts trying to figure this out.

I have a very simple Angular project with routing, below is the app.module.ts, nginx.conf and docker file.

I start up by container

docker run --rm -d -p 80:80/tcp demo:latest

browse to http://localhost and site works all routes render

If I am on http://localhost/contact and refresh page or type Url in directly I get 404 from Nginx.

The nginx.conf has try_files $uri /index.html; this is what all the posts with similar issues have said needs to be set.

Any idea what I am doing wrong.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ContactComponent } from './contact/contact.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'about', component: AboutComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

nginx.conf

server {
    listen   80;

    root /usr/share/nginx/html;
    index index.html;

    server_name _;

    location / {
        try_files $uri /index.html;
    }
}

dockerfile

FROM nginx

COPY nginx.conf /etc/nginx/conf.d/

RUN rm -rf /usr/share/nginx/html/*

COPY ./dist /usr/share/nginx/html

Body:
Silly me, I was not overwriting the default docker conf in the docker file

COPY nginx.conf /etc/nginx/conf.d/default.conf