问:
Adding empty rows to Angular Material table when rows are less than a set number?
I have two angular tables and I am comparing their data side by side, let's say I have default 10 rows to show up on both tables, It can be the case that either if the two tables has less than 10 rows. E.g One table has 10 rows and second has just 1, so the second table end at just 1 row, what I would like to do is to have some empty rows(Number of rows that should be present - number of rows actually present). How can I do that ?

My First table

test-table.component.html

    <ng-container matColumnDef="id">
      Id
      {{row.id}}
    </ng-container>

    <ng-container matColumnDef="name">
      Name
      {{row.name}}
    </ng-container>

  <mat-paginator #paginator
      [length]="dataSource?.data.length"
      [pageIndex]="0"
      [pageSize]="50"
      [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>

```

<p>Data source file for this</p>

<p><code>test-table-datasource.ts</code></p>

<pre class="lang-js prettyprint-override"><code>import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';

// TODO: Replace this with your own data model type
export interface TestTableItem {
  name: string;
  id: number;
}

// TODO: replace this with real data from your application
const EXAMPLE_DATA: TestTableItem[] = [
  {id: 1, name: 'Hydrogen'},
  {id: 2, name: 'Helium'},
  {id: 3, name: 'Lithium'},
  {id: 4, name: 'Beryllium'},
  {id: 5, name: 'Boron'},
  {id: 6, name: 'Carbon'},
  {id: 7, name: 'Nitrogen'},
  {id: 8, name: 'Oxygen'},
  {id: 9, name: 'Fluorine'},
  {id: 10, name: 'Neon'},
  {id: 11, name: 'Sodium'},
  {id: 12, name: 'Magnesium'},
  {id: 13, name: 'Aluminum'},
  {id: 14, name: 'Silicon'},
  {id: 15, name: 'Phosphorus'},
  {id: 16, name: 'Sulfur'},
  {id: 17, name: 'Chlorine'},
  {id: 18, name: 'Argon'},
  {id: 19, name: 'Potassium'},
  {id: 20, name: 'Calcium'},
];

/**
 * Data source for the TestTable view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class TestTableDataSource extends DataSource<TestTableItem> {
  data: TestTableItem[] = EXAMPLE_DATA;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<TestTableItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect() {}

  /**
   * Paginate the data (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getPagedData(data: TestTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the data (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getSortedData(data: TestTableItem[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
</code>```

test-table.component.ts

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { TestTableDataSource, TestTableItem } from './test-table-datasource';

@Component({
  selector: 'app-test-table',
  templateUrl: './test-table.component.html',
  styleUrls: ['./test-table.component.css']
})
export class TestTableComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<TestTableItem>;
  dataSource: TestTableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  ngOnInit() {
    this.dataSource = new TestTableDataSource();
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }
}
```

<p>My Second Table
<code>sample-table.component.html</code></p>

<pre class="lang-js prettyprint-override"><code><div class="mat-elevation-z8">
  <table mat-table class="full-width-table" matSort aria-label="Elements">
    <!-- Id Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
      <td mat-cell *matCellDef="let row">{{row.id}}</td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
      <td mat-cell *matCellDef="let row">{{row.name}}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

  <mat-paginator #paginator
      [length]="dataSource?.data.length"
      [pageIndex]="0"
      [pageSize]="50"
      [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>
</div>
</code>```

sample-table-datasource.ts

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';

// TODO: Replace this with your own data model type
export interface SampleTableItem {
  name: string;
  id: number;
}

// TODO: replace this with real data from your application
const EXAMPLE_DATA: SampleTableItem[] = [
  {id: 1, name: 'Hydrogen'},
  {id: 2, name: 'Helium'},
  {id: 3, name: 'Lithium'},
  {id: 4, name: 'Beryllium'},
  {id: 5, name: 'Boron'},
  {id: 6, name: 'Carbon'},
  {id: 7, name: 'Nitrogen'},
  {id: 8, name: 'Oxygen'},
  {id: 9, name: 'Fluorine'},
  {id: 10, name: 'Neon'},
  {id: 11, name: 'Sodium'},
  {id: 12, name: 'Magnesium'},
  {id: 13, name: 'Aluminum'},
  {id: 14, name: 'Silicon'},
  {id: 15, name: 'Phosphorus'},
  {id: 16, name: 'Sulfur'},
  {id: 17, name: 'Chlorine'},
  {id: 18, name: 'Argon'},
  {id: 19, name: 'Potassium'},
  {id: 20, name: 'Calcium'},
];

