问:
How to pass data as parameter in react-table?
How to pass data values as a parameter in React Table version 7.

I was trying to pass status and id in butFunction inside of react table so that i can create a function which create a button opposite of the status .

here is code what i had tried to do so.

Demo Link of the same code

```<code>
const data = [
  { firstName: "Jane", lastName: "Doe", status: "OPEN" , id: "1" },
  { firstName: "John", lastName: "Smith", status: "CLOSE"  , id: "2" },
  { firstName: "John", lastName: "Walker", status: "OPEN" , id: "3" }
];

const columns = [
      {
        Header: "First Name",
        accessor: "firstName"
      },
      {
        Header: "Last Name",
        accessor: "lastName"
      },
      {
        Header: "Status",
        accessor: "status"
      }
];

const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  });

    const butFunction = (level , id) => {
      console.log(level)
      console.log(id)
    if (level === "OPEN") {
      return <button > CLOSE </button>;
    } else {
      return <button > OPEN </button>;
    }
  };

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()}>{column.render("Header")}</th>
            ))}
            <th>Action</th>
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => {
                return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
              <td>{butFunction(data.status, data.id)}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};

export default function App() {
  return (
    <div className="App">
      <Table columns={columns} data={data} />
    </div>
  );
}
</code>```

答:
You need to access row.values to access the data for each row. Inside the map function, row.values will be an object that contains the data for the current row.

Edit:

As per your comment, row.values object doesn't contains id property of your data objects. To access the id, use row.original.id

```<code><td>{ butFunction(row.values.status, row.original.id) }</td>
</code>```

Body:
How to pass data values as a parameter in React Table version 7.

I was trying to pass status and id in butFunction inside of react table so that i can create a function which create a button opposite of the status .

here is code what i had tried to do so.

Demo Link of the same code

const data = [
  { firstName: "Jane", lastName: "Doe", status: "OPEN" , id: "1" },
  { firstName: "John", lastName: "Smith", status: "CLOSE"  , id: "2" },
  { firstName: "John", lastName: "Walker", status: "OPEN" , id: "3" }
];

const columns = [
      {
        Header: "First Name",
        accessor: "firstName"
      },
      {
        Header: "Last Name",
        accessor: "lastName"
      },
      {
        Header: "Status",
        accessor: "status"
      }
];

const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  });

    const butFunction = (level , id) => {
      console.log(level)
      console.log(id)
    if (level === "OPEN") {
      return <button > CLOSE </button>;
    } else {
      return <button > OPEN </button>;
    }
  };

  return (

        {headerGroups.map(headerGroup => (

            {headerGroup.headers.map(column => (
              {column.render("Header")}
            ))}
            Action

        ))}

        {rows.map((row, i) => {
          prepareRow(row);
          return (

              {row.cells.map(cell => {
                return {cell.render("Cell")}	;
              })}
              {butFunction(data.status, data.id)}

          );
        })}

  );
};

export default function App() {
  return (

  );
}

Body:
You need to access row.values to access the data for each row. Inside the map function, row.values will be an object that contains the data for the current row.

Edit:

As per your comment, row.values object doesn't contains id property of your data objects. To access the id, use row.original.id

<td>{ butFunction(row.values.status, row.original.id) }</td>


来源: stackexchange

问:
Can't collapse/uncollapse Material Tree (Angular 6)
I'm trying to set up Material Tree in my app. This was rather complicated compared to mat-table f.ex., but I've managed to to fetch data and show this. However, I'm just able to show all names, rather than expanding/collapsing the children of them. I get the error

```<code>cannot read property treeControl of undefined
</code>```

when clicking on the items. I tried a suggestion from another SO-post, then I get an additional error of

```<code>cannot read property length of undefined
</code>```

How can I resolve this? Here is the code I have now:

overview.component.html

```<code><mat-tree [dataSource]="nestedDataSource" [treeControl]="nestedTreeControl" class="example-tree">
  <mat-tree-node *matTreeNodeDef="let node">
    <li class="mat-tree-node">
      <button mat-icon-button disabled></button>
      {{ node.name }}
    </li>
  </mat-tree-node>

  <mat-nested-tree-node *matTreeNodeDef="let node; when: hasNestedChild">
    <li>
      <div class="mat-tree-node">
        <button mat-icon-button matTreeNodeToggle [attr.aria-label]="'toggle ' + node.name">
          <mat-icon class="mat-icon-rtl-mirror">
            {{nestedTreeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
          </mat-icon>
        </button>
        {{node.name}}
      </div>
      <ul [class.example-tree-invisible]="!nestedTreeControl.isExpanded(node)">
        <ng-container matTreeNodeOutlet></ng-container>
      </ul>
    </li>
  </mat-nested-tree-node>
</mat-tree>
</code>```

overview.component.scss

```<code>example-tree-invisible {display: none;}

.example-tree ul,
.example-tree li {
    margin-top: 0;
    margin-bottom: 0;
    list-style-type: none;
}
</code>```

overview.module.ts

```<code>    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { OverviewComponent } from './overview.component';
    import { MatTreeModule,
      MatIconModule,
      MatButtonModule } from '@angular/material';

    @NgModule({
      imports: [
        CommonModule,
        MatTreeModule,
        MatIconModule,
        MatButtonModule
      ],
      declarations: [OverviewComponent]
    })
    export class OverviewModule { }
</code>```

overview.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatTreeNestedDataSource } from '@angular/material';
import { NestedTreeControl } from '@angular/cdk/tree';
import { of as observableOf } from 'rxjs';

export class Group {
  name: string;
}
export class MasterGroup extends Group {
  childGroups: Array<Group>;
}

@Component({
  selector: 'app-overview',
  templateUrl: './overview.component.html',
  styleUrls: ['./overview.component.scss']
})
export class OverviewComponent implements OnInit {
  nestedTreeControl: NestedTreeControl<Group>;
  nestedDataSource: MatTreeNestedDataSource<MasterGroup>;

  constructor(private http: HttpClient) {
    this.nestedTreeControl = new NestedTreeControl<Group>(this._getChildren);
    this.nestedDataSource = new MatTreeNestedDataSource();

    this.getGroups();
   }

  ngOnInit() {
  }

  private _getChildren = (node: MasterGroup) => {
     return observableOf(node.childGroups);
  }

   getGroups() {
    const data = [
    {
      name: 'test',
      childGroups: [
        {
          name: 'inner test'
        },
        {
          name: 'inner test 2'
        }
      ]
    },
    {
      name: 'test 2',
      childGroups: [
        {
          name: 'another test'
        }
      ]
    },
    {
      name: 'test 3',
      childGroups: []
    }
  ];

    this.nestedDataSource.data = data;
   }

  hasNestedChild = (_: number, nodeData: MasterGroup) => {
    /*if (nodeData.childGroups) {
      // I get an error using .length here - without it shows all groups
      // When clicking item it gives error 'cannt read property treeControl of undefined'
      return true;
    } else {
      return false;
    } */

    // tried this line from another SO-post, I then get both errors at same time
    return nodeData.childGroups.length;
  }
}
</code>```

答: Seems the matTreeNodeToggle works stable only on mat-tree-node or mat-nested-tree-node tag level. For toggling from level below of these tags use (click)="nestedTreeControl.toggle(node)"

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to set up Material Tree in my app. This was rather complicated compared to mat-table f.ex., but I've managed to to fetch data and show this. However, I'm just able to show all names, rather than expanding/collapsing the children of them. I get the error

cannot read property treeControl of undefined

when clicking on the items. I tried a suggestion from another SO-post, then I get an additional error of

cannot read property length of undefined

How can I resolve this? Here is the code I have now:

overview.component.html

<mat-tree [dataSource]="nestedDataSource" [treeControl]="nestedTreeControl" class="example-tree">
  <mat-tree-node *matTreeNodeDef="let node">

      <button mat-icon-button disabled></button>
      {{ node.name }}

  </mat-tree-node>

  <mat-nested-tree-node *matTreeNodeDef="let node; when: hasNestedChild">

        <button mat-icon-button matTreeNodeToggle [attr.aria-label]="'toggle ' + node.name">
          <mat-icon class="mat-icon-rtl-mirror">
            {{nestedTreeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
          </mat-icon>
        </button>
        {{node.name}}

        <ng-container matTreeNodeOutlet></ng-container>

  </mat-nested-tree-node>
</mat-tree>

overview.component.scss

example-tree-invisible {display: none;}

.example-tree ul,
.example-tree li {
    margin-top: 0;
    margin-bottom: 0;
    list-style-type: none;
}

overview.module.ts

    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { OverviewComponent } from './overview.component';
    import { MatTreeModule,
      MatIconModule,
      MatButtonModule } from '@angular/material';

    @NgModule({
      imports: [
        CommonModule,
        MatTreeModule,
        MatIconModule,
        MatButtonModule
      ],
      declarations: [OverviewComponent]
    })
    export class OverviewModule { }

overview.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatTreeNestedDataSource } from '@angular/material';
import { NestedTreeControl } from '@angular/cdk/tree';
import { of as observableOf } from 'rxjs';

export class Group {
  name: string;
}
export class MasterGroup extends Group {
  childGroups: Array<Group>;
}

@Component({
  selector: 'app-overview',
  templateUrl: './overview.component.html',
  styleUrls: ['./overview.component.scss']
})
export class OverviewComponent implements OnInit {
  nestedTreeControl: NestedTreeControl<Group>;
  nestedDataSource: MatTreeNestedDataSource<MasterGroup>;

  constructor(private http: HttpClient) {
    this.nestedTreeControl = new NestedTreeControl<Group>(this._getChildren);
    this.nestedDataSource = new MatTreeNestedDataSource();

    this.getGroups();
   }

  ngOnInit() {
  }

  private _getChildren = (node: MasterGroup) => {
     return observableOf(node.childGroups);
  }

   getGroups() {
    const data = [
    {
      name: 'test',
      childGroups: [
        {
          name: 'inner test'
        },
        {
          name: 'inner test 2'
        }
      ]
    },
    {
      name: 'test 2',
      childGroups: [
        {
          name: 'another test'
        }
      ]
    },
    {
      name: 'test 3',
      childGroups: []
    }
  ];

    this.nestedDataSource.data = data;
   }

  hasNestedChild = (_: number, nodeData: MasterGroup) => {
    /*if (nodeData.childGroups) {
      // I get an error using .length here - without it shows all groups
      // When clicking item it gives error 'cannt read property treeControl of undefined'
      return true;
    } else {
      return false;
    } */

    // tried this line from another SO-post, I then get both errors at same time
    return nodeData.childGroups.length;
  }
}


问:
Can we detect browsers refresh and back button events?
Anybody know how to detect browsers refresh and back button events in firefox using jquery or javascript.</p>

答:
You can use the following events:

window.onpopstate for back button press.

```<code>window.onpopstate = (e) => {
  // your logic goes here
};
</code>```

window.onbeforeunload for refresh or tab close.

```<code>window.onbeforeunload = (e) => {
  // your logic here
  e.preventDefault();
  e.returnValue = 'There are unsaved changes. Sure you want to leave?';
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use the following events:

window.onpopstate for back button press.

window.onpopstate = (e) => {
  // your logic goes here
};

window.onbeforeunload for refresh or tab close.

window.onbeforeunload = (e) => {
  // your logic here
  e.preventDefault();
  e.returnValue = 'There are unsaved changes. Sure you want to leave?';
};


问:
After pushing values into an array, array becomes a series of values having only one index
I pushed values after fetching an api as below into an array.
After the pushing is done, the array suddenly becomes an array [], and became un-interable.

What did I do wrong and how can I make this array iterable that I could extract value by its inde x number like array[0]?

I used asynchronous function / Promises, to achieve this.

```<code>async function scrapingId(targetArtist){
    let APIRequest=await fetch(`https://api.songkick.com/api/3.0/search/artists.json?apikey=${myAPIkey}&query=${targetArtist}`)
                   .then(data=>{return data.json()});
    // console.log(APIRequest.resultsPage.results.artist[0].id);

    artistIds.push(APIRequest.resultsPage.results.artist[0].id);

    // console.log(artistIds)
}
</code>```

Below is where the async function is executed.

```<code>.then((data)=>{

for (entity of data){
scrapingId(entity.artist);
};

return artistIds

}).then((data)=>{console.log(data)

})
</code>```

The console.log(data) above spits out an array-like thing but I don't think that's a proper array which is iterable by its index number.

The output seems like an array but having 'key's which is index number of each entity.

Thank you inadvance.
Fullcode is attached here
https://codepen.io/jotnajoa/pen/wvMwOxz?editors=1111

答:
You are returning artistIds before your scrapingId(entity.artist) is fetched, so in next then you get an empty array

you should return promise not an array of values

```<code>.then((data) => {
  const scrappingCalls = []
  for (const entity of data){
    scrappingCalls.push(scrapingId(entity.artist))
  }
  return Promise.all(scrappingCalls)
})
.then((data)=>{console.log(data)})
</code>```

or even shorter it can be written

```<code>.then(data => Promise.all(data.map(({ artist }) => scrapingId(artist))))
.then(data => console.log(data))
</code>```

UPDATE:
also change your function that it would return id

```<code>async function scrapingId(targetArtist){
  let APIRequest = await fetch(`https://api.songkick.com/api/3.0/search/artists.json?apikey=${myAPIkey}&query=${targetArtist}`)
    .then(data => data.json())

  const id = APIRequest.resultsPage.results.artist[0].id
  return id
}
</code>```

Body:
I pushed values after fetching an api as below into an array.
After the pushing is done, the array suddenly becomes an array [], and became un-interable.

What did I do wrong and how can I make this array iterable that I could extract value by its inde x number like array[0]?

I used asynchronous function / Promises, to achieve this.

async function scrapingId(targetArtist){
    let APIRequest=await fetch(`https://api.songkick.com/api/3.0/search/artists.json?apikey=${myAPIkey}&query=${targetArtist}`)
                   .then(data=>{return data.json()});
    // console.log(APIRequest.resultsPage.results.artist[0].id);

    artistIds.push(APIRequest.resultsPage.results.artist[0].id);

    // console.log(artistIds)
}