/**
 * Data source for the SampleTable view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class SampleTableDataSource extends DataSource<SampleTableItem> {
  data: SampleTableItem[] = EXAMPLE_DATA;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<SampleTableItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect() {}

  /**
   * Paginate the data (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getPagedData(data: SampleTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the data (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getSortedData(data: SampleTableItem[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
```

<p><code>sample-table.component.ts</code></p>

<pre class="lang-js prettyprint-override"><code>import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { SampleTableDataSource, SampleTableItem } from './sample-table-datasource';

@Component({
  selector: 'app-sample-table',
  templateUrl: './sample-table.component.html',
  styleUrls: ['./sample-table.component.css']
})
export class SampleTableComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<SampleTableItem>;
  dataSource: SampleTableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  ngOnInit() {
    this.dataSource = new SampleTableDataSource();
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }
}
</code>```

app-compoenent.html

Table 1

<app-test-table></app-test-table>

Table 2

<app-sample-table></app-sample-table>

```

How do I add empty rows dynamically ?

答:
If you were to use <mat-table> instead of
, we could denote the data source like <mat-table [dataSource]="dataSource"> and insert empty objects to it. Try the following

Controller

this.dataSource = new MatTableDataSource<any>(this.inputData);
const length = 10 - this.dataSource._data._value.length;
for (let i = 0; i < length; i++) {
  this.dataSource._data._value.push(Object.create(null));
}
```

<p>Template</p>

```

  <mat-table [dataSource]="dataSource" class="full-width-table" matSort aria-label="Elements">
    ...

  </mat-table>
  ...

```

I've used constant 10 to show the behavior. To synchronize actual lengths between two components, you could setup a singleton service that allows data passage b/n the child components.

Body:
I have two angular tables and I am comparing their data side by side, let's say I have default 10 rows to show up on both tables, It can be the case that either if the two tables has less than 10 rows. E.g One table has 10 rows and second has just 1, so the second table end at just 1 row, what I would like to do is to have some empty rows(Number of rows that should be present - number of rows actually present). How can I do that ?

My First table

test-table.component.html

    <ng-container matColumnDef="id">
      Id
      {{row.id}}
    </ng-container>

    <ng-container matColumnDef="name">
      Name
      {{row.name}}
    </ng-container>

  <mat-paginator #paginator
      [length]="dataSource?.data.length"
      [pageIndex]="0"
      [pageSize]="50"
      [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>

Data source file for this

test-table-datasource.ts

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';

// TODO: Replace this with your own data model type
export interface TestTableItem {
  name: string;
  id: number;
}

// TODO: replace this with real data from your application
const EXAMPLE_DATA: TestTableItem[] = [
  {id: 1, name: 'Hydrogen'},
  {id: 2, name: 'Helium'},
  {id: 3, name: 'Lithium'},
  {id: 4, name: 'Beryllium'},
  {id: 5, name: 'Boron'},
  {id: 6, name: 'Carbon'},
  {id: 7, name: 'Nitrogen'},
  {id: 8, name: 'Oxygen'},
  {id: 9, name: 'Fluorine'},
  {id: 10, name: 'Neon'},
  {id: 11, name: 'Sodium'},
  {id: 12, name: 'Magnesium'},
  {id: 13, name: 'Aluminum'},
  {id: 14, name: 'Silicon'},
  {id: 15, name: 'Phosphorus'},
  {id: 16, name: 'Sulfur'},
  {id: 17, name: 'Chlorine'},
  {id: 18, name: 'Argon'},
  {id: 19, name: 'Potassium'},
  {id: 20, name: 'Calcium'},
];

/**
 * Data source for the TestTable view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class TestTableDataSource extends DataSource<TestTableItem> {
  data: TestTableItem[] = EXAMPLE_DATA;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<TestTableItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect() {}

  /**
   * Paginate the data (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getPagedData(data: TestTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the data (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getSortedData(data: TestTableItem[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

test-table.component.ts

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { TestTableDataSource, TestTableItem } from './test-table-datasource';

@Component({
  selector: 'app-test-table',
  templateUrl: './test-table.component.html',
  styleUrls: ['./test-table.component.css']
})
export class TestTableComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<TestTableItem>;
  dataSource: TestTableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  ngOnInit() {
    this.dataSource = new TestTableDataSource();
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }
}

My Second Table
sample-table.component.html

    <ng-container matColumnDef="id">
      Id
      {{row.id}}
    </ng-container>

    <ng-container matColumnDef="name">
      Name
      {{row.name}}
    </ng-container>

  <mat-paginator #paginator
      [length]="dataSource?.data.length"
      [pageIndex]="0"
      [pageSize]="50"
      [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>

sample-table-datasource.ts

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';

// TODO: Replace this with your own data model type
export interface SampleTableItem {
  name: string;
  id: number;
}

// TODO: replace this with real data from your application
const EXAMPLE_DATA: SampleTableItem[] = [
  {id: 1, name: 'Hydrogen'},
  {id: 2, name: 'Helium'},
  {id: 3, name: 'Lithium'},
  {id: 4, name: 'Beryllium'},
  {id: 5, name: 'Boron'},
  {id: 6, name: 'Carbon'},
  {id: 7, name: 'Nitrogen'},
  {id: 8, name: 'Oxygen'},
  {id: 9, name: 'Fluorine'},
  {id: 10, name: 'Neon'},
  {id: 11, name: 'Sodium'},
  {id: 12, name: 'Magnesium'},
  {id: 13, name: 'Aluminum'},
  {id: 14, name: 'Silicon'},
  {id: 15, name: 'Phosphorus'},
  {id: 16, name: 'Sulfur'},
  {id: 17, name: 'Chlorine'},
  {id: 18, name: 'Argon'},
  {id: 19, name: 'Potassium'},
  {id: 20, name: 'Calcium'},
];

/**
 * Data source for the SampleTable view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class SampleTableDataSource extends DataSource<SampleTableItem> {
  data: SampleTableItem[] = EXAMPLE_DATA;
  paginator: MatPaginator;
  sort: MatSort;

  constructor() {
    super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<SampleTableItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect() {}

  /**
   * Paginate the data (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getPagedData(data: SampleTableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the data (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getSortedData(data: SampleTableItem[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'id': return compare(+a.id, +b.id, isAsc);
        default: return 0;
      }
    });
  }
}

/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a: string | number, b: string | number, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}

sample-table.component.ts

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTable } from '@angular/material/table';
import { SampleTableDataSource, SampleTableItem } from './sample-table-datasource';

@Component({
  selector: 'app-sample-table',
  templateUrl: './sample-table.component.html',
  styleUrls: ['./sample-table.component.css']
})
export class SampleTableComponent implements AfterViewInit, OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatTable) table: MatTable<SampleTableItem>;
  dataSource: SampleTableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name'];

  ngOnInit() {
    this.dataSource = new SampleTableDataSource();
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
    this.table.dataSource = this.dataSource;
  }
}

app-compoenent.html

Table 1

<app-test-table></app-test-table>

Table 2

<app-sample-table></app-sample-table>

How do I add empty rows dynamically ?

Body:
If you were to use <mat-table> instead of <table>, we could denote the data source like <mat-table [dataSource]="dataSource"> and insert empty objects to it. Try the following

Controller

this.dataSource = new MatTableDataSource<any>(this.inputData);
const length = 10 - this.dataSource._data._value.length;
for (let i = 0; i < length; i++) {
  this.dataSource._data._value.push(Object.create(null));
}

Template

<div class="mat-elevation-z8">
  <mat-table [dataSource]="dataSource" class="full-width-table" matSort aria-label="Elements">
    ...

  </mat-table>
  ...
</div>

I've used constant 10 to show the behavior. To synchronize actual lengths between two components, you could setup a singleton service that allows data passage b/n the child components.


来源: stackexchange

问:
async/await in react with redux
Hi guys I am quite new to programming and trying to understand one thing with redux and await/async functions. Basically I have this function:

```<code> //nh functions
    const onSubmit = async data => {
        try{
            await dispatch(Login(data))
            if (auth.logged != false){
                addToast(content, { appearance: 'success', autoDismiss: true, })
                history.push('/')
            } else if (auth.logged == false){
                addToast(content2, { appearance: 'error', autoDismiss: true, })
            }
        }finally{
            console.log('Tada')
        }
    }

</code>```

which should first authenticate an account and then push a notification. However, the await is not working at all, and it proceeds immediately to the if statement. Any tips?

答:
I'm assuming that auth is a prop that is mapped from the redux state to the component?

If so you could get around having to create an async functionality for the submit button and handling the redirect and/or state change when the component is updated with a new value from the store.

I would recommend this as you should rather be handling any error in the action itself, that way the component can be kept simple and mainly focuses on what to display.

useEffect(() => {
  if (auth.logged != false){
      addToast(content, { appearance: 'success', autoDismiss: true, })
      history.push('/')
   }
   else if (auth.logged == false){
      addToast(content2, { appearance: 'error', autoDismiss: true, })
   }
}, [auth.logged]);

const onSubmit = data => dispatch(Login(data))
```

ContentLicense: CC BY-SA 4.0

Title: async/await in react with redux

Body:
Hi guys I am quite new to programming and trying to understand one thing with redux and await/async functions. Basically I have this function:

 //nh functions
    const onSubmit = async data => {
        try{
            await dispatch(Login(data))
            if (auth.logged != false){
                addToast(content, { appearance: 'success', autoDismiss: true, })
                history.push('/')
            } else if (auth.logged == false){
                addToast(content2, { appearance: 'error', autoDismiss: true, })
            }
        }finally{
            console.log('Tada')
        }
    }

which should first authenticate an account and then push a notification. However, the await is not working at all, and it proceeds immediately to the if statement. Any tips?


问:
React native apk versionName problemi i want to change versionName 1.0.1
I have a react native app, and I installed google play, and i wanna update this project in google play but i dont know how to get current aab file, How can I do as versionName 1.0.1 in output.json file?

答: Change the value of version in your app.json file of your project.


问:
Callback on memory access?
Does there exist a way to allocate some memory and have some sort of callback (be it pointer to a function or signal) when the memory is being accessed (either read or written to)?

For example, if I said allocate 1mb of memory, I would like to have a way to call a function when any of that 1mb is being accessed.

The platform I'm working on is x86 Linux and writing in C/C++.

答:
Yes, there is.

Use the mprotect(2) system call (see: http://linux.die.net/man/2/mprotect) to set read only or no access memory protection on the page and set a SIGEGVsignal handler that will be called when the memory has been accessed.

Note that you will need to use mprotect in your signal handler to actually allow the memory access once your signal handler is called and when you do you open a window to anything else to access the memory without you knowing it, for example from a different thread. This may or may not be an issue depending on your specific usage.

ContentLicense: CC BY-SA 3.0

Title: Callback on memory access?


问:
Non-integer constant in GROUP BY
I have the following line of code that is supposed to build a Pandas DataFrame from a SQL query:

```<code>query_epd = pandas.read_sql_query("SELECT 'Department', COUNT('LastName') FROM thestaff.employees GROUP BY 'Department'", engine)
</code>```

Yet when I run my code this line gives me the error:

```<code>SyntaxError: non-integer constant in GROUP BY
LINE 1: ...OUNT('LastName') FROM thestaff.employees GROUP BY 'Departmen...
                                                             ^
</code>```

I don't see where or how I am using constants, integer or not, and this is a very standard query for me on MSSQL, but running under PostgreSQL and Pandas this query is not valid. What is wrong with my query?

答: This link might be helpful Non-integer constants in the ORDER BY clause they explain what this error is and when it occurs</p>

Title: Non-integer constant in GROUP BY

Body:
I have the following line of code that is supposed to build a Pandas DataFrame from a SQL query:

query_epd = pandas.read_sql_query("SELECT 'Department', COUNT('LastName') FROM thestaff.employees GROUP BY 'Department'", engine)

Yet when I run my code this line gives me the error:

SyntaxError: non-integer constant in GROUP BY
LINE 1: ...OUNT('LastName') FROM thestaff.employees GROUP BY 'Departmen...
                                                             ^

I don't see where or how I am using constants, integer or not, and this is a very standard query for me on MSSQL, but running under PostgreSQL and Pandas this query is not valid. What is wrong with my query?


问:
Python split text into tokens using regex
Hi I have a question about splitting strings into tokens.

Here is an example string:

string = "As I was waiting, a man came out of a side room, and at a glance I was sure he must be Long John. His left leg was cut off close by the hip, and under the left shoulder he carried a crutch, which he managed with wonderful dexterity, hopping about upon it like a bird. He was very tall and strong, with a face as big as a ham—plain and pale, but intelligent and smiling. Indeed, he seemed in the most cheerful spirits, whistling as he moved about among the tables, with a merry word or a slap on the shoulder for the more favoured of his guests."

and I'm trying to split string correctly into its tokens.

Here is my function count_words

```<code>def count_words(text):
    """Count how many times each unique word occurs in text."""
    counts = dict()  # dictionary of { <word>: <count> } pairs to return
    #counts["I"] = 1
    print(text)
    # TODO: Convert to lowercase
    lowerText = text.lower()
    # TODO: Split text into tokens (words), leaving out punctuation
    # (Hint: Use regex to split on non-alphanumeric characters)
    split = re.split("[\s.,!?:;'\"-]+",lowerText)
    print(split)
    # TODO: Aggregate word counts using a dictionary
</code>```

and the result of split here

['as', 'i', 'was', 'waiting', 'a', 'man', 'came', 'out', 'of', 'a',
  'side', 'room', 'and', 'at', 'a', 'glance', 'i', 'was', 'sure', 'he',
  'must', 'be', 'long', 'john', 'his', 'left', 'leg', 'was', 'cut',
  'off', 'close', 'by', 'the', 'hip', 'and', 'under', 'the', 'left',
  'shoulder', 'he', 'carried', 'a', 'crutch', 'which', 'he', 'managed',
  'with', 'wonderful', 'dexterity', 'hopping', 'about', 'upon', 'it',
  'like', 'a', 'bird', 'he', 'was', 'very', 'tall', 'and', 'strong',
  'with', 'a', 'face', 'as', 'big', 'as', 'a', 'ham—plain', 'and',
  'pale', 'but', 'intelligent', 'and', 'smiling', 'indeed', 'he',
  'seemed', 'in', 'the', 'most', 'cheerful', 'spirits', 'whistling',
  'as', 'he', 'moved', 'about', 'among', 'the', 'tables', 'with', 'a',
  'merry', 'word', 'or', 'a', 'slap', 'on', 'the', 'shoulder', 'for',
  'the', 'more', 'favoured', 'of', 'his', 'guests', '']

as you see there is the empty string '' in the last index of the split list.

Please help me understand this empty string in the list and to correctly split this example string.

答:
```<code>import string

def count_words(text):

    counts = dict()

    text = text.translate(text.maketrans('', '', string.punctuation))
    text = text.lower()

    words = text.split()
    print(words)

    for word in words:
        if word not in counts:
            counts[word] = 1
        else:
            counts[word] += 1

    return counts
</code>```

It works.

Body:
Hi I have a question about splitting strings into tokens.

Here is an example string:

string = "As I was waiting, a man came out of a side room, and at a glance I was sure he must be Long John. His left leg was cut off close by the hip, and under the left shoulder he carried a crutch, which he managed with wonderful dexterity, hopping about upon it like a bird. He was very tall and strong, with a face as big as a ham—plain and pale, but intelligent and smiling. Indeed, he seemed in the most cheerful spirits, whistling as he moved about among the tables, with a merry word or a slap on the shoulder for the more favoured of his guests."

and I'm trying to split string correctly into its tokens.

Here is my function count_words

def count_words(text):
    """Count how many times each unique word occurs in text."""
    counts = dict()  # dictionary of { <word>: <count> } pairs to return
    #counts["I"] = 1
    print(text)
    # TODO: Convert to lowercase
    lowerText = text.lower()
    # TODO: Split text into tokens (words), leaving out punctuation
    # (Hint: Use regex to split on non-alphanumeric characters)
    split = re.split("[\s.,!?:;'\"-]+",lowerText)
    print(split)
    # TODO: Aggregate word counts using a dictionary

and the result of split here

['as', 'i', 'was', 'waiting', 'a', 'man', 'came', 'out', 'of', 'a',
  'side', 'room', 'and', 'at', 'a', 'glance', 'i', 'was', 'sure', 'he',
  'must', 'be', 'long', 'john', 'his', 'left', 'leg', 'was', 'cut',
  'off', 'close', 'by', 'the', 'hip', 'and', 'under', 'the', 'left',
  'shoulder', 'he', 'carried', 'a', 'crutch', 'which', 'he', 'managed',
  'with', 'wonderful', 'dexterity', 'hopping', 'about', 'upon', 'it',
  'like', 'a', 'bird', 'he', 'was', 'very', 'tall', 'and', 'strong',
  'with', 'a', 'face', 'as', 'big', 'as', 'a', 'ham—plain', 'and',
  'pale', 'but', 'intelligent', 'and', 'smiling', 'indeed', 'he',
  'seemed', 'in', 'the', 'most', 'cheerful', 'spirits', 'whistling',
  'as', 'he', 'moved', 'about', 'among', 'the', 'tables', 'with', 'a',
  'merry', 'word', 'or', 'a', 'slap', 'on', 'the', 'shoulder', 'for',
  'the', 'more', 'favoured', 'of', 'his', 'guests', '']

as you see there is the empty string '' in the last index of the split list.

Please help me understand this empty string in the list and to correctly split this example string.

Body:
import string

def count_words(text):

    counts = dict()

    text = text.translate(text.maketrans('', '', string.punctuation))
    text = text.lower()

    words = text.split()
    print(words)

    for word in words:
        if word not in counts:
            counts[word] = 1
        else:
            counts[word] += 1

    return counts

It works.


问:
C-style exec in python
In bash or C, exec will terminate the current process and replace it with something new. Can this functionality be accomplished in Python? I don't wish to simply execute some code then continue running the python script (even just to immediately exit), or spawn a child process.

My specific situation is the following. I'm developing a command line application (python + curses) to manage data generation/analysis in the context of scientific computing. It will sometimes be necessary for me to terminate the application and go wrangle with the data in a given subdirectory manually. It would be convenient if I could do something like:

```<code># within python script; d=<some directory>
if exit_and_goto_dir:
    exec("pushd {}".format(d)) # C-style exec -- terminate program and execute new command
</code>```

The following do not work, for example:

```<code># attempt 1
if exit_and_goto_dir:
    os.system("pushd {}".format(d))
    exit(0) # pushd does not outlast the python script

# attempt 2
if exit_and_goto_dir:
    os.chdir(d)
    exit(0)
</code>```

This behavior isn't really critical. There are plenty of work arounds (e.g. print the directory I care about to terminal then cd manually). Mostly I'm curious if it's possible. Thanks!

答:
The os module contains Python wrappers for the various exec* functions in the C standard library:

```<code>>>> [method for method in dir(os) if method.startswith("exec")]
['execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe']
</code>```

However, pushd is not an executable that you can exec but rather a bash builtin (and the same is true for cd).

What you could do would be to change directory inside the python process and then exec an interactive shell:

```<code>import os
os.chdir(d)
os.execvp("bash", ["bash", "-login"])
</code>```

Python's current directory will be inherited by the shell that you exec.  When you later exit from that shell, control will then return to the original login shell from which you invoked python (unless you used that shell's exec command to launch python in the first place).

What you can't do is to modify the current directory of the calling shell from inside python, in order to return to the shell prompt but in a different working directory from when python was invoked.  (At least there's no straightforward way. There is a hack involving attaching gdb to it, described here, but which only worked as root when I tried it on Ubuntu.)

Title: C-style exec in python

Body:
In bash or C, exec will terminate the current process and replace it with something new. Can this functionality be accomplished in Python? I don't wish to simply execute some code then continue running the python script (even just to immediately exit), or spawn a child process.

My specific situation is the following. I'm developing a command line application (python + curses) to manage data generation/analysis in the context of scientific computing. It will sometimes be necessary for me to terminate the application and go wrangle with the data in a given subdirectory manually. It would be convenient if I could do something like:

# within python script; d=<some directory>
if exit_and_goto_dir:
    exec("pushd {}".format(d)) # C-style exec -- terminate program and execute new command

The following do not work, for example:

# attempt 1
if exit_and_goto_dir:
    os.system("pushd {}".format(d))
    exit(0) # pushd does not outlast the python script

# attempt 2
if exit_and_goto_dir:
    os.chdir(d)
    exit(0)

This behavior isn't really critical. There are plenty of work arounds (e.g. print the directory I care about to terminal then cd manually). Mostly I'm curious if it's possible. Thanks!

Body:
The os module contains Python wrappers for the various exec* functions in the C standard library:

>>> [method for method in dir(os) if method.startswith("exec")]
['execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe']

However, pushd is not an executable that you can exec but rather a bash builtin (and the same is true for cd).

What you could do would be to change directory inside the python process and then exec an interactive shell:

import os
os.chdir(d)
os.execvp("bash", ["bash", "-login"])

Python's current directory will be inherited by the shell that you exec.  When you later exit from that shell, control will then return to the original login shell from which you invoked python (unless you used that shell's exec command to launch python in the first place).

What you can't do is to modify the current directory of the calling shell from inside python, in order to return to the shell prompt but in a different working directory from when python was invoked.  (At least there's no straightforward way. There is a hack involving attaching gdb to it, described here, but which only worked as root when I tried it on Ubuntu.)


问:
query selector find dynamic elements
iam trying to fetch my .btn-viewdetail buttons with the query selector.But only the button i created manually is fetched by the function, not the dynamically created ones. I dont know why, they all have the same class name.

Is it becuase if the , I warp the input buttons in?

does anyone has a solution to this problem?

```<code>window.onload=function(){
    this.getPerson();
    this.document.getElementById('getPerson').addEventListener('click', this.getPerson);
    //this.document.getElementById('deletePerson').addEventListener('click', this.deletePerson);
}

function createNode(element) {
    return document.createElement(element);
}

function append(parent, el) {
  return parent.appendChild(el);
}

const ul = document.getElementById('person');
const url ='http://localhost:8080/person';
var x = 1;

function getPerson(){
//addButton.value = "+";
//addButton.class = "btn btn-success";
$("#output1 tbody tr").remove();
fetch(url)
    .then(res => res.json())
    .then(data => {

        //console.log(data);

        var temp = "";
        data.forEach((person) => {
            temp += "<tr>";
            temp += "<td>" +person.id+"</td>";
            //console.log(person.id);
            temp += "<td>" +person.vorname+"</td>";
            temp += "<td>" +person.nachname+"</td>";
            temp += "<td>"
            person.projectList.forEach((project) => {
              temp += project.name+"<br>";
            });
            temp += "</td>"

            temp += "<td>"
            person.technoList.forEach((techno) => {
              temp += techno.name+"<br>";
            });
            temp += "</td>"

            /*id='addButton" + x + "'*/

            temp += "<td>" + addButton(person.id)+ "</td>"
             //this.parentElement.appendChild(this)
             x++;

            //document.getElementById('personDetail_Button').addEventListener('click', this.personDetail(person.id));
            temp += "</tr>"

        });

        document.getElementById("tableOutput").innerHTML= temp;

    });
}

function addButton(person_id){
  var element = document.createElement("input");
  element.type = 'button';
  element.value = 'test123';
  element.setAttribute("data-person_id",person_id);
  element.setAttribute("class","btn-viewdetail btn btn-primary");

  var _wrap = document.createElement("div");
  _wrap.appendChild(element);

 return _wrap.innerHTML;

}

document.body.innerHTML += addButton(4);

function personDetail(person_id_request){
 //console.log(person_id_request);
 fetch('http://localhost:8080/person/' + person_id_request)
    .then(res => res.json())
    .then(data => {

     console.log(data);
   });
}

function deletePerson(){
var id = document.getElementById('id_delete').value;
var id_input = document.getElementById('id_delete');
fetch('http://localhost:8080/person/' + id, {
    method: 'DELETE',
    })
    .then(res => {
        console.log(res.status)
        if(res.status == 200){
            alert("Die Person mit der ID " +id +" wurde gelöscht");
            getPerson();
            }else{
                alert("Leider konnten wir die Person nicht löschen, hast du vielleicht die falsche ID angegeben? " + res.status)

            }
        res.json();
        $('#id_delete').reset;
    })
    .then((data) => {
    })
}

var _btns = document.querySelectorAll(".btn-viewdetail");
console.log(_btns);
_btns.forEach(function (el) {
  el.addEventListener('click',function(evt){
    console.log(evt.target.getAttribute("data-person_id"));
    personDetail(evt.target.getAttribute("data-person_id"));
  });
});
</code>```

答:
The moment
var _btns = document.querySelectorAll(".btn-viewdetail");
gets executed there is no <input class="btn-viewdetail"> element yet in the html document.

That's because the document.getElementById("tableOutput").innerHTML= temp; code gets executed at a later time.

The way to fix this is to apply the click event listener el.addEventListener('click',function(evt){ after the moment the input element is created var element = document.createElement("input");.

It will look something like this:

function addButton(person_id){
  var element = document.createElement("input");
  element.addEventListener('click',function(evt){
  ...
```