Below is where the async function is executed.

.then((data)=>{

for (entity of data){
scrapingId(entity.artist);
};

return artistIds

}).then((data)=>{console.log(data)

})

The console.log(data) above spits out an array-like thing but I don't think that's a proper array which is iterable by its index number.

The output seems like an array but having 'key's which is index number of each entity.

Thank you inadvance.
Fullcode is attached here
https://codepen.io/jotnajoa/pen/wvMwOxz?editors=1111

Body:
You are returning artistIds before your scrapingId(entity.artist) is fetched, so in next then you get an empty array

you should return promise not an array of values

.then((data) => {
  const scrappingCalls = []
  for (const entity of data){
    scrappingCalls.push(scrapingId(entity.artist))
  }
  return Promise.all(scrappingCalls)
})
.then((data)=>{console.log(data)})

or even shorter it can be written

.then(data => Promise.all(data.map(({ artist }) => scrapingId(artist))))
.then(data => console.log(data))

UPDATE:
also change your function that it would return id

async function scrapingId(targetArtist){
  let APIRequest = await fetch(`https://api.songkick.com/api/3.0/search/artists.json?apikey=${myAPIkey}&query=${targetArtist}`)
    .then(data => data.json())

  const id = APIRequest.resultsPage.results.artist[0].id
  return id
}


问:
jQuery hover effect
I am new to jQuery and trying to figure out how to use the .hover(); effect in place of the .mouseover() and .mouseout() effects. Here is the scenerio:

I am using a table and want to highlight the row with a CSS class that changes the background color to a light yellow. Here is the CSS:

```<code>.bgHvr {
  background-color: #FFFACD;
}
</code>```

The only way I know how to add the hover effect I desire is:

```<code>jQuery(document).ready(function($) {
  $('#table tbody tr').mouseover(function() {
    $(this).addClass('bgHvr');
  });
  $('#table tbody tr').mouseout(function() {
    $(this).removeClass('bgHvr');
  });
});
</code>```

UPDATE:

After some more help I found out a simpler way of a hover effect:

```<code>$('#table tbody tr').hover(function() {
  $(this).toggleClass('bgHvr');
});
</code>```

This is possible after the 1.4.2 update to jQuery which changed how the .toggle() effect worked.

答:
Um...How about just using CSS?

```<code>#table tbody tr:hover {
    background-colour: #FFFACD;
}
</code>```

EDIT: With DEMO

Title: jQuery hover effect

Body:
I am new to jQuery and trying to figure out how to use the .hover(); effect in place of the .mouseover() and .mouseout() effects. Here is the scenerio:

I am using a table and want to highlight the row with a CSS class that changes the background color to a light yellow. Here is the CSS:

.bgHvr {
  background-color: #FFFACD;
}

The only way I know how to add the hover effect I desire is:

jQuery(document).ready(function($) {
  $('#table tbody tr').mouseover(function() {
    $(this).addClass('bgHvr');
  });
  $('#table tbody tr').mouseout(function() {
    $(this).removeClass('bgHvr');
  });
});

UPDATE:

After some more help I found out a simpler way of a hover effect:

$('#table tbody tr').hover(function() {
  $(this).toggleClass('bgHvr');
});

This is possible after the 1.4.2 update to jQuery which changed how the .toggle() effect worked.

Body:
Um...How about just using CSS?

#table tbody tr:hover {
    background-colour: #FFFACD;
}

EDIT: With DEMO


问:
Generate 3x3 puzzles with the same difficulty?
I want to generate several 3x3 puzzles (https://datawookie.netlify.app/blog/2019/04/sliding-puzzle-solvable/) with the same difficulty where difficulty is defined as the minimum necessary moves to reach the solution. For example, in a puzzle [1,2,3,4,5,6,7,0,8], the minimum necessary move is 1 because we can reach the solution by moving 8 up.

The above site has a python code to determine solvability, and I modified it a little bit so that it gives me the number of inversions:

```<code>def solvable(tiles):
    count = 0
    for i in range(8):
        for j in range(i+1, 9):
            if tiles[j] and tiles[i] and tiles[i] > tiles[j]:
                count += 1
    return [count, count % 2 == 0]
</code>```

But the number of inversions is not the minimum necessary moves. How could I modify the code so that it also returns the minimum necessary moves? And, is there any way to automatically generate puzzles with the same minimum necessary moves?

答:
The "difficulty" of a puzzle can be estimated by different metrics (e.g. number of inversions, initial configuration, size, etc.). Some are meaningful, some are not. That's up to you to try different ones and decide whether they are good "difficulty" estimators. But keep in mind that sometimes, what you call "difficulty" is subjective.

Find those metrics and try to evaluate your puzzles with them.

Body:
I want to generate several 3x3 puzzles (https://datawookie.netlify.app/blog/2019/04/sliding-puzzle-solvable/) with the same difficulty where difficulty is defined as the minimum necessary moves to reach the solution. For example, in a puzzle [1,2,3,4,5,6,7,0,8], the minimum necessary move is 1 because we can reach the solution by moving 8 up.

The above site has a python code to determine solvability, and I modified it a little bit so that it gives me the number of inversions:

def solvable(tiles):
    count = 0
    for i in range(8):
        for j in range(i+1, 9):
            if tiles[j] and tiles[i] and tiles[i] > tiles[j]:
                count += 1
    return [count, count % 2 == 0]

But the number of inversions is not the minimum necessary moves. How could I modify the code so that it also returns the minimum necessary moves? And, is there any way to automatically generate puzzles with the same minimum necessary moves?


问:
Don't show anything when there is no content
I have the following code inside the search results page and I want it not to show it when there is no content in any part.</p>

```<code>            if ( have_posts() ) {
                $types = array('singer', 'music', 'album');
                foreach( $types as $type ){
                    if( $type == 'singer'){
                        echo ' <h1>Singers</h1> ';
                    } elseif ( $type == 'music'){
                        echo '<h1>Musics</h1>';
                    }
                    elseif ( $type == 'album'){
                        echo '<h1>Albums</h1>';
                    }
                    while( have_posts() ){
                        the_post();
                        if( $type == get_post_type() ){
                            the_post_thumbnail('medium'); ?>
                            <h3><a href="<?php echo get_permalink(); ?>">
                            <?php the_title();  ?>
                            </a></h3>
                            <?php
                        }
                    }
                rewind_posts();
                }
            } else {
                echo us_translate( 'No results found.' );
            }
</code>```

答:
This is not a good solution, but should work)</p>

```<code>$types = array(
    'singer' => array( 'title' => 'Singers', 'content' => '' ),
    'music'  => array( 'title' => 'Musics', 'content' => '' ),
    'album'  => array( 'title' => 'Albums', 'content' => '' ),
);

if ( have_posts() ) {

    while( have_posts() ) {
        the_post();
        $type = get_post_type();
        if ( array_key_exists( $type, $types ) ) {
            $types[ $type ][ 'content' ] .= get_the_post_thumbnail( null, 'medium' );
            $types[ $type ][ 'content' ] .= '<h3><a href="' . get_the_permalink() . '">' . get_the_title() . '</h3>';
        }
    }

    foreach( $types as $k => $v ) {
        if ( $v[ 'content' ] ) {
            echo '<h1>' . $v[ 'title' ]. '</h1>' . $v[ 'content' ];
        }
    }

} else {
    echo us_translate( 'No results found.' );
}
</code>```

Body:
I have the following code inside the search results page and I want it not to show it when there is no content in any part.

            if ( have_posts() ) {
                $types = array('singer', 'music', 'album');
                foreach( $types as $type ){
                    if( $type == 'singer'){
                        echo '
Singers
 ';
                    } elseif ( $type == 'music'){
                        echo '
Musics
';
                    }
                    elseif ( $type == 'album'){
                        echo '
Albums
';
                    }
                    while( have_posts() ){
                        the_post();
                        if( $type == get_post_type() ){
                            the_post_thumbnail('medium'); ?>

<a href="<?php echo get_permalink(); ?>">
                            <?php the_title();  ?>

                            <?php
                        }
                    }
                rewind_posts();
                }
            } else {
                echo us_translate( 'No results found.' );
            }

Body:
This is not a good solution, but should work)

$types = array(
    'singer' => array( 'title' => 'Singers', 'content' => '' ),
    'music'  => array( 'title' => 'Musics', 'content' => '' ),
    'album'  => array( 'title' => 'Albums', 'content' => '' ),
);

if ( have_posts() ) {

    while( have_posts() ) {
        the_post();
        $type = get_post_type();
        if ( array_key_exists( $type, $types ) ) {
            $types[ $type ][ 'content' ] .= get_the_post_thumbnail( null, 'medium' );
            $types[ $type ][ 'content' ] .= '<h3><a href="' . get_the_permalink() . '">' . get_the_title() . '</h3>';
        }
    }

    foreach( $types as $k => $v ) {
        if ( $v[ 'content' ] ) {
            echo '<h1>' . $v[ 'title' ]. '</h1>' . $v[ 'content' ];
        }
    }

} else {
    echo us_translate( 'No results found.' );
}


问:
django input serializer date field format
I have a date input format in mm/dd/yyyy.

In my input serializer,

```<code>class ProjectInitSerializer(serializers.Serializer):
    client_name = serializers.CharField(allow_blank=False, max_length=300)
    file_name = serializers.CharField(allow_blank=False, max_length=300)
    run_date = serializers.DateField(required=True, input_formats="%d/%m/%Y")
</code>```

I get this response:

```<code>"response": {
    "run_date": [
        "Date has wrong format. Use one of these formats instead: %, d, /, %, m, /, %, Y."
    ]
}
</code>```

This serializer is used for input request only.

How do I format this?

答:
Change input_formats to a list.

```<code>run_date = serializers.DateField(required=True, input_formats=["%d/%m/%Y"])
</code>```

Body:
I have a date input format in mm/dd/yyyy.

In my input serializer,

class ProjectInitSerializer(serializers.Serializer):
    client_name = serializers.CharField(allow_blank=False, max_length=300)
    file_name = serializers.CharField(allow_blank=False, max_length=300)
    run_date = serializers.DateField(required=True, input_formats="%d/%m/%Y")

I get this response:

"response": {
    "run_date": [
        "Date has wrong format. Use one of these formats instead: %, d, /, %, m, /, %, Y."
    ]
}

This serializer is used for input request only.

How do I format this?

Body:
Change input_formats to a list.

run_date = serializers.DateField(required=True, input_formats=["%d/%m/%Y"])


答:
Introducing a difficulties dictionary, as well as an is_solvable boolean in solvable(), and defining generate_tiles() to produce solvable game configurations using itertools.permutations(), as well as choose_difficulty() with default level set to easy:

```<code>from itertools import permutations
from pprint import pprint as pp

def solvable(tiles):
    count = 0
    for i in range(8):
        for j in range(i+1, 9):
            if tiles[j] and tiles[i] and tiles[i] > tiles[j]:
                count += 1

    is_solvable = count % 2 == 0

    if is_solvable:
        difficulties = {'0': 'trivial',
                        '2': 'easy',
                        '4': 'medium',
                        '6': 'hard'
                        }
        difficulty = difficulties.get(str(count), 'very hard')
        return [difficulty, count, is_solvable]

    return [count, is_solvable]

def generate_tiles(count=2):
    """Generate solvable tiles for the 3x3 puzzle."""
    tile_candidates = list(permutations(list(range(9))))
    good_tiles = []
    for tile_candidate in tile_candidates:
        if solvable(tile_candidate)[-1]:
            good_tiles.append(tile_candidate)
    return good_tiles

def choose_difficulty(tiles, level=2):
    """Choose difficulty for the 3x3 puzzle, default level is easy (2)."""
    labelled_tiles = []
    for tile in tiles:
        labelled_tiles.append({"tile": tile,
                               "label": solvable(tile)
                               })
    level_tiles = []
    for tile_dict in labelled_tiles:
        if tile_dict['label'][1] == level:
            level_tiles.append(tile_dict)
    return level_tiles

if __name__ == '__main__':
    # Generate all solvable and easy tiles
    tiles = generate_tiles()
    pp(choose_difficulty(tiles))
</code>```

Returns all the easy tiles:

```<code>...
 {'label': ['easy', 2, True], 'tile': (2, 3, 1, 4, 5, 6, 7, 8, 0)},
 {'label': ['easy', 2, True], 'tile': (3, 0, 1, 2, 4, 5, 6, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 0, 2, 4, 5, 6, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 0, 4, 5, 6, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 4, 0, 5, 6, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 4, 5, 0, 6, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 4, 5, 6, 0, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 4, 5, 6, 7, 0, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 4, 5, 6, 7, 8, 0)}]
</code>```

Title: Generate 3x3 puzzles with the same difficulty?

Body:
Introducing a difficulties dictionary, as well as an is_solvable boolean in solvable(), and defining generate_tiles() to produce solvable game configurations using itertools.permutations(), as well as choose_difficulty() with default level set to easy:

from itertools import permutations
from pprint import pprint as pp

def solvable(tiles):
    count = 0
    for i in range(8):
        for j in range(i+1, 9):
            if tiles[j] and tiles[i] and tiles[i] > tiles[j]:
                count += 1

    is_solvable = count % 2 == 0

    if is_solvable:
        difficulties = {'0': 'trivial',
                        '2': 'easy',
                        '4': 'medium',
                        '6': 'hard'
                        }
        difficulty = difficulties.get(str(count), 'very hard')
        return [difficulty, count, is_solvable]

    return [count, is_solvable]

def generate_tiles(count=2):
    """Generate solvable tiles for the 3x3 puzzle."""
    tile_candidates = list(permutations(list(range(9))))
    good_tiles = []
    for tile_candidate in tile_candidates:
        if solvable(tile_candidate)[-1]:
            good_tiles.append(tile_candidate)
    return good_tiles

def choose_difficulty(tiles, level=2):
    """Choose difficulty for the 3x3 puzzle, default level is easy (2)."""
    labelled_tiles = []
    for tile in tiles:
        labelled_tiles.append({"tile": tile,
                               "label": solvable(tile)
                               })
    level_tiles = []
    for tile_dict in labelled_tiles:
        if tile_dict['label'][1] == level:
            level_tiles.append(tile_dict)
    return level_tiles

if __name__ == '__main__':
    # Generate all solvable and easy tiles
    tiles = generate_tiles()
    pp(choose_difficulty(tiles))

Returns all the easy tiles:

...
 {'label': ['easy', 2, True], 'tile': (2, 3, 1, 4, 5, 6, 7, 8, 0)},
 {'label': ['easy', 2, True], 'tile': (3, 0, 1, 2, 4, 5, 6, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 0, 2, 4, 5, 6, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 0, 4, 5, 6, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 4, 0, 5, 6, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 4, 5, 0, 6, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 4, 5, 6, 0, 7, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 4, 5, 6, 7, 0, 8)},
 {'label': ['easy', 2, True], 'tile': (3, 1, 2, 4, 5, 6, 7, 8, 0)}]


问:
Remove Current Item from List if some criteria matches
I am trying to remove my current item in for each loop if some criterai matches but its triggering error after removing and looping again.

My sample code:

```<code>        For Each Item As BookingRoom In myBookedRooms
            If Item.RoomInfo.UIN = myRoom.UIN Then
                myBookedRooms.Remove(Item)
                Continue For
            End If
        Next
</code>```

*Note RoomInfo and myRoom are both instances of Room Class

I am using myBookedRooms.remove but its trigerring error so what can be the correct way for doing it? ie, remove booked room if the room id matches with selected one

答:
The problem is you're modifying the collection while iterating over it.

You can iterate the list in reverse with a for loop:

```<code>For i = myBookedRooms.Count - 1 To 0 Step -1
    If myBookedRooms(i).RoomInfo.UIN = myRoom.UIN Then
        myBookedRooms.RemoveAt(i)
    End If
Next
</code>```

Alternately, you can use the RemoveAll method:

```<code>myBookedRooms.RemoveAll(Function(item) item.RoomInfo.UIN = myRoom.UIN)
</code>```

Another option is to use the Enumerable.Where method to filter the results, but unlike the previous two approaches you would need to reverse your logic check to exclude the matching items since the intention is to remove them:

```<code>myBookedRooms = myBookedRooms
                    .Where(Function(item) item.RoomInfo.UIN <> myRoom.UIN)
                    .ToList()
</code>```

Body:
I am trying to remove my current item in for each loop if some criterai matches but its triggering error after removing and looping again.

My sample code:

        For Each Item As BookingRoom In myBookedRooms
            If Item.RoomInfo.UIN = myRoom.UIN Then
                myBookedRooms.Remove(Item)
                Continue For
            End If
        Next

*Note RoomInfo and myRoom are both instances of Room Class

I am using myBookedRooms.remove but its trigerring error so what can be the correct way for doing it? ie, remove booked room if the room id matches with selected one

Body:
The problem is you're modifying the collection while iterating over it.

You can iterate the list in reverse with a for loop:

For i = myBookedRooms.Count - 1 To 0 Step -1
    If myBookedRooms(i).RoomInfo.UIN = myRoom.UIN Then
        myBookedRooms.RemoveAt(i)
    End If
Next

Alternately, you can use the RemoveAll method:

myBookedRooms.RemoveAll(Function(item) item.RoomInfo.UIN = myRoom.UIN)

Another option is to use the Enumerable.Where method to filter the results, but unlike the previous two approaches you would need to reverse your logic check to exclude the matching items since the intention is to remove them:

myBookedRooms = myBookedRooms
                    .Where(Function(item) item.RoomInfo.UIN <> myRoom.UIN)
                    .ToList()


问:
How to set time with jquery keyup method?
I want to add time with jquery keyup method.
Here is my code:

$("#textbox").keyup(function () {
    var text = $('#textbox').val()

    $("#output").val(text);
});```
<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>
<!DOCTYPE html>
<html>
   <body>
      <textarea id="textbox" placeholder = "..." rows="5"></textarea>
      <br><br>
      <input type="text" id="output"/>
   </body>
</html></code>```

Actually I want when I'm typing, the keyup function call every 5 seconds.
Like:
I'm typing The quick brown fox jumps over the lazy dog.
Desired output: T f t d like this.
first lettert t. The keyup function is callded after 5 section. And i'm also typing. After 5 sec the secound word is f from 'fox'.
And continue like this....

Have any way?