Title: query selector find dynamic elements

Body:
iam trying to fetch my .btn-viewdetail buttons with the query selector.But only the button i created manually is fetched by the function, not the dynamically created ones. I dont know why, they all have the same class name.

Is it becuase if the , I warp the input buttons in?

does anyone has a solution to this problem?

window.onload=function(){
    this.getPerson();
    this.document.getElementById('getPerson').addEventListener('click', this.getPerson);
    //this.document.getElementById('deletePerson').addEventListener('click', this.deletePerson);
}

function createNode(element) {
    return document.createElement(element);
}

function append(parent, el) {
  return parent.appendChild(el);
}

const ul = document.getElementById('person');
const url ='http://localhost:8080/person';
var x = 1;

function getPerson(){
//addButton.value = "+";
//addButton.class = "btn btn-success";
$("#output1 tbody tr").remove();
fetch(url)
    .then(res => res.json())
    .then(data => {

        //console.log(data);

        var temp = "";
        data.forEach((person) => {
            temp += "
";
            temp += "" +person.id+"	";
            //console.log(person.id);
            temp += "" +person.vorname+"	";
            temp += "" +person.nachname+"	";
            temp += ""
            person.projectList.forEach((project) => {
              temp += project.name+"
";
            });
            temp += "	"

            temp += ""
            person.technoList.forEach((techno) => {
              temp += techno.name+"
";
            });
            temp += "	"

            /*id='addButton" + x + "'*/

            temp += "" + addButton(person.id)+ "	"
             //this.parentElement.appendChild(this)
             x++;

            //document.getElementById('personDetail_Button').addEventListener('click', this.personDetail(person.id));
            temp += "
"

        });

        document.getElementById("tableOutput").innerHTML= temp;

    });
}

function addButton(person_id){
  var element = document.createElement("input");
  element.type = 'button';
  element.value = 'test123';
  element.setAttribute("data-person_id",person_id);
  element.setAttribute("class","btn-viewdetail btn btn-primary");

  var _wrap = document.createElement("div");
  _wrap.appendChild(element);

 return _wrap.innerHTML;

}

document.body.innerHTML += addButton(4);

function personDetail(person_id_request){
 //console.log(person_id_request);
 fetch('http://localhost:8080/person/' + person_id_request)
    .then(res => res.json())
    .then(data => {

     console.log(data);
   });
}

function deletePerson(){
var id = document.getElementById('id_delete').value;
var id_input = document.getElementById('id_delete');
fetch('http://localhost:8080/person/' + id, {
    method: 'DELETE',
    })
    .then(res => {
        console.log(res.status)
        if(res.status == 200){
            alert("Die Person mit der ID " +id +" wurde gelöscht");
            getPerson();
            }else{
                alert("Leider konnten wir die Person nicht löschen, hast du vielleicht die falsche ID angegeben? " + res.status)

            }
        res.json();
        $('#id_delete').reset;
    })
    .then((data) => {
    })
}

var _btns = document.querySelectorAll(".btn-viewdetail");
console.log(_btns);
_btns.forEach(function (el) {
  el.addEventListener('click',function(evt){
    console.log(evt.target.getAttribute("data-person_id"));
    personDetail(evt.target.getAttribute("data-person_id"));
  });
});


问:
iterating over dynamic content with jquery
```<code>var deneme = document.getElementsByClassName("content-holder");
var uzat = document.getElementsByClassName("uzat");
for (var i = 0; i < deneme.length; i++) {
    var yuksek = deneme[i].offsetHeight;
    if (yuksek > 250) {
        deneme[i].style.height = "97px";
        uzat[i].style.display = "block"
    }
};
</code>```

This function finds entries in a page that are longer than 250 px and shrinks them to 97 px, also adds a button "uzat" and when this button is clicked entry gets back to the original size.

Now I'm using infinite scroll to load new entries and this function doesn't work on newly loaded entries. I tried to trigger the function every time new content is added but it also affected the old entries. Is there any way to change only the new entries without affecting the old ones?

Infinite scroll html:

```<code><div class="infinite-container">
    {% for entry in entries_list %}
    <div class="entry-yazar infinite-item">
        <span class=title-span>{{entry.title}}</span>
        <p class=content-holder id={{entry.id}}>
            {% if entry.safe %}{{entry.content|safe|linebreaksbr}}{% else %}{{entry.content|linebreaksbr}}{% endif %}
        </p>
        <button id="{{entry.id}}b" onclick="larger('{{entry.id}}','{{entry.id}}b')" class=uzat>doyamadım...</button>
        <form method="GET">
            {% csrf_token %}

            {% if own_entry > 0 %}
            <div class=entry-bottom>
                <span class=num-holder>{{entry.own_like}}</span>
                <img class=icon3 src="{% static 'icons\facebook.png' %}" alt="facebook">
                <img class=icon4 src="{% static 'icons\twitter.png' %}" alt="twitter">
                <time>
                    {% if best_one == entry.id %}
                    <img class=star-icon src="{% static 'icons\golden-star.png' %}" alt="like">
                    {% endif %}
                    {% if today_best_one == entry.id %}
                    <img class=star-icon src="{% static 'icons\bronze-star.png' %}" alt="like">
                    {% endif %}
                    <span class=timer>{{entry.created_date|date:'Y-m-d H:i'}}</span>
                </time>
                <div class=user-holder>
                    <a href="/entries/delete/{{entry.id}}"><img class=edit-icon src="{% static 'icons\delete.png' %}"
                            alt="sil"></a>
                    <a href="/entries/edit/{{entry.id}}"><img class=edit-icon src="{% static 'icons\edit2.png' %}"
                            alt="edit"></a>
                </div>

                {% else %}

                <form method="GET">
                    {% csrf_token %}

                    {% if entry.already_liked %}
                    <button type="button" onclick="like('{{entry.id}}')" class=active-button id=like-button{{entry.id}}><img
                            class=icon5 src="{% static 'icons\virus.png' %}" alt="like"></button>
                    <button style="display:none" onclick="like('{{entry.id}}')" class=active-button type="button"
                        id=dislike-button{{entry.id}}><img class=icon5 src="{% static 'icons\passive-virus.png' %}"
                            alt="dislike"></button>
                    <img class=icon3 src="{% static 'icons\facebook.png' %}" alt="facebook">
                    <img class=icon4 src="{% static 'icons\twitter.png' %}" alt="twitter">
                    <time>
                        {% if best_one == entry.id %}
                            <img class=star-icon src="{% static 'icons\golden-star.png' %}" alt="like">
                        {% endif %}
                        {% if today_best_one == entry.id %}
                            <img class=star-icon src="{% static 'icons\bronze-star.png' %}" alt="a-like">
                        {% endif %}
                        {% if followed_best_one == entry.id %}
                            <img class=star-icon src="{% static 'icons\purple-star.png' %}" alt="f-like">
                        {% endif %}
                        {% if today_followed_best_one == entry.id %}
                            <img class=star-icon src="{% static 'icons\blue-star.png' %}" alt="af-like">
                        {% endif %}
                        <span class=timer>{{entry.created_date|date:'Y-m-d H:i'}}</span>
                    </time>
                    {% else %}
                    <button style="display:none" onclick="like('{{entry.id}}')" class=active-button type="button"
                        id=like-button{{entry.id}}><img class=icon5 src="{% static 'icons\virus.png' %}" alt="like"></button>
                    <button type="button" id=dislike-button{{entry.id}} class=active-button onclick="like('{{entry.id}}')"><img
                            class=icon5 src="{% static 'icons\passive-virus.png' %}" alt="dislike"></button>
                    <img class=icon3 src="{% static 'icons\facebook.png' %}" alt="facebook">
                    <img class=icon4 src="{% static 'icons\twitter.png' %}" alt="twitter">
                    <time>
                        {% if best_one == entry.id %}
                            <img class=star-icon src="{% static 'icons\golden-star.png' %}" alt="like">
                        {% endif %}
                        {% if today_best_one == entry.id %}
                            <img class=star-icon src="{% static 'icons\bronze-star.png' %}" alt="a-like">
                        {% endif %}
                        {% if followed_best_one == entry.id %}
                            <img class=star-icon src="{% static 'icons\purple-star.png' %}" alt="f-like">
                        {% endif %}
                        {% if today_followed_best_one == entry.id %}
                            <img class=star-icon src="{% static 'icons\blue-star.png' %}" alt="af-like">
                        {% endif %}
                        <span class=timer>{{entry.created_date|date:'Y-m-d H:i'}}</span>
                    </time>
                    {% endif %}

    </div>
    {% endif %}
    {% endfor %}
</code>```