答:
```<code>let lastKeyTime = 0;
$("#textbox").keyup(function () {
    if (lastKeyTime < Date.now() - 5000) {
        const outputElement = $("#output");
        outputElement.val(outputElement.val() + this.value.slice(this.value.length - 1));
        lastKeyTime = Date.now();
    }
});
</code>```

But be aware, that when using keyup instead of keydown and you press two keys partially simultaneously (what happens all the time when typing fast), it will add the last pressed key to your list.

Body:
I want to add time with jquery keyup method.
Here is my code:

$("#textbox").keyup(function () {
    var text = $('#textbox').val()

    $("#output").val(text);
});

<!DOCTYPE html>

      <textarea id="textbox" placeholder = "..." rows="5"></textarea>

      <input type="text" id="output"/>

Actually I want when I'm typing, the keyup function call every 5 seconds.
Like:
I'm typing The quick brown fox jumps over the lazy dog.
Desired output: T f t d like this.
first lettert t. The keyup function is callded after 5 section. And i'm also typing. After 5 sec the secound word is f from 'fox'.
And continue like this....

Have any way?

Body:
let lastKeyTime = 0;
$("#textbox").keyup(function () {
    if (lastKeyTime < Date.now() - 5000) {
        const outputElement = $("#output");
        outputElement.val(outputElement.val() + this.value.slice(this.value.length - 1));
        lastKeyTime = Date.now();
    }
});

But be aware, that when using keyup instead of keydown and you press two keys partially simultaneously (what happens all the time when typing fast), it will add the last pressed key to your list.


问:
How to set content description of a switch or toggle button in Android Studio?
I would like to make my app accessible with Tlkback, but I don't know how could I set different content descriptions for both states of a switch or toggle button.

Do you have any suggestions?

答:
You can set content description programmatically like this.</p>

```<code>toggleButton.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick( View v ) {
            if( toggleButton.isChecked() ) {
                toggleButton.setContentDescription( "Selected" );
            } else {
                toggleButton.setContentDescription( "Unselected" );
            }
        }
    } );
</code>```

Body:
You can set content description programmatically like this.

toggleButton.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick( View v ) {
            if( toggleButton.isChecked() ) {
                toggleButton.setContentDescription( "Selected" );
            } else {
                toggleButton.setContentDescription( "Unselected" );
            }
        }
    } );


问:
With what user should i do queries in postgres and php
Here is the current situation: I have a login page on which user enters his username and pass. Then I connect to the database using a "hardcoded" user (in the script), which opens connection to the server and executes the query to check if this data that user submitted is valid, and if so it "recognizes" him as logged in. This is the scenario that I saw and used in most of my applications.

Now, since I already have a database with many users (postgres database roles and not table "users" - I have to stress this to not mislead you) I was wondering if it would be good practice to do a pg_connect with a username and password the user puts in the login page.

My further question is how would I then keep them logged in? Session variable with username and hashed password? How is this affected from security viewpoint?

I would be grateful for your answers and any good reading material is appreciated!

答:
I don't think that's wise at all. Technically you would have your root or admin user which can DROP or ALTER tables right? You don't want it at all possible for a user to get access to your database internals.

Why don't you have a separate table (at the moment that is)? If you require your users to have real database access (for another system or application) then you should still create a proper users table.

You can always write a script which will sync the data across from the internal DB users table to your application users table.


问:
get total count and created after count for same table in one query
I have team and teams has many teams_users.
I want to get the count of total users of team & users created for team in last 30 days.

I have tried below approach but getting same number for both

```<code>Team.joins(:teams_users)
    .select("teams.id, COUNT(teams_users.id) as total_users, COUNT( CASE WHEN teams_users.created_at > #{Date.today -
30.days} THEN 1 END) AS joined_in_month")
    .group('teams.id').map(&:attributes)
</code>```

output

```<code>[640] {
                 "id" => 688,
        "total_users" => 3,
    "joined_in_month" => 3
},
[641] {
                 "id" => 689,
        "total_users" => 2,
    "joined_in_month" => 2
},
[642] {
                 "id" => 690,
        "total_users" => 1,
    "joined_in_month" => 1
}
</code>```

Anyone know where I am going wrong.

答:
I think you want to use SUM instead of COUNT on the second part. Assuming there are single row for each user per team in teams_users then you should have it with a query like:

```<code>SELECT
   tu.teams_id,
   COUNT(0) AS total_users,
   SUM(tu.created_at > (CURRENT_DATE - INTERVAL 30 DAY)) AS joined_in_month
FROM teams_users tu
GROUP BY tu.teams_id
;
</code>```

Body:
I have team and teams has many teams_users.
I want to get the count of total users of team & users created for team in last 30 days.

I have tried below approach but getting same number for both

Team.joins(:teams_users)
    .select("teams.id, COUNT(teams_users.id) as total_users, COUNT( CASE WHEN teams_users.created_at > #{Date.today -
30.days} THEN 1 END) AS joined_in_month")
    .group('teams.id').map(&:attributes)

output

[640] {
                 "id" => 688,
        "total_users" => 3,
    "joined_in_month" => 3
},
[641] {
                 "id" => 689,
        "total_users" => 2,
    "joined_in_month" => 2
},
[642] {
                 "id" => 690,
        "total_users" => 1,
    "joined_in_month" => 1
}

Anyone know where I am going wrong.

Body:
I think you want to use SUM instead of COUNT on the second part. Assuming there are single row for each user per team in teams_users then you should have it with a query like:

SELECT
   tu.teams_id,
   COUNT(0) AS total_users,
   SUM(tu.created_at > (CURRENT_DATE - INTERVAL 30 DAY)) AS joined_in_month
FROM teams_users tu
GROUP BY tu.teams_id
;


问:
How to provide placeholder in mat-select
I need to display a special string "No values selected" if the user has not selected a value (or cleared selection) in a mat-select.

I wanted to use the placeholder attribute, as can be seen in the documentation.

```<code><h4>Basic mat-select</h4>
<mat-form-field>
  <mat-label>Favorite food</mat-label>
  <mat-select placeholder="No value selected">  <!-- this is not showing-->
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>
</code>```

However, if I apply the attribute, the placeholder is overwritten by the label, which I do not want to.

Stackblitz example: https://stackblitz.com/edit/angular-qlpnim-vyfruq

I have tried to replace it with attribute binding, no luck with that. I still need the <mat-label> so it can be visually similar to other form fields in the form.

答:
You can use floatLabel=always on MatFormField

```<code><mat-form-field floatLabel="always">
  <mat-label>Favorite food</mat-label>
  <mat-select placeholder="test placeholder">  <!-- this is not showing-->
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>
</code>```

stackblitz

Body:
I need to display a special string "No values selected" if the user has not selected a value (or cleared selection) in a mat-select.

I wanted to use the placeholder attribute, as can be seen in the documentation.

Basic mat-select

<mat-form-field>
  <mat-label>Favorite food</mat-label>
  <mat-select placeholder="No value selected">
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

However, if I apply the attribute, the placeholder is overwritten by the label, which I do not want to.

Stackblitz example: https://stackblitz.com/edit/angular-qlpnim-vyfruq

I have tried to replace it with attribute binding, no luck with that. I still need the <mat-label> so it can be visually similar to other form fields in the form.

Body:
You can use floatLabel=always on MatFormField

<mat-form-field floatLabel="always">
  <mat-label>Favorite food</mat-label>
  <mat-select placeholder="test placeholder">  <!-- this is not showing-->
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

stackblitz


问:
how to set the color of toggle button from style already defined in app xaml?
I had created a button and i want to change its color using style from app xaml.
But,i don't get the exact code and i am new to xaml.

Can any one help me with some example.

I am also confused to use which property to change color means background or foreground?

答:
```<code><Window
  x:Class="ToolBar"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="ToolBar"
  Width="300"
  Height="300">
  <DockPanel>
    <ToolBarTray
      DockPanel.Dock="Top"
      IsLocked="True"
      Orientation="Horizontal">
      <ToolBar
        x:Name="ToolBar1">
        <ToggleButton>
          <ToggleButton.Style>
            <Style
              TargetType="{x:Type ToggleButton}">
              <Setter Property="ContentTemplate">
                <Setter.Value>
                  <DataTemplate>
                    <Label>Play</Label>
                  </DataTemplate>
                </Setter.Value>
              </Setter>
              <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                  <Setter Property="ContentTemplate">
                    <Setter.Value>
                      <DataTemplate>
                        <Label>Pause</Label>
                      </DataTemplate>
                    </Setter.Value>
                  </Setter>
                  <Setter Property="BorderBrush" Value="Transparent" />
                  <Setter Property="Panel.Background" Value="Transparent" />
                </Trigger>
              </Style.Triggers>
            </Style>
          </ToggleButton.Style>
        </ToggleButton>
      </ToolBar>
    </ToolBarTray>
  </DockPanel>
</Window>
</code>```

Within a toolbar, the two statements:

```<code><Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Panel.Background" Value="Transparent" />
</code>```

causes the toggle button to appear in the normal state when the toggle button is checked, however nothing changes when you hover over the checked toggle button.

If I wrap the toggle button in another layout, say wrap layout:

```<code><Window
  x:Class="ToolBar"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="ToolBar"
  Width="300"
  Height="300">
  <WrapPanel>
        <ToggleButton>
          <ToggleButton.Style>
            <Style
              TargetType="{x:Type ToggleButton}">
              <Setter Property="ContentTemplate">
                <Setter.Value>
                  <DataTemplate>
                    <Label>Play</Label>
                  </DataTemplate>
                </Setter.Value>
              </Setter>
              <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                  <Setter Property="ContentTemplate">
                    <Setter.Value>
                      <DataTemplate>
                        <Label>Pause</Label>
                      </DataTemplate>
                    </Setter.Value>
                  </Setter>
                  <Setter Property="BorderBrush" Value="Transparent" />
                  <Setter Property="Panel.Background" Value="Transparent" />
                </Trigger>
              </Style.Triggers>
            </Style>
          </ToggleButton.Style>
        </ToggleButton>
  </WrapPanel>
</Window>
</code>```

the two statements:

```<code><Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Panel.Background" Value="Transparent" />
</code>```

You can find tutorial in the folowing url
http://social.msdn.microsoft.com/Forums/pl-PL/wpf/thread/7e565a41-0aad-40a3-a3c4-666c5caf38fe

Thanks
Deepak

Body:
<Window
  x:Class="ToolBar"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="ToolBar"
  Width="300"
  Height="300">
  <DockPanel>
    <ToolBarTray
      DockPanel.Dock="Top"
      IsLocked="True"
      Orientation="Horizontal">
      <ToolBar
        x:Name="ToolBar1">
        <ToggleButton>
          <ToggleButton.Style>
            <Style
              TargetType="{x:Type ToggleButton}">
              <Setter Property="ContentTemplate">
                <Setter.Value>
                  <DataTemplate>
                    <Label>Play</Label>
                  </DataTemplate>
                </Setter.Value>
              </Setter>
              <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                  <Setter Property="ContentTemplate">
                    <Setter.Value>
                      <DataTemplate>
                        <Label>Pause</Label>
                      </DataTemplate>
                    </Setter.Value>
                  </Setter>
                  <Setter Property="BorderBrush" Value="Transparent" />
                  <Setter Property="Panel.Background" Value="Transparent" />
                </Trigger>
              </Style.Triggers>
            </Style>
          </ToggleButton.Style>
        </ToggleButton>
      </ToolBar>
    </ToolBarTray>
  </DockPanel>