Infinite scroll jquery:

```<code> var infinite = new Waypoint.Infinite({
        element: $('.infinite-container')[0],

      });
</code>```

答:
Easiest way would be to add new entries with some type of DOM attribute that you will immediatelly remove after processing or the other way around just add one that says it was processed

like ie <element data-processed="true" />

or use additional class that you will remove on processing and search for it.

Body:
var deneme = document.getElementsByClassName("content-holder");
var uzat = document.getElementsByClassName("uzat");
for (var i = 0; i < deneme.length; i++) {
    var yuksek = deneme[i].offsetHeight;
    if (yuksek > 250) {
        deneme[i].style.height = "97px";
        uzat[i].style.display = "block"
    }
};

This function finds entries in a page that are longer than 250 px and shrinks them to 97 px, also adds a button "uzat" and when this button is clicked entry gets back to the original size.

Now I'm using infinite scroll to load new entries and this function doesn't work on newly loaded entries. I tried to trigger the function every time new content is added but it also affected the old entries. Is there any way to change only the new entries without affecting the old ones?

Infinite scroll html:

    {% for entry in entries_list %}

        {{entry.title}}

            {% if entry.safe %}{{entry.content|safe|linebreaksbr}}{% else %}{{entry.content|linebreaksbr}}{% endif %}

        <button id="{{entry.id}}b" onclick="larger('{{entry.id}}','{{entry.id}}b')" class=uzat>doyamadım...</button>
        <form method="GET">
            {% csrf_token %}

            {% if own_entry > 0 %}

                {{entry.own_like}}

                <time>
                    {% if best_one == entry.id %}

                    {% endif %}
                    {% if today_best_one == entry.id %}

                    {% endif %}
                    {{entry.created_date|date:'Y-m-d H:i'}}
                </time>

                {% else %}

                <form method="GET">
                    {% csrf_token %}

                    {% if entry.already_liked %}
                    <button type="button" onclick="like('{{entry.id}}')" class=active-button id=like-button{{entry.id}}></button>
                    <button style="display:none" onclick="like('{{entry.id}}')" class=active-button type="button"
                        id=dislike-button{{entry.id}}></button>

                    <time>
                        {% if best_one == entry.id %}

                        {% endif %}
                        {% if today_best_one == entry.id %}

                        {% endif %}
                        {% if followed_best_one == entry.id %}

                        {% endif %}
                        {% if today_followed_best_one == entry.id %}

                        {% endif %}
                        {{entry.created_date|date:'Y-m-d H:i'}}
                    </time>
                    {% else %}
                    <button style="display:none" onclick="like('{{entry.id}}')" class=active-button type="button"
                        id=like-button{{entry.id}}></button>
                    <button type="button" id=dislike-button{{entry.id}} class=active-button onclick="like('{{entry.id}}')"></button>

                    <time>
                        {% if best_one == entry.id %}

                        {% endif %}
                        {% if today_best_one == entry.id %}

                        {% endif %}
                        {% if followed_best_one == entry.id %}

                        {% endif %}
                        {% if today_followed_best_one == entry.id %}

                        {% endif %}
                        {{entry.created_date|date:'Y-m-d H:i'}}
                    </time>
                    {% endif %}

    {% endif %}
    {% endfor %}

Infinite scroll jquery:

 var infinite = new Waypoint.Infinite({
        element: $('.infinite-container')[0],

      });


问:
Can i use d3.js for creating interactive visualizations inside an android app?
I am trying to create an interactive visualization within an android app.

The data that will be visualized will be stored locally in a sqlite database and will be queried to generate visualizations.

I have not yet decided whether to build a native app or a web app.

Based on my research d3.js seems to fit the needs very well but I am unsure about how to use it in a mobile environment.

答:
For those of you, like me, trying to learn how to integrate D3 in Android via the referenced tutorial here is the js code for the D3 Pie Chart for the current D3 Version V5.</p>

```<code>function loadPieChart(dataset) {
      var svg = d3.select("#piechart");
      var height = 500;
      var width = 500;
      var textLabelSuffix = "%";

      showPieChart(dataset, svg, height, width,
          textLabelSuffix);
    }

    function showPieChart(dataset, svg, height, width,
      textLabelSuffix)
    {
      var outerRadius = width / 2;
      var innerRadius = 0;

      // set height/width to match the SVG element
      svg.attr("height", height).attr("width", width);

      // create a new pie layout
      var pie = d3.pie();

      // initialize arcs/wedges to span
      // the radius of the circle
      var arc = d3.arc()
                   .innerRadius(innerRadius)
                   .outerRadius(outerRadius);

      // create groups
      var arcs = svg.selectAll("g.arc")
                    // bind dataset to pie layout
                    .data(pie(dataset))
                    // create groups
                    .enter()
                    // append groups
                    .append("g")
                    // create arcs
                    .attr("class", "arc")
                    // position each arc in the pie layout
                    .attr("transform", "translate(" +
                     outerRadius + "," +
                     outerRadius + ")");

      // initialize color scale - refer to
      // <a href="https://github.com/mbostock/d3/wiki/Ordinal-Scales" target="_blank">https://github.com/mbostock/d3/wiki/Ordinal-Scales</a>
      var color = d3.scaleOrdinal(d3.schemeAccent);

      arcs.append("path")
          .attr("fill", function(d,i) { return color(i); })
          .attr("d", arc);

      arcs.append("text")
          .attr("transform", function(d) {
              return "translate(" + arc.centroid(d) + ")";
           })
          .attr("text-anchor", "middle")
          .text(function(d) { return d.value +
             textLabelSuffix; });
    }
</code>```

Body:
For those of you, like me, trying to learn how to integrate D3 in Android via the referenced tutorial here is the js code for the D3 Pie Chart for the current D3 Version V5.

function loadPieChart(dataset) {
      var svg = d3.select("#piechart");
      var height = 500;
      var width = 500;
      var textLabelSuffix = "%";

      showPieChart(dataset, svg, height, width,
          textLabelSuffix);
    }

    function showPieChart(dataset, svg, height, width,
      textLabelSuffix)
    {
      var outerRadius = width / 2;
      var innerRadius = 0;

      // set height/width to match the SVG element
      svg.attr("height", height).attr("width", width);

      // create a new pie layout
      var pie = d3.pie();

      // initialize arcs/wedges to span
      // the radius of the circle
      var arc = d3.arc()
                   .innerRadius(innerRadius)
                   .outerRadius(outerRadius);

      // create groups
      var arcs = svg.selectAll("g.arc")
                    // bind dataset to pie layout
                    .data(pie(dataset))
                    // create groups
                    .enter()
                    // append groups
                    .append("g")
                    // create arcs
                    .attr("class", "arc")
                    // position each arc in the pie layout
                    .attr("transform", "translate(" +
                     outerRadius + "," +
                     outerRadius + ")");

      // initialize color scale - refer to
      // <a href="https://github.com/mbostock/d3/wiki/Ordinal-Scales" target="_blank">https://github.com/mbostock/d3/wiki/Ordinal-Scales</a>
      var color = d3.scaleOrdinal(d3.schemeAccent);

      arcs.append("path")
          .attr("fill", function(d,i) { return color(i); })
          .attr("d", arc);

      arcs.append("text")
          .attr("transform", function(d) {
              return "translate(" + arc.centroid(d) + ")";
           })
          .attr("text-anchor", "middle")
          .text(function(d) { return d.value +
             textLabelSuffix; });
    }


问:
Devise + Sendgrid confirmations - Ruby on Rails
So I'm trying to setup email confirmations for this app, and I've pretty much got it down so far. It's working perfectly in development (using sendgrid), but not in production. It just errors out in production. I've set the config environment (via account I have with sendgrid API integration) I've followed a number of tutorials using both the SMTP method and the WebAPI whatnot. None of it is working. I tried doing a test message with the bundle exec on an rb file, that worked perfectly. The confirmation codes are fine, the emails are going out on development (local environment), but I glitch out on production confirmation emails and only when being sent. The page itself will let me know if there is an error with the email, or if an email is already being used, but it errors out only when sending the email.  This tells me that the email code is good, there's just something wrong with my API integration. Here's the code:

./Environments/production.rb:

```<code>config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => 'bryan-saas-app.herokuapp.com', :protocol => 'https' }
</code>```

./Initializers/devise.rb:

```<code>config.mailer_sender = 'info@mysyte.com'
</code>```

./Config/environments.rb:

```<code>ActionMailer::Base.smtp_settings = {

  :address => 'smtp.sendgrid.net',
  :port => '587',
  :authentication => :plain,
  :user_name => ENV['SENDGRID_USERNAME'],
  :password => ENV['SENDGRID_PASSWORD'],
  :domain => 'heroku.com',
  :enable_starttls_auto => true

}
</code>```

./sendgrid.env:

```<code>export SENDGRID_API_KEY='full api key'
export SENDGRID_USERNAME='apikey'
export SENDGRID_PASSWORD='full api key'
</code>```

Am I missing something? For what it's worth, I can't access my sendgrid account from the heroku app/config.add-ons area of the dashboard. It errors out there too, so I made a new sendgrid account (personal, non-heroku link) and used an API code from there. Not sure if this would break something.

答:
Sendgrid has nothing to do with your development environment.

Console:

```<code>heroku addons:create sendgrid:starter
</code>```

application_mailer.rb:

```<code>  #replace corsego with your app name
  default from: 'support@corsego.herokuapp.com'
</code>```

production.rb:

```<code>ActionMailer::Base.smtp_settings = {
  :address => 'smtp.sendgrid.net',
  :port => '587',
  :authentication => :plain,
  :user_name => ENV['SENDGRID_USERNAME'],
  :password => ENV['SENDGRID_PASSWORD'],
  :domain => 'heroku.com',
  :enable_starttls_auto => true
}
</code>```

environment.rb:

```<code>      #replace corsego with your app name
      config.action_mailer.default_url_options = { :host => 'corsego.herokuapp.com', :protocol => 'https' }
      config.action_mailer.perform_deliveries = true
      config.action_mailer.delivery_method = :smtp
</code>```

Documentation: https://devcenter.heroku.com/articles/sendgrid

Push the changes to production and you're done with sendgrid.

Devise confirmable is explalined step by step here https://github.com/heartcombo/devise/wiki/How-To:-Add-:confirmable-to-Users

Body:
So I'm trying to setup email confirmations for this app, and I've pretty much got it down so far. It's working perfectly in development (using sendgrid), but not in production. It just errors out in production. I've set the config environment (via account I have with sendgrid API integration) I've followed a number of tutorials using both the SMTP method and the WebAPI whatnot. None of it is working. I tried doing a test message with the bundle exec on an rb file, that worked perfectly. The confirmation codes are fine, the emails are going out on development (local environment), but I glitch out on production confirmation emails and only when being sent. The page itself will let me know if there is an error with the email, or if an email is already being used, but it errors out only when sending the email.  This tells me that the email code is good, there's just something wrong with my API integration. Here's the code:

./Environments/production.rb:

config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { :host => 'bryan-saas-app.herokuapp.com', :protocol => 'https' }

./Initializers/devise.rb:

config.mailer_sender = 'info@mysyte.com'

./Config/environments.rb:

ActionMailer::Base.smtp_settings = {

  :address => 'smtp.sendgrid.net',
  :port => '587',
  :authentication => :plain,
  :user_name => ENV['SENDGRID_USERNAME'],
  :password => ENV['SENDGRID_PASSWORD'],
  :domain => 'heroku.com',
  :enable_starttls_auto => true

}

./sendgrid.env:

export SENDGRID_API_KEY='full api key'
export SENDGRID_USERNAME='apikey'
export SENDGRID_PASSWORD='full api key'

Am I missing something? For what it's worth, I can't access my sendgrid account from the heroku app/config.add-ons area of the dashboard. It errors out there too, so I made a new sendgrid account (personal, non-heroku link) and used an API code from there. Not sure if this would break something.

Body:
Sendgrid has nothing to do with your development environment.

Console:

heroku addons:create sendgrid:starter

application_mailer.rb:

  #replace corsego with your app name
  default from: 'support@corsego.herokuapp.com'

production.rb:

ActionMailer::Base.smtp_settings = {
  :address => 'smtp.sendgrid.net',
  :port => '587',
  :authentication => :plain,
  :user_name => ENV['SENDGRID_USERNAME'],
  :password => ENV['SENDGRID_PASSWORD'],
  :domain => 'heroku.com',
  :enable_starttls_auto => true
}

environment.rb:

      #replace corsego with your app name
      config.action_mailer.default_url_options = { :host => 'corsego.herokuapp.com', :protocol => 'https' }
      config.action_mailer.perform_deliveries = true
      config.action_mailer.delivery_method = :smtp

Documentation: https://devcenter.heroku.com/articles/sendgrid

Push the changes to production and you're done with sendgrid.

Devise confirmable is explalined step by step here https://github.com/heartcombo/devise/wiki/How-To:-Add-:confirmable-to-Users


问:
Does flash play .avi or .mpg4 ? If yes, how?
How to load and play .avi or .mpg4 in Flash? Is that possible ?

-> This class can play .flv and also .mp4 .. but for .avi it shows error "Error #2044: Unhandled NetStatusEvent:. level=error, code=NetStream.Play.StreamNotFound"

```<code>package src {
    import flash.display.Sprite;
    import flash.media.Video;
    import flash.net.NetConnection;
    import flash.net.NetStream;
    import flash.events.Event;
    import flash.events.MouseEvent;

        public class vplayer extends Sprite{
            public var vid:Video = new Video(1920,1080);
            private var nc:NetConnection = new NetConnection();
            public var ns:NetStream;
            public var listener:Object = new Object();
            private var _duration:Number = 0;

            public function vplayer():void{
                addChild(vid);
                nc.connect(null);
                ns = new NetStream(nc);
                vid.attachNetStream(ns);
                listener.onMetaData = metaDataHandler;
                ns.client = listener;
                //customClient.onCuePoint = cuePointHandler;
            }
            public function playVideo00(vv:String):void{

                ns.play(vv);
            }
            public function stopVideo00():void{
                ns.close();
            }
            /*public function cuePointHandler(infoObject:Object):void {
                trace("cuePoint");
            }*/
            public function metaDataHandler(infoObject:Object):void {
                _duration = infoObject["duration"];
                trace (" Time:  " + infoObject["duration"]);
            }
            public function get duration00():Number {
                return _duration;
            }
        }
}
</code>```

.. any help ?

答: this example can play .mp4 files

Body:
How to load and play .avi or .mpg4 in Flash? Is that possible ?

-> This class can play .flv and also .mp4 .. but for .avi it shows error "Error #2044: Unhandled NetStatusEvent:. level=error, code=NetStream.Play.StreamNotFound"

package src {
    import flash.display.Sprite;
    import flash.media.Video;
    import flash.net.NetConnection;
    import flash.net.NetStream;
    import flash.events.Event;
    import flash.events.MouseEvent;

        public class vplayer extends Sprite{
            public var vid:Video = new Video(1920,1080);
            private var nc:NetConnection = new NetConnection();
            public var ns:NetStream;
            public var listener:Object = new Object();
            private var _duration:Number = 0;

            public function vplayer():void{
                addChild(vid);
                nc.connect(null);
                ns = new NetStream(nc);
                vid.attachNetStream(ns);
                listener.onMetaData = metaDataHandler;
                ns.client = listener;
                //customClient.onCuePoint = cuePointHandler;
            }
            public function playVideo00(vv:String):void{

                ns.play(vv);
            }
            public function stopVideo00():void{
                ns.close();
            }
            /*public function cuePointHandler(infoObject:Object):void {
                trace("cuePoint");
            }*/
            public function metaDataHandler(infoObject:Object):void {
                _duration = infoObject["duration"];
                trace (" Time:  " + infoObject["duration"]);
            }
            public function get duration00():Number {
                return _duration;
            }
        }
}

.. any help ?

Body: this example can play .mp4 files


问:
how to specified color in plot from matplotlib
I have player data from fifa 19. It has Composure, Penalties ability, and Nationality. I would like to plot in a figure with X axis is Composure and Y axis is Penalties ability, but i would like to color it if the player from some nationality. I have this code:

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

df= pandas.read_csv('fifa19.csv')

n= len(df)
x=[]
y=[]
fig, ax=plt.subplots()
j=0
for i in range(n):
   if(not math.isnan(df['Composure'][i])
       and not math.isnan(df['Penalties'][i])):
       x.append(df['Composure'][i])
       y.append(df['Penalties'][i])
   if(df['Nationality'][i]=='Brazil'): #it supposed to be blue if the nationality is brazil else is default(correct me if i'm wrong)
       ax.plot(x, y, 'o', color='blue')

ax.set_xlabel('Composure attribute')
ax.set_ylabel('Penalties attribute')
fig.show()
</code>```

But it all turned to blue.
I have tried to change the loop like this:

```<code>if(df['Nationality'][i]=='Brazil'):
        ax.plot(x[i], y[i], 'o', color='blue')
</code>```

But it says 'IndexError: list index out of range'. Any idea how to color it using plot? Thank you for your help.

答:
use this code

```<code>import matplotlib
from matplotlib import style

plt.title("Natitk")
plt.plot([1,4,7],[3,4,5],linewidth=4, Label="first", color="yellow")
plt.plot([5,4,7],[2,6,8],linewidth=4, Label="second")

plt.legend()

plt.xlabel("x")
style.use("ggplot")
plt.ylabel("y")
</code>```

store yellow in a variable and then use if statement

Body:
I have player data from fifa 19. It has Composure, Penalties ability, and Nationality. I would like to plot in a figure with X axis is Composure and Y axis is Penalties ability, but i would like to color it if the player from some nationality. I have this code:

import pandas
import math
import matplotlib.pyplot as plt

df= pandas.read_csv('fifa19.csv')

n= len(df)
x=[]
y=[]
fig, ax=plt.subplots()
j=0
for i in range(n):
   if(not math.isnan(df['Composure'][i])
       and not math.isnan(df['Penalties'][i])):
       x.append(df['Composure'][i])
       y.append(df['Penalties'][i])
   if(df['Nationality'][i]=='Brazil'): #it supposed to be blue if the nationality is brazil else is default(correct me if i'm wrong)
       ax.plot(x, y, 'o', color='blue')

ax.set_xlabel('Composure attribute')
ax.set_ylabel('Penalties attribute')
fig.show()

But it all turned to blue.
I have tried to change the loop like this:

if(df['Nationality'][i]=='Brazil'):
        ax.plot(x[i], y[i], 'o', color='blue')

But it says 'IndexError: list index out of range'. Any idea how to color it using plot? Thank you for your help.

Body:
use this code

import matplotlib
from matplotlib import style

plt.title("Natitk")
plt.plot([1,4,7],[3,4,5],linewidth=4, Label="first", color="yellow")
plt.plot([5,4,7],[2,6,8],linewidth=4, Label="second")

plt.legend()

plt.xlabel("x")
style.use("ggplot")
plt.ylabel("y")

store yellow in a variable and then use if statement


问:
Regex for parse YAML
I have many translation files organized in YAML files. For example:

    every_month: Kas mėnesį
    bank_acc_nr: A/s
    'Internal Server Error': 'Vidinė serverio klaida'
    next_lock: 'Kitas užrakinimas'
    two_days_later_00:00: Two days later 00:00
    same_day_00:00: 'Tą pačia dieną 00:00'
    'series %number%': 'Serija: Nr. %number%'
    not_allowed_to_edit_records_before_reset_date: 'Neleidžiama kurti įrašų anksčiau archyvo datos: %date%'
```