</Window>

Within a toolbar, the two statements:

<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Panel.Background" Value="Transparent" />

causes the toggle button to appear in the normal state when the toggle button is checked, however nothing changes when you hover over the checked toggle button.

If I wrap the toggle button in another layout, say wrap layout:

<Window
  x:Class="ToolBar"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="ToolBar"
  Width="300"
  Height="300">
  <WrapPanel>
        <ToggleButton>
          <ToggleButton.Style>
            <Style
              TargetType="{x:Type ToggleButton}">
              <Setter Property="ContentTemplate">
                <Setter.Value>
                  <DataTemplate>
                    <Label>Play</Label>
                  </DataTemplate>
                </Setter.Value>
              </Setter>
              <Style.Triggers>
                <Trigger Property="IsChecked" Value="True">
                  <Setter Property="ContentTemplate">
                    <Setter.Value>
                      <DataTemplate>
                        <Label>Pause</Label>
                      </DataTemplate>
                    </Setter.Value>
                  </Setter>
                  <Setter Property="BorderBrush" Value="Transparent" />
                  <Setter Property="Panel.Background" Value="Transparent" />
                </Trigger>
              </Style.Triggers>
            </Style>
          </ToggleButton.Style>
        </ToggleButton>
  </WrapPanel>
</Window>

the two statements:

<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Panel.Background" Value="Transparent" />

You can find tutorial in the folowing url
http://social.msdn.microsoft.com/Forums/pl-PL/wpf/thread/7e565a41-0aad-40a3-a3c4-666c5caf38fe

Thanks
Deepak


问:
Why is Java giving my ArrayList an IndexOutOfBoundsException?
Why is Java giving me an error message?
Im using JavaSE-12 and don't understand why I have an IndexOutOfBoundsException.
Do I have to specify the index of the ArrayList or what am I missing?</p>

```<code>    import java.util.ArrayList;

public class DSArrayList {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<String> namensListe = new ArrayList<String>();

        namensListe.add("Hans");
        namensListe.add("Peter");

        for(int i = 0; i <= namensListe.size(); i++) {
            System.out.println("Name: " + namensListe.get(i));
        }

    }

}
</code>```

答:
for(int i = 0; i < namensListe.size(); i++)

(note the < operator)

To explain, arrays and like structures are indexed from zero, not one. Obviously we count, however, from one, not zero. So the length of an array is always one greater than the index of the last item it contains.

Body:
Why is Java giving me an error message?
Im using JavaSE-12 and don't understand why I have an IndexOutOfBoundsException.
Do I have to specify the index of the ArrayList or what am I missing?

    import java.util.ArrayList;

public class DSArrayList {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<String> namensListe = new ArrayList<String>();

        namensListe.add("Hans");
        namensListe.add("Peter");

        for(int i = 0; i <= namensListe.size(); i++) {
            System.out.println("Name: " + namensListe.get(i));
        }

    }

}


问:
Getting all 10 digit and 9 digit number for a string in python
I'm a new bee to the python.So all I want is to get all the 10 digit number and 9 digit number from a string.
I'm having a string Like this

```<code>Re: ehi - ECQ TANGAL INIP NA!!!! 67778877 NO LOAD 34567890123!!!! 5678901234 123456789
</code>```

Should return only the numbers with 9 and 10 digit.The number can occur anywhere in the string.
In the above string it should return these numbers

```<code>5678901234
123456789
</code>```

But not

```<code>67778877 as it is 8 digit number
34567890123 as it is 11 digit number

</code>```

答:
You can use a regular expression to find all required matches:

```<code>import re

data = 'Re: ehi - ECQ TANGAL INIP NA!!!! 67778877 NO LOAD 34567890123!!!! 5678901234 123456789'
values = re.findall(r'\b\d{9,10}\b', data)
print( values )  # ['5678901234', '123456789']
</code>```

Here \b states for the boundary of the numeric group \d (same as [0-9]). {9,10} is the number of repetitions of \d.

DOCS: https://docs.python.org/3/library/re.html

Body:
I'm a new bee to the python.So all I want is to get all the 10 digit number and 9 digit number from a string.
I'm having a string Like this

Re: ehi - ECQ TANGAL INIP NA!!!! 67778877 NO LOAD 34567890123!!!! 5678901234 123456789

Should return only the numbers with 9 and 10 digit.The number can occur anywhere in the string.
In the above string it should return these numbers

5678901234
123456789

But not

67778877 as it is 8 digit number
34567890123 as it is 11 digit number

Body:
You can use a regular expression to find all required matches:

import re

data = 'Re: ehi - ECQ TANGAL INIP NA!!!! 67778877 NO LOAD 34567890123!!!! 5678901234 123456789'
values = re.findall(r'\b\d{9,10}\b', data)
print( values )  # ['5678901234', '123456789']

Here \b states for the boundary of the numeric group \d (same as [0-9]). {9,10} is the number of repetitions of \d.

DOCS: https://docs.python.org/3/library/re.html


问:
Replace values outside range with NA using replace_with_na function
I have the following dataset

```<code>structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 34
3 9  1 77
4 2  9 88
5 9 12 33
6 8 NA 60
</code>```

From column b I only want values between 4-9. Column c between 50-80. Replacing the values outside the range with NA, resulting in

```<code>structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, NA, 9, NA,
NA), c = c(50, NA, 77, NA, NA, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 NA
3 9 NA 77
4 2  9 NA
5 9 NA NA
6 8 NA 60
</code>```

I've tried several things with replace_with_na_at function where this seemed most logical:

```<code>test <- replace_with_na_at(data = test, .vars="c",
                          condition = ~.x < 2 & ~.x > 2)
</code>```

However, nothing I tried works. Does somebody know why? Thanks in advance! :)

答:
You simply could use Map to replace your values with NA.

```<code>dat[2:3] <- Map(function(x, y) {x[!x %in% y] <- NA;x}, dat[2:3], list(4:9, 50:80))
dat
#   a  b  c
# 1 2  4 50
# 2 1  5 NA
# 3 9 NA 77
# 4 2  9 NA
# 5 9 NA NA
# 6 8 NA 60
</code>```

Data:

```<code>dat <- structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))
</code>```

Body:
I have the following dataset

structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 34
3 9  1 77
4 2  9 88
5 9 12 33
6 8 NA 60

From column b I only want values between 4-9. Column c between 50-80. Replacing the values outside the range with NA, resulting in

structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, NA, 9, NA,
NA), c = c(50, NA, 77, NA, NA, 60)), class = "data.frame", row.names = c(NA,
-6L))

  a  b  c
1 2  4 50
2 1  5 NA
3 9 NA 77
4 2  9 NA
5 9 NA NA
6 8 NA 60

I've tried several things with replace_with_na_at function where this seemed most logical:

test <- replace_with_na_at(data = test, .vars="c",
                          condition = ~.x < 2 & ~.x > 2)

However, nothing I tried works. Does somebody know why? Thanks in advance! :)

Body:
You simply could use Map to replace your values with NA.

dat[2:3] <- Map(function(x, y) {x[!x %in% y] <- NA;x}, dat[2:3], list(4:9, 50:80))
dat
#   a  b  c
# 1 2  4 50
# 2 1  5 NA
# 3 9 NA 77
# 4 2  9 NA
# 5 9 NA NA
# 6 8 NA 60

Data:

dat <- structure(list(a = c(2, 1, 9, 2, 9, 8), b = c(4, 5, 1, 9, 12,
NA), c = c(50, 34, 77, 88, 33, 60)), class = "data.frame", row.names = c(NA,
-6L))


问:
How should I store consecutive f64 values in Wasm memory?
I am writing a tiny compiler that outputs Wasm directly. In my source language all values are f64s and they can be written into (and read out of) a fixed size buffer by index.

I am attempting to use a (the?) Wasm memory to store that buffer.

When storing consecutive f64 values in memory, should I be deriving the address at runtime by multiplying the index by the byte size of an f64, or can I somehow achieve this using align/offset?

In my initial approach (which is stupid in retrospect) assumed I could just use consecutive indices and somehow the fact that I was using f64.store and f64.load it would "just work".

It looked something like this .wat file:

```<code>(module
      (memory 1)
      (func (result f64)
          ;; Write 0 to index 99
          i32.const 99
          f64.const 0
          f64.store

          ;; Write 1 to index 100
          i32.const 100
          f64.const 1
          f64.store

          ;; Read from 99
          i32.const 99
          f64.load
      )
      (export "run" (func 0))
  )
</code>```

I expected this to output 0 but it output -3.105036184601418e+231 which I assume is because some of the bytes I'm reading when I start reading at index 99 were just written when I wrote to index 100.

What would a "correct" version of the above .wat file -- one that that stores two consecutive f64 values into memory and then reads one -- look like?

The official f64.load/f64.store spec can be found here.

答:
When storing consecutive f64 values in memory, should I be deriving the address at runtime by multiplying the index by the byte size of an f64, or can I somehow achieve this using align/offset?

No, you can't obtain this with align/offset.

You have to multiply all indexes by 8 (since f64 is 64 bit / 8 bit = 8).

You can do that directly in every memory access or another way would be to define two utility functions:

(result f64) myload(index i32) and

() mystore(i32 index, f64 value)

These function will then do the load/store at index*8.

Body:
I am writing a tiny compiler that outputs Wasm directly. In my source language all values are f64s and they can be written into (and read out of) a fixed size buffer by index.

I am attempting to use a (the?) Wasm memory to store that buffer.

When storing consecutive f64 values in memory, should I be deriving the address at runtime by multiplying the index by the byte size of an f64, or can I somehow achieve this using align/offset?

In my initial approach (which is stupid in retrospect) assumed I could just use consecutive indices and somehow the fact that I was using f64.store and f64.load it would "just work".

It looked something like this .wat file:

(module
      (memory 1)
      (func (result f64)
          ;; Write 0 to index 99
          i32.const 99
          f64.const 0
          f64.store

          ;; Write 1 to index 100
          i32.const 100
          f64.const 1
          f64.store

          ;; Read from 99
          i32.const 99
          f64.load
      )
      (export "run" (func 0))
  )

I expected this to output 0 but it output -3.105036184601418e+231 which I assume is because some of the bytes I'm reading when I start reading at index 99 were just written when I wrote to index 100.

What would a "correct" version of the above .wat file -- one that that stores two consecutive f64 values into memory and then reads one -- look like?

The official f64.load/f64.store spec can be found here.