<p>After upgrade, my framework requires that I add quotes to all translation messages. To do it by the hands will be a very long and complex task. I've tried to write next regex for this <code>(.*?):[\s]{0,2}([^'"]{0,1}[\%]?[\w\d]+[\%]?[\/,\-\.\(\)\%\_\h\p{L}]+)</code>, and it has a little bug, it also matches lines like these:</p>

<pre class="lang-yaml prettyprint-override"><code>    'series %number%': 'Serija: Nr. %number%'
    not_allowed_to_edit_records_before_reset_date: 'Neleidžiama kurti įrašų anksčiau archyvo datos: %date%'
</code>```

but I want only to match lines without quotes:

    every_month: Kas mėnesį
    bank_acc_nr: A/s
    two_days_later_00:00: Two days later 00:00
```

Here is an online regex editor where I tried to implement that https://regex101.com/r/t5hRAk/2

答:
You could add matching a : and digits \d to the last character class and  match 1-2 whitespace chars after the colon and use anchors ^ and $

```<code>^(.*?):\s{1,2}(%?\w+%?[\/,.()_\h\p{L}:\d-]+)$
</code>```

Regex demo

About the pattern you tried

[\%]? can be written as %?

\w also matches \d, so this [\w\d]+ can be written as \w+

If the value should be between % or neither you could write %?\w+%? as (?:%\w+%|\w+)

It depends on the delimiters, but you don't have to escape the \/

If you want to match any char except " or ' before the first optional %:

```<code>^(.*?):\s{1,2}([^'"]?%?\w+%?[\/,.()_\h\p{L}:\d-]+)$
</code>```

Regex demo

Title: Regex for parse YAML

Body:
I have many translation files organized in YAML files. For example:

    every_month: Kas mėnesį
    bank_acc_nr: A/s
    'Internal Server Error': 'Vidinė serverio klaida'
    next_lock: 'Kitas užrakinimas'
    two_days_later_00:00: Two days later 00:00
    same_day_00:00: 'Tą pačia dieną 00:00'
    'series %number%': 'Serija: Nr. %number%'
    not_allowed_to_edit_records_before_reset_date: 'Neleidžiama kurti įrašų anksčiau archyvo datos: %date%'

After upgrade, my framework requires that I add quotes to all translation messages. To do it by the hands will be a very long and complex task. I've tried to write next regex for this (.*?):[\s]{0,2}([^'"]{0,1}[\%]?[\w\d]+[\%]?[\/,\-\.\(\)\%\_\h\p{L}]+), and it has a little bug, it also matches lines like these:

    'series %number%': 'Serija: Nr. %number%'
    not_allowed_to_edit_records_before_reset_date: 'Neleidžiama kurti įrašų anksčiau archyvo datos: %date%'

but I want only to match lines without quotes:

    every_month: Kas mėnesį
    bank_acc_nr: A/s
    two_days_later_00:00: Two days later 00:00

Here is an online regex editor where I tried to implement that https://regex101.com/r/t5hRAk/2

Body:
You could add matching a : and digits \d to the last character class and  match 1-2 whitespace chars after the colon and use anchors ^ and $

^(.*?):\s{1,2}(%?\w+%?[\/,.()_\h\p{L}:\d-]+)$

Regex demo

About the pattern you tried

[\%]? can be written as %?

\w also matches \d, so this [\w\d]+ can be written as \w+

If the value should be between % or neither you could write %?\w+%? as (?:%\w+%|\w+)

It depends on the delimiters, but you don't have to escape the \/

If you want to match any char except " or ' before the first optional %:

^(.*?):\s{1,2}([^'"]?%?\w+%?[\/,.()_\h\p{L}:\d-]+)$

Regex demo


问:
Add one fore each identical index
```<code>l = ['a','b','c','a','a','c']
l1 = ['a1','b','c1','a2','a3','c2']
</code>```

I've a list that looks like this, and if there is more then one index that are identical I want to add one so that the list looks like l1 but I can´t figure out how

答:
Try this:

```<code>l = ['a','b','c','a','a','c']
counts = {v:list(range(1, l.count(v)+1)) for v in l}
l1 = [x if counts[x] == [1] else '%s%s' % (x, counts[x].pop(0)) for x in l]
print(l1)
</code>```

Output:

```<code>['a1', 'b', 'c1', 'a2', 'a3', 'c2']
</code>```

Title: Add one fore each identical index

Body:
l = ['a','b','c','a','a','c']
l1 = ['a1','b','c1','a2','a3','c2']

I've a list that looks like this, and if there is more then one index that are identical I want to add one so that the list looks like l1 but I can´t figure out how

Body:
Try this:

l = ['a','b','c','a','a','c']
counts = {v:list(range(1, l.count(v)+1)) for v in l}
l1 = [x if counts[x] == [1] else '%s%s' % (x, counts[x].pop(0)) for x in l]
print(l1)

Output:

['a1', 'b', 'c1', 'a2', 'a3', 'c2']


问:
What cache coherence solution do modern x86 CPUs use?
I am somewhat confused with what  how cache coherence systems function in modern multi core CPU. I have seen that snooping based protocols like MESIF/MOESI snooping based protocols have been used in Intel and AMD processors, on the other hand directory based protocols seem to be a lot more efficient with multiple core as they don't broadcast but send messages to specific nodes.

What is the modern cache coherence solution in AMD or Intel processors, is it snooping based protocols like MOESI and MESIF, or is it only directory based protocols, or is it a combination of both (snooping based protocols for communication between elements inside the same node, and directory based for node to node communications)?

答:
MESI is defined in terms of snooping a shared bus, but no, modern CPUs don't actually work that way.  MESI states for each cache line can be tracked / updated with messages and a snoop filter (basically a directory) to avoid broadcasting those messages, which is what Intel (MESIF) and AMD (MOESI) actually do.

e.g. the shared inclusive L3 cache in Intel CPUs (before Skylake server) lets L3 tags act as a snoop filter; as well as tracking the MESI state, they also record which core # (if any) has a private copy of a line.  Which cache mapping technique is used in intel core i7 processor?

For example, a Sandybridge-family CPU with a ring bus (modern client chips, server chips up to Broadwell).  Core #0 reads a line.  That line is in Modified state on core #1.

read misses in L1d and L2 cache on core #0, resulting in is sending a request on the ring bus to the L3 slice that contains that line (indexing via a hash function on some physical address bits)

That slice of L3 gets the message, checks its tags.  If it found tag = Shared at this point, the response could go back over the bidirectional ring bus with the data.

Otherwise, L3 tags tell it that core #1 has exclusive ownership of a line:  Exclusive, may have been promoted to Modified = dirty.

L3 cache logic in that slice of L3 will generate a message to ask core #1 to write back that line.

The message arrives at the ring bus stop for core #1, and gets its L2 or L1d to write back that line.

IDK if one ring bus message can be read directly by Core #0 as well as the relevant slice of L3 cache, or if the message might have to go all the way to the L3 slice and then to core #0 from there.  (Worst case distance = basically all the way around the ring, instead of half, for a bidirectional ring.)

This is super hand-wavy; do not take my word for it on the exact details, but the general concept of sending messages like share-request, RFO, or write-back, is the right mental model.  BeeOnRope has an answer that with a similar breakdown into steps that covers uops and the store buffer, as well as MESI / RFO.

In a similar case, core #1 could have silently dropped the line without having modified it, if it had only gotten Exclusive ownership but never written it.  (Loads that miss in cache default to loading into Exclusive state so a separate store won't have to do an RFO for the same line).  In that case I assume it the core that doesn't have the line after all has to send a message back to indicate that.  Or maybe it sends a message directly to one of the memory controllers that are also on the ring bus, instead of a round trip back to the L3 slice to force it to do that.

Obviously stuff like this can be happening in parallel for every core.  (And each core can have multiple outstanding requests it's waiting for: memory level parallelism within a single core.  On Intel, L2 superqueue has 16 entries on some microarchitectures, while there are 10 or 12 L1 LFBs.)

Quad-socket and higher systems have snoop filters between sockets; dual-socket Intel systems with E5-xxxx CPUs of Broadwell and earlier did just spam snoops to each other over the QPI links.  (Unless you used a quad-socket-capable CPU (E7-xxxx) in a dual-socket system).  Multi-socket is hard because missing in local L3 doesn't necessarily mean it's time to hit DRAM; the / an other socket might have the line modified.

Also related:

https://www.realworldtech.com/sandy-bridge/ Kanter's SnB write-up covers some about Intel's ring bus design, IIRC, although it's mostly about the internals of each core.  The shared inclusive L3 was new in Nehalem (when Intel started using the "core i7" brand name), https://www.realworldtech.com/nehalem/

Why is Skylake so much better than Broadwell-E for single-threaded memory throughput? - more hops on the ring bus for Intel CPUs with more cores hurts L3 and DRAM latency and therefore bandwidth = max-concurrency / latency.

What is the benefit of the MOESI cache coherency protocol over MESI? some more links.


问:
How to convert JSON string into integer in python?
How can I convert year and isbn into integers from this json?</p>

```<code>({
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
})
</code>```

答:
Read this article, it is about json and Python!

This will work:

```<code>import json

json_data =  '''{
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
}'''

python_data = json.loads(json_data)

year = int(python_data["year"])
isbn  = int(python_data["isbn"])
print(year, isbn)
</code>```

json_data is a string containing the data in json format. Then, with json.loads() is converted into a Python dictionary. Finally, year and isbn are being converted from string to integer.

Body:
How can I convert year and isbn into integers from this json?

({
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
})

Body:
Read this article, it is about json and Python!

This will work:

import json

json_data =  '''{
    "title": "The Notebook",
    "author": "Nicholas Sparks",
    "year": "1996",
    "isbn": "0553816713"
}'''

python_data = json.loads(json_data)

year = int(python_data["year"])
isbn  = int(python_data["isbn"])
print(year, isbn)

json_data is a string containing the data in json format. Then, with json.loads() is converted into a Python dictionary. Finally, year and isbn are being converted from string to integer.


问:
Making all form inputs to be in readonly mode while clicking submit button
I have a form when the submit button is clicked form's all inputs needs to be in read-only mode and hide submit button and also displays submitting text. For this I coded:

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text

    $("#testform :input").prop('readonly', true); //Making all inputs to readonly

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}</code>```

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1

Question?

      <input type="hidden" name="qid1" value="22">

        <input type="radio" name="radio1" id="checka1" value="A">

A

        <input type="radio" name="radio1" id="checkb1" value="B">

B

        <input type="radio" name="radio1" id="checkc1" value="C">

C

        <input type="radio" name="radio1" id="checkd1" value="D">

D

        <input type="radio" name="radio1" id="checke1" value="E">

None of the above

  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  Submitting please do not refresh!
</form>```

When I click the submit button it hides the submit button and shows submitting text. But it doesn't change the input property to read-only mode.

答:
For radio button use disabled property:

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text

    $("#testform :input").prop('disabled', true); //Making all inputs to disabled

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}</code>```

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1

Question?

      <input type="hidden" name="qid1" value="22">

        <input type="radio" name="radio1" id="checka1" value="A">

A

        <input type="radio" name="radio1" id="checkb1" value="B">

B

        <input type="radio" name="radio1" id="checkc1" value="C">

C

        <input type="radio" name="radio1" id="checkd1" value="D">

D

        <input type="radio" name="radio1" id="checke1" value="E">

None of the above

  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  Submitting please do not refresh!
</form>```
</div>
</div>
</p>

<p>If you want send the selected value to the server then probably you can set the <code>pointer-events</code> to <code>none</code> which will indicate that the element is not the target of pointer events:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text
    $("#testform :input").css({'pointer-events':'none', 'opacity':'.5'});
    $('.option_div p').css({'opacity':'.5'});
    $('.option_div p').click(false);
    console.log($("form").serialize());
  });
});</code>```

.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}```
<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>
<iframe name="hiddenFrame" class="hiddenFramehideclass"></iframe>

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1
  <div class="question_container">
    <div class="question_div">
      <p>Question?</p>
      <input type="hidden" name="qid1" value="22">
      <div class="option_div">
        <input type="radio" name="radio1" id="checka1" value="A">
        <label for="checka1">
          <p>A</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkb1" value="B">
        <label for="checkb1">
          <p>B</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkc1" value="C">
        <label for="checkc1">
          <p>C</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkd1" value="D">
        <label for="checkd1">
          <p>D</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checke1" value="E">
        <label for="checke1">
          <p>None of the above</p>
        </label>
      </div>
    </div>
  </div>
  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  <span id="submit_text">Submitting please <b>do not</b> refresh!</span>
</form></code>```

Body:
I have a form when the submit button is clicked form's all inputs needs to be in read-only mode and hide submit button and also displays submitting text. For this I coded:

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text

    $("#testform :input").prop('readonly', true); //Making all inputs to readonly

  });
});

.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1

Question?

      <input type="hidden" name="qid1" value="22">

        <input type="radio" name="radio1" id="checka1" value="A">

A

        <input type="radio" name="radio1" id="checkb1" value="B">

B

        <input type="radio" name="radio1" id="checkc1" value="C">

C

        <input type="radio" name="radio1" id="checkd1" value="D">

D

        <input type="radio" name="radio1" id="checke1" value="E">

None of the above

  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  Submitting please do not refresh!
</form>

When I click the submit button it hides the submit button and shows submitting text. But it doesn't change the input property to read-only mode.

Body:
For radio button use disabled property:

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text

    $("#testform :input").prop('disabled', true); //Making all inputs to disabled

  });
});

.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe name="hiddenFrame" class="hiddenFramehideclass"></iframe>

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1
  <div class="question_container">
    <div class="question_div">
      <p>Question?</p>
      <input type="hidden" name="qid1" value="22">
      <div class="option_div">
        <input type="radio" name="radio1" id="checka1" value="A">
        <label for="checka1">
          <p>A</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkb1" value="B">
        <label for="checkb1">
          <p>B</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkc1" value="C">
        <label for="checkc1">
          <p>C</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkd1" value="D">
        <label for="checkd1">
          <p>D</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checke1" value="E">
        <label for="checke1">
          <p>None of the above</p>
        </label>
      </div>
    </div>
  </div>
  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  <span id="submit_text">Submitting please <b>do not</b> refresh!</span>
</form>

If you want send the selected value to the server then probably you can set the pointer-events to none which will indicate that the element is not the target of pointer events:

$(document).ready(function() {
  $("#submit_text").hide(); //Hiding submit_text
  $("#testsubmitbutton").click(function() {
    $("#testsubmitbutton").hide(); //Hiding submit button
    $("#submit_text").show(); //Showing submit_text
    $("#testform :input").css({'pointer-events':'none', 'opacity':'.5'});
    $('.option_div p').css({'opacity':'.5'});
    $('.option_div p').click(false);
    console.log($("form").serialize());
  });
});

.hiddenFramehideclass {
  position: absolute;
  top: -1px;
  left: -1px;
  width: 1px;
  height: 1px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe name="hiddenFrame" class="hiddenFramehideclass"></iframe>

<form method="post" action="" enctype="multipart/form-data" id="testform" target="hiddenFrame">

  Question 1
  <div class="question_container">
    <div class="question_div">
      <p>Question?</p>
      <input type="hidden" name="qid1" value="22">
      <div class="option_div">
        <input type="radio" name="radio1" id="checka1" value="A">
        <label for="checka1">
          <p>A</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkb1" value="B">
        <label for="checkb1">
          <p>B</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkc1" value="C">
        <label for="checkc1">
          <p>C</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checkd1" value="D">
        <label for="checkd1">
          <p>D</p>
        </label>
      </div>
      <div class="option_div">
        <input type="radio" name="radio1" id="checke1" value="E">
        <label for="checke1">
          <p>None of the above</p>
        </label>
      </div>
    </div>
  </div>
  <button class="" type="submit" name="testsubmitbutton" id="testsubmitbutton">Submit</button>
  <span id="submit_text">Submitting please <b>do not</b> refresh!</span>
</form>


问:
C++ for loop too slow
I'm trying to make an audio application with PortAudio. My callback function has been very slow and it has been creating constant underruns. I removed everything in the callback one by one until I found the issue: the for loop. I removed everything so that the only thing happening in the callback function is the for loop and it is still causing underruns. I know it is the for loop because when I reduce the number of iterations, the underruns go away.

```<code>static int patestCallback(const void *inputBuffer, void *outputBuffer,
                      unsigned long framesPerBuffer,
                      const PaStreamCallbackTimeInfo *timeInfo,
                      PaStreamCallbackFlags statusFlags, void *userData)
{
    int x = 0;
    for (int jj = 0; jj < 10000; jj++)
    {
        x++; // for testing, not actually used
    };
    return paContinue;
}
</code>```

Here is my full code for testing: https://gist.github.com/johnroper100/b87641f5609dbb49bc3c1121b1f4daf1

Not really necessary for this question, but I did the same callback in the python equivalent (sounddevice) and there are no issues.

答: Aside from API-specific questions that may cause your loops or overall program to slow down, I'll give a general advise to your general question. Always favor prefix (++i;) over postfix (i++;) increment if you'll ignore the returning value, because the prefix doesn't return the copy of the value/object you're applying the operator on. Hence, you can avoid an unnecessary copy operation. Although, most of the modern compilers do replace this for you on the fly, but they may be tricked with your code somehow, so it's always best to make it a habit to use prefix increment. And of course you need to compile your code with the -O3 parameter for the highest performance and make sure the compiler will do its best. Another option to consider for optimizing loops further is multi-threading.

Title: C++ for loop too slow

Body:
I'm trying to make an audio application with PortAudio. My callback function has been very slow and it has been creating constant underruns. I removed everything in the callback one by one until I found the issue: the for loop. I removed everything so that the only thing happening in the callback function is the for loop and it is still causing underruns. I know it is the for loop because when I reduce the number of iterations, the underruns go away.

static int patestCallback(const void *inputBuffer, void *outputBuffer,
                      unsigned long framesPerBuffer,
                      const PaStreamCallbackTimeInfo *timeInfo,
                      PaStreamCallbackFlags statusFlags, void *userData)
{
    int x = 0;
    for (int jj = 0; jj < 10000; jj++)
    {
        x++; // for testing, not actually used
    };
    return paContinue;
}

Here is my full code for testing: https://gist.github.com/johnroper100/b87641f5609dbb49bc3c1121b1f4daf1

Not really necessary for this question, but I did the same callback in the python equivalent (sounddevice) and there are no issues.