问:
how to read the response from a web site?
I have a website url which gives corresponding city names by taking zip code as input parameter. Now I want to know how to read the response from the site.

This is the link I am using http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680

答:
try this (you'll need to include System.text and System.net)</p>

```<code>WebClient client = new WebClient();
string url = "http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680";
Byte[] requestedHTML;
requestedHTML = client.DownloadData(url);

UTF8Encoding objUTF8 = new UTF8Encoding();
string html = objUTF8.GetString(requestedHTML);
Response.Write(html);
</code>```

Body:
try this (you'll need to include System.text and System.net)

WebClient client = new WebClient();
string url = "http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680";
Byte[] requestedHTML;
requestedHTML = client.DownloadData(url);

UTF8Encoding objUTF8 = new UTF8Encoding();
string html = objUTF8.GetString(requestedHTML);
Response.Write(html);


问:
How to get a reference to firebase image to be able to delete it?
so I have this function to retrieve all my photos

```<code>const getPhotos = async () => {
    const storage = firebaseApp.storage()
    let gsReference = storage.refFromURL('gs://my-app/')
    gsReference = gsReference.child(`${id}/${country}`)

    const { items } = await gsReference.listAll()
    const urlPromises = items.map((pr) =>
        pr
            .getDownloadURL()
            .then((url) => fetch(url))
            .catch((error) => error),
    )

    let urls = await Promise.all(urlPromises)
    urls = urls.filter((result) => !(result instanceof Error))
    setPhotos(urls)
}
</code>```

this works all good

now the problem is when I want to delete an image. ive got this function

```<code>const deletePhoto = (photoRef) => {
    console.log('PHOTO:', photoRef)
    var storage = firebaseApp.storage()
    var storageRef = storage.ref(`${id}/${country}`)
}
</code>```

the problem is I have no way of knowing the reference to the image I want to delete?

I am mapping over all the images and for each image I'm attaching the delete function and passing in the photo as an arg. however this just returns me this

```<code>body: ReadableStream {locked: false}
bodyUsed: false
headers: Headers {append: function, delete: function, get: function, has: function, set:
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://firebasestorage.googleapis.com/v0/b/my-app.appspot.com/o/F2DFB6714-8082-4AF9-89…"
</code>```

it looks like the url does reference the path but it cuts some of it off at the end. plus I don't really want to be splicing that down to find the image. there must be an easy way to set the reference??

答:
You can combine Response and Reference object in another then callback after catch.

const getPhotos = async () => {
    const storage = firebaseApp.storage()
    let gsReference = storage.refFromURL('gs://my-app/')
    gsReference = gsReference.child(`${id}/${country}`)

    const { items: references } = await gsReference.listAll()
    const result = references.map(async (reference) => {
        const url = await reference.getDownloadURL();
        let response = null;

        try {
           response = await fetch(url);
        }
        catch(error) {
           response = error;
        }

        return {
           response,
           url,
           reference
        }
      }
    )

    let referencesWithUrls = await Promise.all(result)
    referencesWithUrls = referencesWithUrls.filter((result) => !(result.response instanceof Error))
    setPhotos(referencesWithUrls.map(pr => pr.response))
}
```

Body:
so I have this function to retrieve all my photos

const getPhotos = async () => {
    const storage = firebaseApp.storage()
    let gsReference = storage.refFromURL('gs://my-app/')
    gsReference = gsReference.child(`${id}/${country}`)

    const { items } = await gsReference.listAll()
    const urlPromises = items.map((pr) =>
        pr
            .getDownloadURL()
            .then((url) => fetch(url))
            .catch((error) => error),
    )

    let urls = await Promise.all(urlPromises)
    urls = urls.filter((result) => !(result instanceof Error))
    setPhotos(urls)
}

this works all good

now the problem is when I want to delete an image. ive got this function

const deletePhoto = (photoRef) => {
    console.log('PHOTO:', photoRef)
    var storage = firebaseApp.storage()
    var storageRef = storage.ref(`${id}/${country}`)
}

the problem is I have no way of knowing the reference to the image I want to delete?

I am mapping over all the images and for each image I'm attaching the delete function and passing in the photo as an arg. however this just returns me this

body: ReadableStream {locked: false}
bodyUsed: false
headers: Headers {append: function, delete: function, get: function, has: function, set:
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://firebasestorage.googleapis.com/v0/b/my-app.appspot.com/o/F2DFB6714-8082-4AF9-89…"

it looks like the url does reference the path but it cuts some of it off at the end. plus I don't really want to be splicing that down to find the image. there must be an easy way to set the reference??


问:
C# Emgu.Cv wrapper: Retrieved (byte) pixel-values of Mat do not match Image<Gray,byte> Bytes values, when cropping ROIs
(I use Emgu.Cv version 4.2.0.3662)

Let's consider the following construction of image objects by cropping a small ROI of width=w, and height=h:

```<code>Image<Gray, byte> img = new Image<Gray, byte>(@"D:\temp\tst_img.JPG");
Mat mat = img.Copy().Mat;
var roi = new Rectangle(0, 0, w, h);
img.ROI = roi;
var tst_img = img.Copy();
var tst_mat = new Mat(mat, roi);
</code>```

(the w of the image file is divisible by 4.)
In order to get the byte values of tst_img I can use tst_img.Data (which is a byte[,,1] array) or tst_img.Bytes (which corresponds to the image pixel values as a byte[] array).

In order to get the byte values of the image which tst_mat corresponds to, I firstly tried tst_mat.GetData() (which can be identified as a byte[,] array). I noticed that the values of the tst_mat.GetData() byte array do not match the tst_img.Data values, however their dimensions do match (disregarding the extra 1-dim channel of the latter) . Yet, the following approach gives the expected values:

```<code>tst_mat.ToImage<Gray, byte>().Bytes
</code>```

I tried to follow some idea of implementing Marshal.Copy as described in
https://bugsdb.com/_en/debug/0cad34a2bab07405564a5f09bc14ccf7
so I prepared the following property in a MatExtension

```<code>public static byte[] MatData(this Mat mat)
{
        int w = mat.Width;
        int h = mat.Height;
        int l = w * h;
        byte[] output = new byte[l];
        Marshal.Copy(mat.DataPointer, output, 0, l);
        return output;
}
</code>```

Yet, tst_mat.MatData() do not yield the same byte values as tst_img.Bytes.
I suspect that this approach gives values which do not match tst_img.bytes since it doesn't consider the width/stride of the original mat (from which tst_mat was cropped).

Here I provide an explicit tested example, using an roi of size 4*2 (width*height) for the purpose of demonstration:

the test image

I compare the byte values of the following variables:

```<code>byte[,,] img_bytes_dat = img_roi.Data;
byte[,] mat_bytes_dat = (byte[,]) mat_roi.GetData();
byte[] img_bytes_arr = img_roi.Bytes;
byte[] mat_bytes_arr = mat_roi.MatData();
byte[] mat2img_bytes_arr = mat_roi.ToImage<Gray, byte>().Bytes;
</code>```

Looking at img_bytes_dat (or at its flattened version img_bytes_arr) I get following pixel values:

[0, 0, 0]   126

[0, 1, 0]   126

[0, 2, 0]   131

[0, 3, 0]   146

[1, 0, 0]   125 <-

[1, 1, 0]   124

[1, 2, 0]   130

[1, 3, 0]   145

(and mat2img_bytes_arr contains these pixel values).
Looking at mat_bytes_dat (mat_bytes_arr has the same pixel values) I get  following pixel values:

[0, 0]  126

[0, 1]  126

[0, 2]  131

[0, 3]  146

[1, 0]  154 <-

[1, 1]  156

[1, 2]  157

[1, 3]  153

It is the width of the ROI, which determines the index from which these arrays do not match.

Considering the above I am very confused about the meaning of the Mat.GetData() method, when we apply it to a Mat object which we construct by cropping an ROI of a different Mat object. The resulting array actually has the dimensions of the ROI but the data do not match what one would expect.

what is the correct and most efficient way to get all the pixel values of "tst_mat" as a single array (I don't mind 1d or multi-dimensional)?
(without the 2 stages route of "mat2img_bytes_arr" )

答:
First, well done for your diligence and testing. I was able to recreate the exact same behavior and consider this a bug. I would encourage you to report it to Emgu Forum where hopefully you may be better supported.

For you interest, I enclose the EmguCV source for the Mat(Mat,Rectangle) constructor, however it invokes the underlying OpenCV method with little indication of why it might behave this way:

```<code>/// <summary>
/// Create a mat header for the specific ROI
/// </summary>
/// <param name="mat">The mat where the new Mat header will share data from</param>
/// <param name="roi">The region of interest</param>
public Mat(Mat mat, Rectangle roi)
           : this(MatInvoke.cveMatCreateFromRect(mat.Ptr, ref roi), true, true){}
</code>```

To support you in the interim, I would advise against Marshal approaches since I do not believe the Image.Data object is necessarily pinned. Considering you are dealing with an array of unmanaged type, byte, you can be confident that any assignment made from them directly, unless explicitly ref, will assign by value and provide a "copy".

Perhaps the following extension might be helpful to you:

```<code>public static TDepth[,] CopyROIData<TDepth>(this Image<Gray, TDepth> image, int channel)
    where TDepth : new()
{
    TDepth[,] result = new TDepth[image.ROI.Height, image.ROI.Width];
    int xOrigin = image.ROI.X;
    int yOrigin = image.ROI.Y;

    TDepth[,,] fullData = image.Data;
    for(int u = 0; u < image.ROI.Width; u++)
    {
        for (int v = 0; v < image.ROI.Height; v++)
        {
            result[v,u] = fullData[v + yOrigin, u + xOrigin, channel];
        }
    }

    return result;
}
</code>```

Called as:

```<code>Image<Gray, byte> myImage = new Image<Gray, byte>(@"D:\temp\tst_img.JPG");
var myROIData = myImage.CopyROIData(0);
</code>```

Body:
(I use Emgu.Cv version 4.2.0.3662)

Let's consider the following construction of image objects by cropping a small ROI of width=w, and height=h:

Image<Gray, byte> img = new Image<Gray, byte>(@"D:\temp\tst_img.JPG");
Mat mat = img.Copy().Mat;
var roi = new Rectangle(0, 0, w, h);
img.ROI = roi;
var tst_img = img.Copy();
var tst_mat = new Mat(mat, roi);

(the w of the image file is divisible by 4.)
In order to get the byte values of tst_img I can use tst_img.Data (which is a byte[,,1] array) or tst_img.Bytes (which corresponds to the image pixel values as a byte[] array).

In order to get the byte values of the image which tst_mat corresponds to, I firstly tried tst_mat.GetData() (which can be identified as a byte[,] array). I noticed that the values of the tst_mat.GetData() byte array do not match the tst_img.Data values, however their dimensions do match (disregarding the extra 1-dim channel of the latter) . Yet, the following approach gives the expected values:

tst_mat.ToImage<Gray, byte>().Bytes

I tried to follow some idea of implementing Marshal.Copy as described in
https://bugsdb.com/_en/debug/0cad34a2bab07405564a5f09bc14ccf7
so I prepared the following property in a MatExtension

public static byte[] MatData(this Mat mat)
{
        int w = mat.Width;
        int h = mat.Height;
        int l = w * h;
        byte[] output = new byte[l];
        Marshal.Copy(mat.DataPointer, output, 0, l);
        return output;
}

Yet, tst_mat.MatData() do not yield the same byte values as tst_img.Bytes.
I suspect that this approach gives values which do not match tst_img.bytes since it doesn't consider the width/stride of the original mat (from which tst_mat was cropped).

Here I provide an explicit tested example, using an roi of size 4*2 (width*height) for the purpose of demonstration:

the test image

I compare the byte values of the following variables:

byte[,,] img_bytes_dat = img_roi.Data;
byte[,] mat_bytes_dat = (byte[,]) mat_roi.GetData();
byte[] img_bytes_arr = img_roi.Bytes;
byte[] mat_bytes_arr = mat_roi.MatData();
byte[] mat2img_bytes_arr = mat_roi.ToImage<Gray, byte>().Bytes;

Looking at img_bytes_dat (or at its flattened version img_bytes_arr) I get following pixel values:

[0, 0, 0]   126

[0, 1, 0]   126

[0, 2, 0]   131

[0, 3, 0]   146

[1, 0, 0]   125 <-

[1, 1, 0]   124

[1, 2, 0]   130

[1, 3, 0]   145

(and mat2img_bytes_arr contains these pixel values).
Looking at mat_bytes_dat (mat_bytes_arr has the same pixel values) I get  following pixel values:

[0, 0]  126

[0, 1]  126

[0, 2]  131

[0, 3]  146

[1, 0]  154 <-

[1, 1]  156

[1, 2]  157

[1, 3]  153

It is the width of the ROI, which determines the index from which these arrays do not match.

Considering the above I am very confused about the meaning of the Mat.GetData() method, when we apply it to a Mat object which we construct by cropping an ROI of a different Mat object. The resulting array actually has the dimensions of the ROI but the data do not match what one would expect.

what is the correct and most efficient way to get all the pixel values of "tst_mat" as a single array (I don't mind 1d or multi-dimensional)?
(without the 2 stages route of "mat2img_bytes_arr" )

Body:
First, well done for your diligence and testing. I was able to recreate the exact same behavior and consider this a bug. I would encourage you to report it to Emgu Forum where hopefully you may be better supported.

For you interest, I enclose the EmguCV source for the Mat(Mat,Rectangle) constructor, however it invokes the underlying OpenCV method with little indication of why it might behave this way:

/// <summary>
/// Create a mat header for the specific ROI
/// </summary>
/// <param name="mat">The mat where the new Mat header will share data from</param>
/// <param name="roi">The region of interest</param>
public Mat(Mat mat, Rectangle roi)
           : this(MatInvoke.cveMatCreateFromRect(mat.Ptr, ref roi), true, true){}

To support you in the interim, I would advise against Marshal approaches since I do not believe the Image.Data object is necessarily pinned. Considering you are dealing with an array of unmanaged type, byte, you can be confident that any assignment made from them directly, unless explicitly ref, will assign by value and provide a "copy".

Perhaps the following extension might be helpful to you:

public static TDepth[,] CopyROIData<TDepth>(this Image<Gray, TDepth> image, int channel)
    where TDepth : new()
{
    TDepth[,] result = new TDepth[image.ROI.Height, image.ROI.Width];
    int xOrigin = image.ROI.X;
    int yOrigin = image.ROI.Y;

    TDepth[,,] fullData = image.Data;
    for(int u = 0; u < image.ROI.Width; u++)
    {
        for (int v = 0; v < image.ROI.Height; v++)
        {
            result[v,u] = fullData[v + yOrigin, u + xOrigin, channel];
        }
    }

    return result;
}

Called as:

Image<Gray, byte> myImage = new Image<Gray, byte>(@"D:\temp\tst_img.JPG");
var myROIData = myImage.CopyROIData(0);


问:
Dialogflow: Forcing certain intents to be invalid given context
I want to make knock knock jokes using dialogflow, but I found that I can trigger one knock knock joke from the context of another. For example I have the following intents:

knockknock: training phrase (knock knock joke), response (knock knock)

whosethere: trainging phrase (who dat), response (annie, orange)

punchline-annie: training phrase (annie who), response (annie thing you can do I can do better)

punchline-orange: training phrase (orange who), response (orange you glad...)

If the bot responds with annie, I can respond with orange who and get the orange punchline to the joke. How can I prevent this from happening? I only want the orange punchline to be able to be called when the response from the whosethere intent was orange.

答: I think you need to look into how to send a responsive via fulfilment/webhook and how contexts work. In your whosthere intent, you could send a response via fulfilment and set the context appropriately. E.g.: if you answer with "annie", set an annie specific context (e.g. punchline-annie-context) and set punchline-annie-context as an input context for the punchline-annie intent. This way you ensure that punchline-annie can only be activated, if the whosthere response was "annie".</p>


问:
How to format ISO date in React-Native
I am getting date data in this format from my API:

```<code>"2018-12-26T05:00:29"
</code>```

however I need to display this in the application front end in a different format like this:

```<code>"Monday, Nov 26 at 10:00 am"
</code>```

How can I achieve this in react-native?

答:
While Moment.js can resolve this issue quickly, it's however a pretty big library to use for a single use case. I recommend using date-fns instead. It's lite.

I come out of this thanks to https://github.com/date-fns/date-fns/issues/376#issuecomment-353871093.

Despite the solution, I did some perfection on Date Field Symbol. You may need to use dd instead of DD / yyyy instead of YYYY for formatting days of the month / for formatting years.

Read the doc here: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md

Title: How to format ISO date in React-Native

Body:
I am getting date data in this format from my API:

"2018-12-26T05:00:29"

however I need to display this in the application front end in a different format like this:

"Monday, Nov 26 at 10:00 am"

How can I achieve this in react-native?


问:
Making numbers easier to read using filters
So I am trying to convert numbers on my website to look a bit nicer, such as 3217210 instead should be 3,217,210 I have tested a few threads but didn't get it to work.

My website takes these values from an API.

Heres my HTML:

```<code><tbody>
      {% for product in products %}
      <tr>
        <td>{{ product.id|replace("_", ' ')|lower()|title() }}</td>
        {% for buy in product.buy_price %}
        <td>{{ buy.pricePerUnit }}</td>
        {% for sell in product.sell_price %}
        <td>{{ sell.pricePerUnit }}</td>

        <td>{{ product.buy_volume|numberFormat }}</td>
        <td>{{ product.sell_volume}}</td>
        {% set margin = buy.pricePerUnit - sell.pricePerUnit%} {% set marginPer
        = margin/buy.pricePerUnit * 100%}
        <td
          aria-label="{{ marginPer|round(1, 'floor') }} % "
          data-balloon-pos="right"
        >
          {{ margin|round(1, 'floor')}}
        </td>
        {% endfor %}{% endfor %}
      </tr>
      {% endfor %}
    </tbody>
</code>```

And here is my python:

```<code>@app.route('/bprices', methods=['GET'])
def bPrices():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[cant show]').json()
    products = [
        {
            "id": product["product_id"],
            "sell_price": product["sell_summary"][:1],
            "buy_price": product["buy_summary"][:1],
            "sell_volume": product["quick_status"]["sellVolume"],
            "buy_volume": product["quick_status"]["buyVolume"],
        }
        for product in f["products"].values()
    ]
    return render_template("bprices.html", products=products)
</code>```

Thanks:)

答:
You can use global template filter in flask code and then use it in template. You can read the official documentation on custom template filter.

app.py:

```<code>from flask import Flask, render_template
app = Flask(__name__)

@app.template_filter()
def numberFormat(value):
    return format(int(value), ',d')

@app.route("/", methods=["GET"])
def home():
    products = [
        {
            "name": "mobile",
            "quantity": 3217210
        },
        {
            "name": "laptop",
            "quantity": 343217210
        },
        {
            "name": "mouse",
            "quantity": 100
        }
    ]
    return render_template("index.html", products=products)
</code>```

index.html:

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Number format</title>
  </head>
  <body>
    <h3>Products</h3>
    <table border="1">
      <thead>
        <tr>
          <th>Name</th>
          <th>Quantity</th>
        </tr>
      </thead>
      <tbody>
        {% for product in products %}
        <tr>
          <td>{{ product.name }}</td>
          <td>{{ product.quantity | numberFormat }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </body>
</html>
</code>```

Output:

You can modify the filter as per your requirements.

Body:
So I am trying to convert numbers on my website to look a bit nicer, such as 3217210 instead should be 3,217,210 I have tested a few threads but didn't get it to work.

My website takes these values from an API.

Heres my HTML:

      {% for product in products %}

        {{ product.id|replace("_", ' ')|lower()|title() }}
        {% for buy in product.buy_price %}
        {{ buy.pricePerUnit }}
        {% for sell in product.sell_price %}
        {{ sell.pricePerUnit }}

        {{ product.buy_volume|numberFormat }}
        {{ product.sell_volume}}
        {% set margin = buy.pricePerUnit - sell.pricePerUnit%} {% set marginPer
        = margin/buy.pricePerUnit * 100%}

          {{ margin|round(1, 'floor')}}

        {% endfor %}{% endfor %}

      {% endfor %}

And here is my python:

@app.route('/bprices', methods=['GET'])
def bPrices():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[cant show]').json()
    products = [
        {
            "id": product["product_id"],
            "sell_price": product["sell_summary"][:1],
            "buy_price": product["buy_summary"][:1],
            "sell_volume": product["quick_status"]["sellVolume"],
            "buy_volume": product["quick_status"]["buyVolume"],
        }
        for product in f["products"].values()
    ]
    return render_template("bprices.html", products=products)

Thanks:)

Body:
You can use global template filter in flask code and then use it in template. You can read the official documentation on custom template filter.

app.py:

from flask import Flask, render_template
app = Flask(__name__)

@app.template_filter()
def numberFormat(value):
    return format(int(value), ',d')

@app.route("/", methods=["GET"])
def home():
    products = [
        {
            "name": "mobile",
            "quantity": 3217210
        },
        {
            "name": "laptop",
            "quantity": 343217210
        },
        {
            "name": "mouse",
            "quantity": 100
        }
    ]
    return render_template("index.html", products=products)

index.html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Number format</title>
  </head>
  <body>
    <h3>Products</h3>
    <table border="1">
      <thead>
        <tr>
          <th>Name</th>
          <th>Quantity</th>
        </tr>
      </thead>
      <tbody>
        {% for product in products %}
        <tr>
          <td>{{ product.name }}</td>
          <td>{{ product.quantity | numberFormat }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </body>
</html>

Output:

You can modify the filter as per your requirements.


问:
Parse string in nodejs to an array
How can I convert following string into an array in nodejs?

```<code>"Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]"
</code>```

I tried JSON.parse, but there was an error: Unexpected token c in JSON at position 2.

Do you have any ideas?

答:
You first need to remove "Content:", and then you need to make the string json-compliant, like so.</p>

```<code>const a = '[{"id": 1, "value": 1, "number": 1}]'
</code>```

Title: Parse string in nodejs to an array

Body:
How can I convert following string into an array in nodejs?

"Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]"

I tried JSON.parse, but there was an error: Unexpected token c in JSON at position 2.

Do you have any ideas?

Body:
You first need to remove "Content:", and then you need to make the string json-compliant, like so.

const a = '[{"id": 1, "value": 1, "number": 1}]'


问:
taking 3*3 matrix input of single lineby user in python without using numpy
I am unable to make a code which can take 3x3 matrix .
Problem statement is: First line is 3x3 matrix .

I tried arr=[[int(input()) for i in range(3)] for j in range(3)]
which is getting an error.
when I wrote arr=input()
it returns :[[1, 0, 1], [0, 1, 0], [1, 0, 1]] which is completely string.

答:
Try</p>

```<code>matrix = [list(map(int,input().split())) for i in range(3)]
</code>```

Body:
Try

matrix = [list(map(int,input().split())) for i in range(3)]


问:
I have json data i need search `unique` if key exist or not
I have JSON data I need search unique if the key exists or not.

```<code>[
 {
  "key1" => []
 },
 {
  "key" => []
 },
 {
  "unique" => []
 }
]
</code>```

I can use loop but need an efficient way to check unique exist or not

答:
You'll need to iterate through the array either way.

```<code># You'll get found item or `nil`
data.find { |item| item.key?('unique') }

# You'll get `true` or `false`
data.any? { |item| item.key?('unique') }
</code>```

Btw better to use a hash as an input instead of an array:

```<code>data = {
  "key1" => [],
  "key" => [],
  "unique" => []
 }

data.key?('unique')

=> true
</code>```

Body:
I have JSON data I need search unique if the key exists or not.

[
 {
  "key1" => []
 },
 {
  "key" => []
 },
 {
  "unique" => []
 }
]

I can use loop but need an efficient way to check unique exist or not

Body:
You'll need to iterate through the array either way.

# You'll get found item or `nil`
data.find { |item| item.key?('unique') }

# You'll get `true` or `false`
data.any? { |item| item.key?('unique') }

Btw better to use a hash as an input instead of an array:

data = {
  "key1" => [],
  "key" => [],
  "unique" => []
 }

data.key?('unique')

=> true


问:
MVVM pattern basics
A very common scenario. We have:

double _H;
public double H
{
  get { return _H; }
  set
  {
    if (_H == value) return;
    _H = value;
    SomeMethod("H");
    //Inside SomeMethod's body we calculate some other properties among other things,
    //and we call their corresponding base.RaisePropertyChanged. ALSO we
    //RECALCULATE the freshly set H and we WANT to call base.RaisePropertyChanged("H")
    //to "propagate" the changed value back to the View control that called the setter
    //portion of the property in the first place!
    }
}
```

<p><strong>Answer :</strong>
Look at Jay's post. Key concept to keep from this question: <strong>Asynchronous Invocation</strong> as Jay mentioned.</p>

<p><strong>Some more details (maybe repetitive or irrelevant) :</strong> I have a NumericUpDown control and I click on it's button to change its value. The problem is that I want to recalculate the given value and see if it is permitted (validation in view-model). But I cant push back the value that is being sent from control to the set portion of the property. The first solution which came in mind is to trigger the <code>ValueChanged</code> event in the View and call <code>SomeMethod("H")</code> from there. Not good though.</p>

<p>In reality there are about 10 NumericUpDown controls. The value of each represent a dimension of a geometric shape. So, changes in one value, can alter the other dimensions. The problem arises when the calculation determines that the value just given must change also (if you understand what I mean).
Also some relevant XAML code:</p>

```<l:NumericUpDown Value="{Binding H}" Maximum="{Binding MaxSide, Mode=OneTime}"
 Grid.Column="7"/>
```

答:
You need to use the Dispatcher to either force a refresh or to raise the property change notification outside of the context of the setter (asynchronous invocation).

So, instead of

```<code>base.OnPropertyChanged("H");
</code>```

…you'd do

```<code>Action action = () => base.OnPropertyChanged("H");
Dispatcher.CurrentDispatcher.BeginInvoke(action);
</code>```

Title: MVVM pattern basics

Body:
A very common scenario. We have:

double _H;
public double H
{
  get { return _H; }
  set
  {
    if (_H == value) return;
    _H = value;
    SomeMethod("H");
    //Inside SomeMethod's body we calculate some other properties among other things,
    //and we call their corresponding base.RaisePropertyChanged. ALSO we
    //RECALCULATE the freshly set H and we WANT to call base.RaisePropertyChanged("H")
    //to "propagate" the changed value back to the View control that called the setter
    //portion of the property in the first place!
    }
}

Answer :
Look at Jay's post. Key concept to keep from this question: Asynchronous Invocation as Jay mentioned.

Some more details (maybe repetitive or irrelevant) : I have a NumericUpDown control and I click on it's button to change its value. The problem is that I want to recalculate the given value and see if it is permitted (validation in view-model). But I cant push back the value that is being sent from control to the set portion of the property. The first solution which came in mind is to trigger the ValueChanged event in the View and call SomeMethod("H") from there. Not good though.

In reality there are about 10 NumericUpDown controls. The value of each represent a dimension of a geometric shape. So, changes in one value, can alter the other dimensions. The problem arises when the calculation determines that the value just given must change also (if you understand what I mean).
Also some relevant XAML code:

<l:NumericUpDown Value="{Binding H}" Maximum="{Binding MaxSide, Mode=OneTime}"
 Grid.Column="7"/>

Body:
You need to use the Dispatcher to either force a refresh or to raise the property change notification outside of the context of the setter (asynchronous invocation).

So, instead of

base.OnPropertyChanged("H");

…you'd do

Action action = () => base.OnPropertyChanged("H");
Dispatcher.CurrentDispatcher.BeginInvoke(action);


问:
How can I change the user on Git Bash?

I want to sign out an actual user so I can sign in with another user.

What I see in Git bash is:

```<code>MINGW64 ~/Documents/NetBeansProjects/ConstructorJava (master)
git push -u origin/master
remote: Permission to Fre1234/ConstructorJava.git denied to Fre123.
Fatal: unable to access https://github.com/Fre1234/ConstructorJava.git/": The requested URL returned error: 403
</code>```

答:
For any OS

This helped me so I'll put it here, just in case.
Once you are done with adding the rsa keys for both the accounts, add a config file in your .ssh directory for both the accounts (.ssh/config)

```<code># First account
Host github.com-<FIRST_ACCOUNT_USERNAME_HERE>
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user1

# Second account
Host github.com-<SECOND_ACCOUNT_USERNAME_HERE>
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user2
</code>```

Make sure you use the correct usernames and RSA files. Next, you can open the terminal/git bash on the repository root and check which account you would be pushing from

```<code>git config user.email
</code>```

Suppose this returns the first user email and you want to push from the second user. Change the local user.name and user.email :

```<code>git config user.name "SECOND_USER"
git config user.email "SECOND_USER@example.com"
</code>```

(This won't change the global config and you can have the first user set up as the global user). Once done, you can confirm with git config user.email and it should return the email of the second user. You're all set to push to GitHub with the second user. The rest is all the same old git add , git commit and git push.
To push from the first user, change the local user.name again and follow the same steps.
Hope it helps :)

If the above steps are still not working for you, check to see if you have uploaded the RSA keys within GitHub portal. Refer to GitHub documentation:

Then, clear your ssh cached keys Reference

```<code>ssh-add -D
</code>```

Then add you 2 ssh keys

```<code>ssh-add ~/.ssh/id_rsa_user1
ssh-add ~/.ssh/id_rsa_user2
</code>```

Then type in your terminal:

```<code>ssh -T git@github.com-<SECOND_ACCOUNT_USERNAME_HERE>
</code>```

You should see the following output:

```<code>Hi <SECOND_USERNAME>! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

Then, assign the correct remote to your local repository. Make sure you put the same username as the one you gave in your .ssh/config file next to Host. In the following case git@github.com-<SECOND_ACCOUNT_USERNAME_HERE>.

```<code>git remote rm origin
git remote add origin git@github.com-<SECOND_ACCOUNT_USERNAME_HERE>:/your_username/your_repository.git
</code>```

Title: How can I change the user on Git Bash?

Body:
I want to sign out an actual user so I can sign in with another user.

What I see in Git bash is:

MINGW64 ~/Documents/NetBeansProjects/ConstructorJava (master)
git push -u origin/master
remote: Permission to Fre1234/ConstructorJava.git denied to Fre123.
Fatal: unable to access https://github.com/Fre1234/ConstructorJava.git/": The requested URL returned error: 403

Body:
For any OS

This helped me so I'll put it here, just in case.
Once you are done with adding the rsa keys for both the accounts, add a config file in your .ssh directory for both the accounts (.ssh/config)

# First account
Host github.com-<FIRST_ACCOUNT_USERNAME_HERE>
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user1

# Second account
Host github.com-<SECOND_ACCOUNT_USERNAME_HERE>
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_user2

Make sure you use the correct usernames and RSA files. Next, you can open the terminal/git bash on the repository root and check which account you would be pushing from

git config user.email

Suppose this returns the first user email and you want to push from the second user. Change the local user.name and user.email :

git config user.name "SECOND_USER"
git config user.email "SECOND_USER@example.com"

(This won't change the global config and you can have the first user set up as the global user). Once done, you can confirm with git config user.email and it should return the email of the second user. You're all set to push to GitHub with the second user. The rest is all the same old git add , git commit and git push.
To push from the first user, change the local user.name again and follow the same steps.
Hope it helps :)

If the above steps are still not working for you, check to see if you have uploaded the RSA keys within GitHub portal. Refer to GitHub documentation:

Then, clear your ssh cached keys Reference

ssh-add -D

Then add you 2 ssh keys

ssh-add ~/.ssh/id_rsa_user1
ssh-add ~/.ssh/id_rsa_user2

Then type in your terminal:

ssh -T git@github.com-<SECOND_ACCOUNT_USERNAME_HERE>

You should see the following output:

Hi <SECOND_USERNAME>! You've successfully authenticated, but GitHub does not provide shell access.

Then, assign the correct remote to your local repository. Make sure you put the same username as the one you gave in your .ssh/config file next to Host. In the following case git@github.com-<SECOND_ACCOUNT_USERNAME_HERE>.

git remote rm origin
git remote add origin git@github.com-<SECOND_ACCOUNT_USERNAME_HERE>:/your_username/your_repository.git