问:
Why it is giving me 'Cannot read property 'deleteProduct' of undefined' error react Js
I am getting an error when deleting one row in react js. error is 'Cannot read property 'deleteProduct' of undefined'. also is there any simple way to delete data from the database using custom api. below is my complete code for deleting data from the database.

Here is my code for deleting row-

```<code>import React from 'react';
import ReactDOM from 'react-dom';
export default class FetchedData extends React.Component{
  constructor(props){
    super(props);
    this.state={
      UserData:[],
      response: {}
      };
    this.headers=[
      {key:1,label:'Name'},
      {key:2,label:'Department'},
      {key:3,label:'Marks'},
    ];
    this.deleteProduct=this.deleteProduct.bind(this);
  }

  componentDidMount(){
  this.lookupInterval = setInterval(() => {
    fetch("https://www.veomit.com/test/zend/api/fetch.php")
    .then(response => {
                return response.json();
            })
    .then(result => {
                this.setState({
                    UserData:result
                })
        .catch(error => {
        console.log(
          "An error occurred while trying to fetch data from Foursquare: " +error
        );
      });
    });
  }, 500)
  }

  deleteProduct(userId) {
    const { UserData } = this.state;

    const apiUrl = 'https://www.veomit.com/test/zend/api/delete.php';
    const formData = new FormData();
    formData.append('userId', userId);

    const options = {
      method: 'POST',
      body: formData
    }

    fetch(apiUrl, options)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            response: result,
            UserData: UserData.filter(item => item.id !== userId)
          });
        },
        (error) => {
          this.setState({ error });
        }
      )
  }
  render(){
    return(
      <div>
      <table class="table table-bordered">
          <thead>
            <tr>
              {
                        this.headers.map(function(h) {
                            return (
                                <th key = {h.key}>{h.label}</th>
                            )
                        })
                        }
            </tr>
          </thead>
          <tbody>
              {
                        this.state.UserData.map(function(item, key) {
                        return (
                                <tr key = {key}>
                                  <td>{item.name}</td>
                                  <td>{item.department}</td>
                                  <td>{item.marks}</td>
                  <td><span onClick={() => this.deleteProduct(item.id)}>Delete</span></td>
                                </tr>
                            )
                        })
                    }
          </tbody>
      </table>
      </div>
    );
  }
}
</code>```

Please help me remove this error.
thanks in advance.

答:
Your mapping function is creating a new scope:

```<code>this.state.UserData.map(function(item, key) {
                    return (
                            <tr key = {key}>
                              <td>{item.name}</td>
                              <td>{item.department}</td>
                              <td>{item.marks}</td>
              <td><span onClick={() => this.deleteProduct(item.id)}>Delete</span></td>
                            </tr>
                        )
                    })
</code>```

Making it an arrow function should solve the issue:

```<code>this.state.UserData.map((item, key) => {
                    return (
                            <tr key = {key}>
                              <td>{item.name}</td>
                              <td>{item.department}</td>
                              <td>{item.marks}</td>
              <td><span onClick={() => this.deleteProduct(item.id)}>Delete</span></td>
                            </tr>
                        )
                    })
</code>```

Body:
I am getting an error when deleting one row in react js. error is 'Cannot read property 'deleteProduct' of undefined'. also is there any simple way to delete data from the database using custom api. below is my complete code for deleting data from the database.

Here is my code for deleting row-

import React from 'react';
import ReactDOM from 'react-dom';
export default class FetchedData extends React.Component{
  constructor(props){
    super(props);
    this.state={
      UserData:[],
      response: {}
      };
    this.headers=[
      {key:1,label:'Name'},
      {key:2,label:'Department'},
      {key:3,label:'Marks'},
    ];
    this.deleteProduct=this.deleteProduct.bind(this);
  }

  componentDidMount(){
  this.lookupInterval = setInterval(() => {
    fetch("https://www.veomit.com/test/zend/api/fetch.php")
    .then(response => {
                return response.json();
            })
    .then(result => {
                this.setState({
                    UserData:result
                })
        .catch(error => {
        console.log(
          "An error occurred while trying to fetch data from Foursquare: " +error
        );
      });
    });
  }, 500)
  }

  deleteProduct(userId) {
    const { UserData } = this.state;

    const apiUrl = 'https://www.veomit.com/test/zend/api/delete.php';
    const formData = new FormData();
    formData.append('userId', userId);

    const options = {
      method: 'POST',
      body: formData
    }

    fetch(apiUrl, options)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            response: result,
            UserData: UserData.filter(item => item.id !== userId)
          });
        },
        (error) => {
          this.setState({ error });
        }
      )
  }
  render(){
    return(

              {
                        this.headers.map(function(h) {
                            return (
                                {h.label}
                            )
                        })
                        }

              {
                        this.state.UserData.map(function(item, key) {
                        return (

                                  {item.name}
                                  {item.department}
                                  {item.marks}
                   this.deleteProduct(item.id)}>Delete

                            )
                        })
                    }

    );
  }
}

Please help me remove this error.
thanks in advance.

Body:
Your mapping function is creating a new scope:

this.state.UserData.map(function(item, key) {
                    return (
                            <tr key = {key}>
                              <td>{item.name}</td>
                              <td>{item.department}</td>
                              <td>{item.marks}</td>
              <td><span onClick={() => this.deleteProduct(item.id)}>Delete</span></td>
                            </tr>
                        )
                    })

Making it an arrow function should solve the issue:

this.state.UserData.map((item, key) => {
                    return (
                            <tr key = {key}>
                              <td>{item.name}</td>
                              <td>{item.department}</td>
                              <td>{item.marks}</td>
              <td><span onClick={() => this.deleteProduct(item.id)}>Delete</span></td>
                            </tr>
                        )
                    })


来源: stackexchange

问:
std::string gets corrupted/change structure when passed to a library
I am using Visual Studio 2012 for a project and a build I made myself of Log4cxx for logging purposes. Both projects are built in Debug x64 and (I believe) linked properly.

Platform toolset for both projects is Visual Studio 2012 (v110), Runtime Library is Multi-threaded Debug DLL (/MDd), Log4cxx is created and linked as a dynamic library (.dll).

Consider the following:

```<code>std::string szTestString = "Hello World!";
DOMConfigurator::configure(szTestString); // Call to Log4cxx.dll
</code>```

While debugging, just before getting in that function, this is the value of szTestString:

So far so good. Now I step into the function:

```<code>void DOMConfigurator::configure(const std::string& filename)
{
    File file(filename);
    DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository());
}
</code>```

And when looking at filename...

That's obviously not right.

If I step once forward, I get an error:

Unhandled exception at at 0x000007FEFD6FBDED in SampleProject.exe: Microsoft C++ exception: std::length_error at memory location 0x000000000030F110.

What could be causing the change in std::string interpretation?

EDIT: currently I added a wrapper to Log4cxx to take char* instead of std::string and it did the trick. The question still stands however.

答:
This problem generally occurs when library is compiled in "Release" mode and you are trying to run application in "Debug" mode.

Keep both the components i.e., DLL and Application in same mode (Either Release or Debug).

Make sure that "Code Generation" property value for both DLL and Application are same.

ContentLicense: CC BY-SA 4.0

Body:
I am using Visual Studio 2012 for a project and a build I made myself of Log4cxx for logging purposes. Both projects are built in Debug x64 and (I believe) linked properly.

Platform toolset for both projects is Visual Studio 2012 (v110), Runtime Library is Multi-threaded Debug DLL (/MDd), Log4cxx is created and linked as a dynamic library (.dll).

Consider the following:

std::string szTestString = "Hello World!";
DOMConfigurator::configure(szTestString); // Call to Log4cxx.dll

While debugging, just before getting in that function, this is the value of szTestString:

So far so good. Now I step into the function:

void DOMConfigurator::configure(const std::string& filename)
{
    File file(filename);
    DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository());
}

And when looking at filename...

That's obviously not right.

If I step once forward, I get an error:

Unhandled exception at at 0x000007FEFD6FBDED in SampleProject.exe: Microsoft C++ exception: std::length_error at memory location 0x000000000030F110.

What could be causing the change in std::string interpretation?

EDIT: currently I added a wrapper to Log4cxx to take char* instead of std::string and it did the trick. The question still stands however.


问:
React reducer that does not update the state
From a Redux tutorial I've been going through they allow you to add a place multiple times.  I changed the reducer to reject duplicates.  My question is, (see code), do I have to return the state if no updates are made or is there some other way of indicating no state is changed?</p>

```<code>function placeReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_PLACE:
        const existing = state.places.find((item) => item.value == action.payload);
        if (existing) {
            return {...state};
        }
        return {
            ...state,
            places: state.places.concat({
                key: Math.random(),
                value: action.payload
            })
        };
    default:
        return state;
  }
}
</code>```

答: Just return the state, no need to create a new copy.</p>

Body:
From a Redux tutorial I've been going through they allow you to add a place multiple times.  I changed the reducer to reject duplicates.  My question is, (see code), do I have to return the state if no updates are made or is there some other way of indicating no state is changed?

function placeReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_PLACE:
        const existing = state.places.find((item) => item.value == action.payload);
        if (existing) {
            return {...state};
        }
        return {
            ...state,
            places: state.places.concat({
                key: Math.random(),
                value: action.payload
            })
        };
    default:
        return state;
  }
}


问:
Conversion of number not match with length of datatype in SQL Server
I refer the following number with datatype bigInt.

```<code>DECLARE @Number Bigint = '269687584'
</code>```

When I convert the datatype to Varbinary(4), it returns 0x10131B20.

But when I calculate the length of the Varbinary data, it returns only 3.
I didn't know exact what wrong.

In SQL Server database, I want to write an query to convert Bigint to
Varbinary(4), but is converted as only as Varbinary(3).

Here is what I have tried:

```<code>DECLARE @Number BIGINT = '269687584'

SELECT
    @Number,
    CONVERT(VARBINARY(4), @Number),
    LEN(CONVERT(VARBINARY(4), @Number))
</code>```

答:
Use DATALENGTH instead:</p>

```<code>DECLARE @Number BIGINT ='269687584'
SELECT @Number, CONVERT(VARBINARY(4), @Number), DATALENGTH(CONVERT(VARBINARY(4), @Number))
</code>```

Body:
I refer the following number with datatype bigInt.

DECLARE @Number Bigint = '269687584'

When I convert the datatype to Varbinary(4), it returns 0x10131B20.

But when I calculate the length of the Varbinary data, it returns only 3.
I didn't know exact what wrong.

In SQL Server database, I want to write an query to convert Bigint to
Varbinary(4), but is converted as only as Varbinary(3).

Here is what I have tried:

DECLARE @Number BIGINT = '269687584'

SELECT
    @Number,
    CONVERT(VARBINARY(4), @Number),
    LEN(CONVERT(VARBINARY(4), @Number))

Body:
Use DATALENGTH instead:

DECLARE @Number BIGINT ='269687584'
SELECT @Number, CONVERT(VARBINARY(4), @Number), DATALENGTH(CONVERT(VARBINARY(4), @Number))


问:
How to determine if child component form is valid in parent component when using reactive forms
I am using Angular 5 with Reactive forms

Child component class:

```<code>export class UserEditor implements OnInit {

    public userForm: FormGroup;

...

ngOnInit() {
    this.createFormControls();
    this.createForm();
}
createFormControls() {
    this.userName = new FormControl('', [
        Validators.required,
        Validators.minLength(4)
    ]);
    this.firstName = new FormControl('', Validators.required);
    this.lastName = new FormControl('', Validators.required);
    this.email = new FormControl('', [
      Validators.required,
      Validators.pattern("[^ @]*@[^ @]*")
    ]);

}
createForm() {
 this.userForm = new FormGroup({
      userName: this.userName,
      name: new FormGroup({
        firstName: this.firstName,
        lastName: this.lastName,
      }),
      email: this.email,
    });
}
</code>```

In my parent component form I have buttons that are disabled if the above validators is not valid

In the parent component html:

```<code><button class="btn btn-sm  btn-primary" (click)="saveUser()" [disabled]="!userListChild?.userForm.valid">
</code>```

In the parent component class:

```<code>export class UserList implements OnInit {
     @ViewChild(UserEditor) userListChild: UserEditor;
</code>```

Everything works well however I get the well known error

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false

I tried the change detection solution listed in this blog but it didn't help.

https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

So I am stuck unless if I ignore the error as the app works fine with the error.

答:
It would be really simpler if you were using this library  https://github.com/cloudnc/ngx-sub-form

I've replied to a very similar answer than this one here https://stackoverflow.com/a/56375605/2398593 so I don't think it would be of any use to provide some more code than there.

Please also check the demo I've made for that answer here https://stackblitz.com/edit/so-question-angular-2-large-scale-application-forms-handling where you'll be able to see something similar as your structure

Notice the errors part? From the parent component you'll have access to it and be able to see what's wrong into your form even if you've got sub forms!

ContentLicense: CC BY-SA 3.0

Body:
I am using Angular 5 with Reactive forms

Child component class:

export class UserEditor implements OnInit {

    public userForm: FormGroup;

...

ngOnInit() {
    this.createFormControls();
    this.createForm();
}
createFormControls() {
    this.userName = new FormControl('', [
        Validators.required,
        Validators.minLength(4)
    ]);
    this.firstName = new FormControl('', Validators.required);
    this.lastName = new FormControl('', Validators.required);
    this.email = new FormControl('', [
      Validators.required,
      Validators.pattern("[^ @]*@[^ @]*")
    ]);

}
createForm() {
 this.userForm = new FormGroup({
      userName: this.userName,
      name: new FormGroup({
        firstName: this.firstName,
        lastName: this.lastName,
      }),
      email: this.email,
    });
}

In my parent component form I have buttons that are disabled if the above validators is not valid

In the parent component html:

<button class="btn btn-sm  btn-primary" (click)="saveUser()" [disabled]="!userListChild?.userForm.valid">

In the parent component class:

export class UserList implements OnInit {
     @ViewChild(UserEditor) userListChild: UserEditor;

Everything works well however I get the well known error

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false

I tried the change detection solution listed in this blog but it didn't help.

https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

So I am stuck unless if I ignore the error as the app works fine with the error.


问:
how to number sequences with the same name in bed file
I have a file bed like this.

```<code>    KQ4156  0       34      Simple_repeat   .   +
    KQ4156  35      64      Simple_repeat   .   +
    KQ4156  1759    1822    Simple_repeat   .   +
    KQ4156  1901    2059    Simple_repeat   .   -
    KQ4156  2112    2258    DNA/hAT-Charlie .   +
    KQ4156  2890    2964    Simple_repeat   .   +
    KQ4156  4085    4130    DNA/hAT-Charlie .   +
    KQ4156  5587    5619    Simple_repeat   .   +
    KQ4156  5931    5995    SINE/tRNA-Deu   .   -
</code>```

for subsequent analysis I need to distinguish the same elements. es. simple_repeats_1, simple_repeats_2, etc. and DNA/hAT-Charlie_1, DNA/hAT-Charlie_2, etc.... for all of the elements.
the script used is this:

awk 'BEGIN{OFS="\t"}{if(NR>3) {if($9=="C"){strand="-"}else{strand="+"};print $5,$6-1,$7,$11,".",strand}}' file.fa.out > file.bed

how can I modify it in order to get what I'm looking for? I thought about applying paste but I don't know how to apply it for all the sequences

答:
The awk solution using a table is the simplest:

```<code>awk -vOFS='\t' '{ seen[$4]++; $4=$4"_"seen[$4]; print; }' file
</code>```

will output:

```<code>KQ4156  0   34  Simple_repeat_1 .   +
KQ4156  35  64  Simple_repeat_2 .   +
KQ4156  1759    1822    Simple_repeat_3 .   +
KQ4156  1901    2059    Simple_repeat_4 .   -
KQ4156  2112    2258    DNA/hAT-Charlie_1   .   +
KQ4156  2890    2964    Simple_repeat_5 .   +
KQ4156  4085    4130    DNA/hAT-Charlie_2   .   +
KQ4156  5587    5619    Simple_repeat_6 .   +
KQ4156  5931    5995    SINE/tRNA-Deu_1 .   -
</code>```

Body:
I have a file bed like this.

    KQ4156  0       34      Simple_repeat   .   +
    KQ4156  35      64      Simple_repeat   .   +
    KQ4156  1759    1822    Simple_repeat   .   +
    KQ4156  1901    2059    Simple_repeat   .   -
    KQ4156  2112    2258    DNA/hAT-Charlie .   +
    KQ4156  2890    2964    Simple_repeat   .   +
    KQ4156  4085    4130    DNA/hAT-Charlie .   +
    KQ4156  5587    5619    Simple_repeat   .   +
    KQ4156  5931    5995    SINE/tRNA-Deu   .   -

for subsequent analysis I need to distinguish the same elements. es. simple_repeats_1, simple_repeats_2, etc. and DNA/hAT-Charlie_1, DNA/hAT-Charlie_2, etc.... for all of the elements.
the script used is this:

awk 'BEGIN{OFS="\t"}{if(NR>3) {if($9=="C"){strand="-"}else{strand="+"};print $5,$6-1,$7,$11,".",strand}}' file.fa.out > file.bed

how can I modify it in order to get what I'm looking for? I thought about applying paste but I don't know how to apply it for all the sequences

Body:
The awk solution using a table is the simplest:

awk -vOFS='\t' '{ seen[$4]++; $4=$4"_"seen[$4]; print; }' file

will output:

KQ4156  0   34  Simple_repeat_1 .   +
KQ4156  35  64  Simple_repeat_2 .   +
KQ4156  1759    1822    Simple_repeat_3 .   +
KQ4156  1901    2059    Simple_repeat_4 .   -
KQ4156  2112    2258    DNA/hAT-Charlie_1   .   +
KQ4156  2890    2964    Simple_repeat_5 .   +
KQ4156  4085    4130    DNA/hAT-Charlie_2   .   +
KQ4156  5587    5619    Simple_repeat_6 .   +
KQ4156  5931    5995    SINE/tRNA-Deu_1 .   -


问:
Get count of array objects belonging to a partical ID in JavaScript/Node js
I have an array of arrays like this:

```<code>var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]
</code>```

The ID's in the above array (2,3 and 4) come dynamically from a server response.
I need to count the number of entries for a particular ID.
I'm not able to figure out how to loop over this array to get the expected output.
The expected output is:

```<code>[{"ID" : "4", Count : "1"},{"ID" : "3", Count : "2"},{"ID" : "2",Count : "3"}]
</code>```

Note that the output is in the ascending order of the Count.

This is what I tried :

```<code>var temp1 = [];
                var temp2 = [];
                var temp3 = [];
                for(var i = 0; i < array.length; ++i){
                     if(array[i][0] == 2){
                        temp1.push(array[i])
                     }
                     if(array[i][0] == 1){
                        temp2.push(array[i])
                     }
                     if(array[i][0] == 3){
                        temp3.push(array[i])
                     }

                }

 var output = [{
                    ID: "2",
                    Count: temp1.length,
                },
                {
                    ID: "1",
                    Count: temp2.length,
                },
                {
                    ID: "3",
                    Count: temp3.length
                }]

console.log(output)
</code>```

I believe the way I'm doing it is not the best approach if the data is dynamic.
How do I do it in a better way?

答:
If you want to stick to your for loop an easy way is to check for each item if it's already included in the output, and if so to increment the count, as such:

```<code>var array = [
[ '2','Yes'],
[ '2','Yes'],
[ '2','Yes'],
[ '3','Yes'],
[ '3','Yes'],
[ '4','Yes'],
];

var output = [];

for(var i = 0; i < array.length; ++i) {
  if(!output.find(item => item.ID === array[i][0])){
    output.push({'ID': array[i][0], 'Count': 1});
  } else {
    output.find(item => item.ID === array[i][0]).Count += 1;
  }
}
output.sort( (a,b) => a.Count - b.Count)

console.log(output);
</code>```

Body:
I have an array of arrays like this:

var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]

The ID's in the above array (2,3 and 4) come dynamically from a server response.
I need to count the number of entries for a particular ID.
I'm not able to figure out how to loop over this array to get the expected output.
The expected output is:

[{"ID" : "4", Count : "1"},{"ID" : "3", Count : "2"},{"ID" : "2",Count : "3"}]

Note that the output is in the ascending order of the Count.

This is what I tried :

var temp1 = [];
                var temp2 = [];
                var temp3 = [];
                for(var i = 0; i < array.length; ++i){
                     if(array[i][0] == 2){
                        temp1.push(array[i])
                     }
                     if(array[i][0] == 1){
                        temp2.push(array[i])
                     }
                     if(array[i][0] == 3){
                        temp3.push(array[i])
                     }

                }

 var output = [{
                    ID: "2",
                    Count: temp1.length,
                },
                {
                    ID: "1",
                    Count: temp2.length,
                },
                {
                    ID: "3",
                    Count: temp3.length
                }]

console.log(output)

I believe the way I'm doing it is not the best approach if the data is dynamic.
How do I do it in a better way?

Body:
If you want to stick to your for loop an easy way is to check for each item if it's already included in the output, and if so to increment the count, as such:

var array = [
[ '2','Yes'],
[ '2','Yes'],
[ '2','Yes'],
[ '3','Yes'],
[ '3','Yes'],
[ '4','Yes'],
];

var output = [];

for(var i = 0; i < array.length; ++i) {
  if(!output.find(item => item.ID === array[i][0])){
    output.push({'ID': array[i][0], 'Count': 1});
  } else {
    output.find(item => item.ID === array[i][0]).Count += 1;
  }
}
output.sort( (a,b) => a.Count - b.Count)

console.log(output);


答:
This is probably due to losing context here:

```<code>{
                        this.state.UserData.map(function(item, key) {
                        return (
                                <tr key = {key}>
                                  <td>{item.name}</td>
                                  <td>{item.department}</td>
                                  <td>{item.marks}</td>
                  <td><span onClick={() => this.deleteProduct(item.id)}>Delete</span></td>
                                </tr>
                            )
                        })
                    }
</code>```

Change the function to an arrow function to autobind the callback:

```<code>{
                        this.state.UserData.map((item, key) => {
                        return (
                                <tr key = {key}>
                                  <td>{item.name}</td>
                                  <td>{item.department}</td>
                                  <td>{item.marks}</td>
                  <td><span onClick={() => this.deleteProduct(item.id)}>Delete</span></td>
                                </tr>
                            )
                        })
                    }
</code>```

Title: Why it is giving me 'Cannot read property 'deleteProduct' of undefined' error react Js

Body:
This is probably due to losing context here:

{
                        this.state.UserData.map(function(item, key) {
                        return (
                                <tr key = {key}>
                                  <td>{item.name}</td>
                                  <td>{item.department}</td>
                                  <td>{item.marks}</td>
                  <td><span onClick={() => this.deleteProduct(item.id)}>Delete</span></td>
                                </tr>
                            )
                        })
                    }

Change the function to an arrow function to autobind the callback:

{
                        this.state.UserData.map((item, key) => {
                        return (
                                <tr key = {key}>
                                  <td>{item.name}</td>
                                  <td>{item.department}</td>
                                  <td>{item.marks}</td>
                  <td><span onClick={() => this.deleteProduct(item.id)}>Delete</span></td>
                                </tr>
                            )
                        })
                    }


问:
How to silence 'The last statement should return a value' warning?
Sun Studio 12.1 prints the warning

```<code>Warning: The last statement should return a value.
</code>```

frequently for functions like that:

```<code>int f()
{
  /* some code that may return */

  // if we end up here, something is broken
  throw std::runtime_error("Error ...");
}
</code>```

It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like

```<code>// Silence a compiler warning
return 42;
</code>```

at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.

What is the recommended way to silence such a warning?

答:
Can you reorganize the code in the function in such a way (hopefully more logical as well) that the normal path happens at the end of the function so that a return can be used, and the exceptional path happens earlier, NOT as the last statement?

EDIT: If reorganizing the function really doesn't make sense, you can always just put a dummy return 0; with a comment. It's better to squelch the warning that way than more globally.

If you really want to quiet the warning permanently, you can use #pragma error_messages (off, wnoretvalue) but note that the warning really is useful most of the time so I absolutely don't suggest turning it off. You can use the on version of the pragma to re-enable the warning after the function, but the compiler will still emit the warning if your function is ever inlined. If you put the function in its own source file and use the pragma that should shush the warning relatively safely though, since it can't affect other translation units.

Another really wacky possibility is to switch to g++. Unless you're compiling for SPARC g++ may actually generate better code than Sun studio.

Body:
Sun Studio 12.1 prints the warning

Warning: The last statement should return a value.

frequently for functions like that:

int f()
{
  /* some code that may return */

  // if we end up here, something is broken
  throw std::runtime_error("Error ...");
}

It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like

// Silence a compiler warning
return 42;

at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.

What is the recommended way to silence such a warning?


问:
apple In-App Purchase server call back JSON does not contain a “latest_receipt_info” key?
before 2019-05-29 the callback json have  “latest_receipt_info” key, but today the callback json does have any receipt info  example:</p>

```<code>    {
  "auto_renew_product_id": "com.xx.xx",
  "notification_type": "DID_CHANGE_RENEWAL_STATUS",
  "environment": "PROD",
  "password": "xxxxx",
  "auto_renew_status_change_date_ms": "1559178490000",
  "auto_renew_status_change_date_pst": "2019-05-29 18:08:10 America/Los_Angeles",
  "auto_renew_status_change_date": "2019-05-30 01:08:10 Etc/GMT",
  "auto_renew_status": "false"
}
</code>```

答:
I've started receiving these kind of notifications yesterday too, since about 2019-05-29 21:00 UTC, and it looks like some kind of malfunction, as they are totally useless without receipt or other identifying info. I've been receiving them for about 13 hours and now I see that normal notifications are starting to appear (since 2019-05-30 10:00 UTC).

So I think that was some issue at Apple, I hope it's been resolved.

Body:
before 2019-05-29 the callback json have  “latest_receipt_info” key, but today the callback json does have any receipt info  example:

    {
  "auto_renew_product_id": "com.xx.xx",
  "notification_type": "DID_CHANGE_RENEWAL_STATUS",
  "environment": "PROD",
  "password": "xxxxx",
  "auto_renew_status_change_date_ms": "1559178490000",
  "auto_renew_status_change_date_pst": "2019-05-29 18:08:10 America/Los_Angeles",
  "auto_renew_status_change_date": "2019-05-30 01:08:10 Etc/GMT",
  "auto_renew_status": "false"
}


问:
Angular 7 popover loading
I am using fabricjs to load image and textcontents.

I have many textcontents on canvas with fabricjs.

now on click of textcontents of fabricjs I want to open Angular 7 popover may be (ngbPopover).

how to open that on click of textcontents, like we are opening dialogbox?

because I can not inject popover config anywhere in fabricjs.

答:
I had similar functionality to do but I found another shortcut way in doing it so.

On click of the text, object read the object by using

this.canvas.on('object:selected', (e) => {this.objectSelected(e)});

Then initally makesure that the textbox/popover is hidden

On click of the object read the selected object by:

var absCoords = this.canvas.getActiveObject();

When you read the active object there are things that you will have to take care

unhide the textbox/popover

get absCoords.left and absCoords.top and set it to the textbox.

This is one of the workarounds which helped to solve it.

Title: Angular 7 popover loading


问:
Is there any algorithm whose time-complexity is O(n^3) for Maximum Sum Sublist?
When I read the answer for the former question! on stack overflow, it said that it was possible to solve Maximum Sum Sublist for O(n).

And I also wrote the code whose computational complexity was O(n^2) .

However, I heard that there is algorithm to solve  Maximum Sum Sublist for O(n^3).

If you know it, I would appreciate if you could share it with me.

The code for O(n)

```<code>def mssl(l):
    best = cur = 0
    for i in l:
        cur = max(cur + i, 0)
        best = max(best, cur)
    return best
</code>```

The code for O(n^2)

```<code>def solution(A):
    start = None
    end = None
    max_total = 0

    for i in range(len(A)):
        for j in range(i, len(A)):
            tmp = sum(A[i:j+1])
            if max_total < tmp:
                max_total = tmp
                start = i
                end = j

    return max_total, start, end

if __name__ == '__main__':
    A = [18, -10, 30, 23, -26]
    ans = solution(A)
    print(ans)
</code>```

I would like to know any algorithm to solve Maximum Sum Sublist for O(n^3).

答:
```<code>A[i:j+1]
</code>```

This part copies j + 1 - i elements.

```<code>for j in range(i, len(A)):
</code>```

The sum of j + 1 − i for j from i to n − 1 (n = len(A)) inclusive is:

the sum of j in the same range, which is

the sum of j for j from 1 to n − 1: (n − 1)n / 2 = n²/2 − n/2

minus the sum of j for j from 1 to i − 1: (i − 1)i / 2 = i²/2 − i/2

plus the sum of 1 in the same range, which is 1(n − i) = n − i

plus the sum of −i in the same range, which is −i(n − i) = −in + i²

Put it all together and you get n²/2 − n/2 + i²/2 − i/2 + n − i − in + i² = n²/2 + n/2 + 3/2 i² − (n + 3/2) i copies for the j loop.

```<code>for i in range(len(A)):
</code>```

The sum of n²/2 + n/2 + 3/2 i² − (n + 3/2) i for i from 0 to l − 1 is:

the sum of n²/2 + n/2: (n²/2 + n/2)n = n³/2 + n²/2

plus 3/2 the sum of i²: 3/2 (n − 1)(n − 1 + 1)(2(n − 1) + 1)/6 = (n − 1)(n)(2n + 1)/4 = n/4 (2n² − 2i + n − 1) = n³/2 − n²/4 − n/4

minus (n + 3/2) times the sum of i: (n + 3/2)(n − 1)n/2 = (n² + 3/2 n − n − 3/2)n/2 = n³/2 + n²/4 − 3n/4

which comes to n³/2 + n²/2 + n³/2 − n²/4 − n/4 − n³/2 − n²/4 + 3n/4 = n³/2 + n/2 copies, for a typical time complexity measurement of O(n^3), not O(n^2).

(Sanity check: n³ + n/2 is always a whole number.)

Body:
When I read the answer for the former question! on stack overflow, it said that it was possible to solve Maximum Sum Sublist for O(n).

And I also wrote the code whose computational complexity was O(n^2) .

However, I heard that there is algorithm to solve  Maximum Sum Sublist for O(n^3).

If you know it, I would appreciate if you could share it with me.

The code for O(n)

def mssl(l):
    best = cur = 0
    for i in l:
        cur = max(cur + i, 0)
        best = max(best, cur)
    return best

The code for O(n^2)

def solution(A):
    start = None
    end = None
    max_total = 0

    for i in range(len(A)):
        for j in range(i, len(A)):
            tmp = sum(A[i:j+1])
            if max_total < tmp:
                max_total = tmp
                start = i
                end = j

    return max_total, start, end

if __name__ == '__main__':
    A = [18, -10, 30, 23, -26]
    ans = solution(A)
    print(ans)

I would like to know any algorithm to solve Maximum Sum Sublist for O(n^3).

Body:
A[i:j+1]

This part copies j + 1 - i elements.

for j in range(i, len(A)):

The sum of j + 1 − i for j from i to n − 1 (n = len(A)) inclusive is:

the sum of j in the same range, which is

the sum of j for j from 1 to n − 1: (n − 1)n / 2 = n²/2 − n/2

minus the sum of j for j from 1 to i − 1: (i − 1)i / 2 = i²/2 − i/2

plus the sum of 1 in the same range, which is 1(n − i) = n − i

plus the sum of −i in the same range, which is −i(n − i) = −in + i²

Put it all together and you get n²/2 − n/2 + i²/2 − i/2 + n − i − in + i² = n²/2 + n/2 + 3/2 i² − (n + 3/2) i copies for the j loop.

for i in range(len(A)):

The sum of n²/2 + n/2 + 3/2 i² − (n + 3/2) i for i from 0 to l − 1 is:

the sum of n²/2 + n/2: (n²/2 + n/2)n = n³/2 + n²/2

plus 3/2 the sum of i²: 3/2 (n − 1)(n − 1 + 1)(2(n − 1) + 1)/6 = (n − 1)(n)(2n + 1)/4 = n/4 (2n² − 2i + n − 1) = n³/2 − n²/4 − n/4

minus (n + 3/2) times the sum of i: (n + 3/2)(n − 1)n/2 = (n² + 3/2 n − n − 3/2)n/2 = n³/2 + n²/4 − 3n/4

which comes to n³/2 + n²/2 + n³/2 − n²/4 − n/4 − n³/2 − n²/4 + 3n/4 = n³/2 + n/2 copies, for a typical time complexity measurement of O(n^3), not O(n^2).

(Sanity check: n³ + n/2 is always a whole number.)


问:
Xamarin Forms Collection view ItemsSource Binding not updating the UI
Xamarin.Forms 4.0 collection view ItemsSource binding is not working as expected if I set the binding in code behind. The items are displayed based on the initial value of the source collection but, the UI is not updating when the source collection is updated. Same is working if I set the binding in xaml.

Code behind:

```<code>    public MainPage()
    {
        this.InitializeComponent();
        this.BindingContext = this.mainViewModel = new MainViewModel();

        CollectionView courseCollectionView = new CollectionView
        {
            ItemSizingStrategy = ItemSizingStrategy.MeasureFirstItem,
            ItemTemplate = new DataTemplate(typeof(ItemView))
        };

     courseCollectionView.SetBinding(CollectionView.ItemsSourceProperty,
     new Binding() { Source = this.mainViewModel.CountryNames, Mode =
     BindingMode.TwoWay });

     courseCollectionView.ItemsLayout = new GridItemsLayout(4,
      ItemsLayoutOrientation.Vertical);

        this.CoursesStack.Children.Clear();
        this.CoursesStack.Children.Add(courseCollectionView);

    }
</code>```

View Model Property which is using for ItemsSource Binding:

```<code>   ObservableCollection<Country> countryNames;

    public ObservableCollection<Country> CountryNames
    {
        get => this.countryNames;
        set
        {
            this.countryNames = value;
            RaisePropertyChanged("CountryNames");
        }
    }
</code>```

Expected: View should be updated as per the changes made to the ObsevableCollection (add/delete items from collection) which is bound to the ItemsSource Property.

Actual: View is not updated with changes to the ObservableCollection.

答:
About updating UI when using CollectionView, I do one sample that you can take a look:

```<code>public partial class MainPage : ContentPage
{
    public mainvidemodel viewmodel { get; set; }
    public MainPage()
    {
        InitializeComponent();
        viewmodel = new mainvidemodel();
        this.BindingContext = viewmodel;

        CollectionView collectionView = new CollectionView();

        collectionView.SetBinding(ItemsView.ItemsSourceProperty, "countries");

        collectionView.ItemTemplate = new DataTemplate(() =>
        {
            StackLayout stacklayout = new StackLayout();

            Label label1 = new Label();
            label1.SetBinding(Label.TextProperty,"Id");

            Label label2 = new Label();
            label2.SetBinding(Label.TextProperty, "Name");

            Label label3 = new Label();
            label3.SetBinding(Label.TextProperty, "caption");

            stacklayout.Children.Add(label1);
            stacklayout.Children.Add(label2);

            stacklayout.Children.Add(label3);
            return stacklayout;

        });
        Button btn = new Button() { Text = "btn", WidthRequest = 200, HeightRequest = 50 };
        btn.Clicked += Btn_Clicked;
        stacklayout1.Children.Add(collectionView);
        stacklayout1.Children.Add(btn);

    }

    private void Btn_Clicked(object sender, EventArgs e)
    {
        viewmodel.countries.Add(new Country()  { Id = 8, Name = "country8", caption = "caption 8" });
    }
}
public class mainvidemodel
{
    public ObservableCollection<Country> countries { get; set; }
    public mainvidemodel()
    {
        countries = new ObservableCollection<Country>()
        {
            new Country(){Id=1,Name="country1",caption="caption 1"},
            new Country(){Id=2,Name="country2",caption="caption 2"},
            new Country(){Id=3,Name="country3",caption="caption 3"},
            new Country(){Id=4,Name="country4",caption="caption 4"},
            new Country(){Id=5,Name="country5",caption="caption 5"},
            new Country(){Id=6,Name="country6",caption="caption 6"},
            new Country(){Id=7,Name="country7",caption="caption 7"},

        };

    }
}
public class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string caption { get; set; }
}
</code>```

Body:
Xamarin.Forms 4.0 collection view ItemsSource binding is not working as expected if I set the binding in code behind. The items are displayed based on the initial value of the source collection but, the UI is not updating when the source collection is updated. Same is working if I set the binding in xaml.

Code behind:

    public MainPage()
    {
        this.InitializeComponent();
        this.BindingContext = this.mainViewModel = new MainViewModel();

        CollectionView courseCollectionView = new CollectionView
        {
            ItemSizingStrategy = ItemSizingStrategy.MeasureFirstItem,
            ItemTemplate = new DataTemplate(typeof(ItemView))
        };

     courseCollectionView.SetBinding(CollectionView.ItemsSourceProperty,
     new Binding() { Source = this.mainViewModel.CountryNames, Mode =
     BindingMode.TwoWay });

     courseCollectionView.ItemsLayout = new GridItemsLayout(4,
      ItemsLayoutOrientation.Vertical);

        this.CoursesStack.Children.Clear();
        this.CoursesStack.Children.Add(courseCollectionView);

    }

View Model Property which is using for ItemsSource Binding:

   ObservableCollection<Country> countryNames;

    public ObservableCollection<Country> CountryNames
    {
        get => this.countryNames;
        set
        {
            this.countryNames = value;
            RaisePropertyChanged("CountryNames");
        }
    }

Expected: View should be updated as per the changes made to the ObsevableCollection (add/delete items from collection) which is bound to the ItemsSource Property.

Actual: View is not updated with changes to the ObservableCollection.

Body:
About updating UI when using CollectionView, I do one sample that you can take a look:

public partial class MainPage : ContentPage
{
    public mainvidemodel viewmodel { get; set; }
    public MainPage()
    {
        InitializeComponent();
        viewmodel = new mainvidemodel();
        this.BindingContext = viewmodel;

        CollectionView collectionView = new CollectionView();

        collectionView.SetBinding(ItemsView.ItemsSourceProperty, "countries");

        collectionView.ItemTemplate = new DataTemplate(() =>
        {
            StackLayout stacklayout = new StackLayout();

            Label label1 = new Label();
            label1.SetBinding(Label.TextProperty,"Id");

            Label label2 = new Label();
            label2.SetBinding(Label.TextProperty, "Name");

            Label label3 = new Label();
            label3.SetBinding(Label.TextProperty, "caption");

            stacklayout.Children.Add(label1);
            stacklayout.Children.Add(label2);

            stacklayout.Children.Add(label3);
            return stacklayout;

        });
        Button btn = new Button() { Text = "btn", WidthRequest = 200, HeightRequest = 50 };
        btn.Clicked += Btn_Clicked;
        stacklayout1.Children.Add(collectionView);
        stacklayout1.Children.Add(btn);

    }

    private void Btn_Clicked(object sender, EventArgs e)
    {
        viewmodel.countries.Add(new Country()  { Id = 8, Name = "country8", caption = "caption 8" });
    }
}
public class mainvidemodel
{
    public ObservableCollection<Country> countries { get; set; }
    public mainvidemodel()
    {
        countries = new ObservableCollection<Country>()
        {
            new Country(){Id=1,Name="country1",caption="caption 1"},
            new Country(){Id=2,Name="country2",caption="caption 2"},
            new Country(){Id=3,Name="country3",caption="caption 3"},
            new Country(){Id=4,Name="country4",caption="caption 4"},
            new Country(){Id=5,Name="country5",caption="caption 5"},
            new Country(){Id=6,Name="country6",caption="caption 6"},
            new Country(){Id=7,Name="country7",caption="caption 7"},

        };

    }
}
public class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string caption { get; set; }
}


问:
where is the swagger spec file kept?
So I am building a Rest API and have used a swagger YAML file to define the API.

I use the swagger editor to view the spec but how do I host / make it available for everyone in our company to browse ?

Does the swagger get bundled with the actual deployed code and then it is accessible ?

答: You will need to host it somewhere. Either simply as a downloadable file, or embedded in an application such as Swagger UI.</p>

Title: where is the swagger spec file kept?


问:
No agent found in pool Hosted which satisfies the specified demands
Visual Studio Online does not queue in my private agent pool and defaults to the Hosted pool instead

I have a private build agent installed on my local machine in a Linux container, running against an agent pool, "MyBuildPool", on VSTS/Visual Studio Online.

The agent is online (up and running) on VSTS web portal (SUCCESS!)

When I queue a build, I select my build pool "MyBuildPool".

For diagnostic purposes, I have a demand in place to find the Agent.Name (which is the hash of the container i.e. c5f5044d043a) (Note: If I remove the demand, I get the same incorrect behaviour)

VSTS insists upon queueing my build on the Hosted pool! (FAIL!)

Any ideas?

Many Thanks

```<code>No agent found in pool **Hosted** which satisfies the specified demands:
     Agent.Name -equals c5f5044d043a
     Agent.Version -gtVersion 2.115.0
</code>```

答:
In my case, I had added the system variable VSTS_HTTP_TIMEOUT and VSTS_HTTP_RETRY in agent machine and it started failing with the above error.

After removing the above system variable from my VSTS agent machine, and restarting the machine, started working fine.

Body:
Visual Studio Online does not queue in my private agent pool and defaults to the Hosted pool instead

I have a private build agent installed on my local machine in a Linux container, running against an agent pool, "MyBuildPool", on VSTS/Visual Studio Online.

The agent is online (up and running) on VSTS web portal (SUCCESS!)

When I queue a build, I select my build pool "MyBuildPool".

For diagnostic purposes, I have a demand in place to find the Agent.Name (which is the hash of the container i.e. c5f5044d043a) (Note: If I remove the demand, I get the same incorrect behaviour)

VSTS insists upon queueing my build on the Hosted pool! (FAIL!)

Any ideas?

Many Thanks

No agent found in pool **Hosted** which satisfies the specified demands:
     Agent.Name -equals c5f5044d043a
     Agent.Version -gtVersion 2.115.0


问:
Passing a predicate as a parameter c#
I recently did an assessment from a company that had a case where they wanted to set up a predicate as an input parameter to a method.  Have little to no experience with this I've been researching it on my own.  The code looks like:

```<code>using System;

public interface IBird
{
    Egg Lay();
}

public class Chicken : IBird
{
    public Chicken()
    {
    }

    public void EggLay()
    {
    }

    public Egg Lay()
    {
        return new Egg();
    }
}

public class Egg
{
    public Egg(Func<IBird> createBird)
    {
        throw new NotImplementedException("Waiting to be implemented.");
    }

    public IBird Hatch()
    {
        throw new NotImplementedException("Waiting to be implemented.");
    }
}

public class Program
{
    public static void Main(string[] args)
    {
//      var chicken1 = new Chicken();
//      var egg = chicken1.Lay();
//      var childChicken = egg.Hatch();
    }
}
</code>```

My question is what is the Egg function expecting and why?

I've already seen this answer and this answer and this answer but it's not making any sense still. It's academic at this point but I really want to understand.

答:
Thanks for this example.
You can implement the singleton pattern so that the bird can hatch only once by modifying the Egg class as following:</p>

```<code>    public class Egg
{
    private readonly Func<IBird> _createBird;
    private IBird _Bird = null;

    public Egg(Func<IBird> createBird)
    {
        _createBird = createBird;
    }

    public IBird Hatch()
    {
        if (_Bird == null)
        {
            _Bird = _createBird();
        }

        return _Bird;
    }
}
</code>```

Title: Passing a predicate as a parameter c#

Body:
I recently did an assessment from a company that had a case where they wanted to set up a predicate as an input parameter to a method.  Have little to no experience with this I've been researching it on my own.  The code looks like:

using System;

public interface IBird
{
    Egg Lay();
}

public class Chicken : IBird
{
    public Chicken()
    {
    }

    public void EggLay()
    {
    }

    public Egg Lay()
    {
        return new Egg();
    }
}

public class Egg
{
    public Egg(Func<IBird> createBird)
    {
        throw new NotImplementedException("Waiting to be implemented.");
    }

    public IBird Hatch()
    {
        throw new NotImplementedException("Waiting to be implemented.");
    }
}

public class Program
{
    public static void Main(string[] args)
    {
//      var chicken1 = new Chicken();
//      var egg = chicken1.Lay();
//      var childChicken = egg.Hatch();
    }
}

My question is what is the Egg function expecting and why?

I've already seen this answer and this answer and this answer but it's not making any sense still. It's academic at this point but I really want to understand.

Body:
Thanks for this example.
You can implement the singleton pattern so that the bird can hatch only once by modifying the Egg class as following:

    public class Egg
{
    private readonly Func<IBird> _createBird;
    private IBird _Bird = null;

    public Egg(Func<IBird> createBird)
    {
        _createBird = createBird;
    }

    public IBird Hatch()
    {
        if (_Bird == null)
        {
            _Bird = _createBird();
        }

        return _Bird;
    }
}


问:
log4j2 isThreadContextMapInheritable property usage
I am trying to log events of a Java application to separate log files based on a key set to the ThreadContext. But my key is not reaching the child thread (created on MouseEvent) even after setting "log4j2.isThreadContextMapInheritable" to "true" in system properties. Someone please help me to get this resolved.

My main method:

```<code>public class Application {
static {
    System.setProperty("log4j2.isThreadContextMapInheritable","true");
}

private final static Logger LOGGER = LogManager.getLogger(Application.class);

public static void main(String[] args) throws Exception
{
    ThreadContext.put("cfg","RLS");
    LOGGER.info("New window opening!!!"+ThreadContext.get("cfg"));
    newWindow();
}

private static void newWindow() throws Exception {
    ButtonFrame buttonFrame = new ButtonFrame("Button Demo");
    buttonFrame.setSize( 350, 275 );
    buttonFrame.setVisible( true );
}
</code>```

}

ButtonFrame class:

```<code>public class ButtonFrame extends JFrame{
private final static Logger LOGGER = LogManager.getLogger(NewWindow.class);
JButton bChange;
JFrame frame = new JFrame("Our JButton listener example");

  public ButtonFrame(String title)
  {
    super( title );
    setLayout( new FlowLayout() );
    bChange = new JButton("Click Me!");
      bChange.addMouseListener(new MouseListener() {
          @Override
          public void mouseClicked(MouseEvent e) {
              try {
                  LOGGER.info("Mouse clicked!!!"+ThreadContext.get("cfg"));
                  JDialog d = new JDialog(frame, "HI", true);
                  d.setLocationRelativeTo(frame);
                  d.setVisible(true);
              } catch (Exception e1) {
                  e1.printStackTrace();
              }
          }

          @Override
          public void mousePressed(MouseEvent e) {}

          @Override
          public void mouseReleased(MouseEvent e) {}

          @Override
          public void mouseEntered(MouseEvent e) {}

          @Override
          public void mouseExited(MouseEvent e) {}
      });
    add( bChange );
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  }
</code>```

}

log4j2.properties file:

```<code>appenders = rls,otr,routing

appender.rls.type = RollingFile
appender.rls.name = RollingFile_Rls
appender.rls.fileName = D:\\RLS\\rls_%d{MMdd}.log
appender.rls.filePattern = D:\\RLS\\rls_%d{MMdd}.log
appender.rls.layout.type = PatternLayout
appender.rls.layout.pattern = %d{ABSOLUTE} %level{length=1}
%markerSimpleName [%C{1}:%L] %m%n
appender.rls.policies.type = Policies
appender.rls.policies.time.type = TimeBasedTriggeringPolicy
appender.rls.policies.time.interval = 1
appender.rls.policies.time.modulate = true
appender.rls.policies.size.type = SizeBasedTriggeringPolicy
appender.rls.policies.size.size = 100MB
appender.rls.strategy.type = DefaultRolloverStrategy
appender.rls.strategy.max = 5
appender.otr.type = RollingFile
appender.otr.name = RollingFile_Otr
appender.otr.fileName = D:\\RLS\\otr_%d{MMdd}.log
appender.otr.filePattern = D:\\RLS\\otr_%d{MMdd}.log
appender.otr.layout.type = PatternLayout
appender.otr.layout.pattern = %d{ABSOLUTE} %level{length=1}
%markerSimpleName [%C{1}:%L] %m%n
appender.otr.policies.type = Policies
appender.otr.policies.time.type = TimeBasedTriggeringPolicy
appender.otr.policies.time.interval = 1
appender.otr.policies.time.modulate = true
appender.otr.policies.size.type = SizeBasedTriggeringPolicy
appender.otr.policies.size.size = 100MB
appender.otr.strategy.type = DefaultRolloverStrategy
appender.otr.strategy.max = 5

appender.routing.type = Routing
appender.routing.name = Route_Finder
appender.routing.routes.type = Routes
appender.routing.routes.pattern = $${ctx:cfg}
appender.routing.routes.route1.type = Route
appender.routing.routes.route1.ref = RollingFile_Rls
appender.routing.routes.route1.key = RLS
appender.routing.routes.route2.type = Route
appender.routing.routes.route2.ref = RollingFile_Otr
appender.routing.routes.route2.key = $${ctx:cfg}

loggers = rls,otr

logger.rls.name = logging
logger.rls.level = info
logger.rls.additivity = false
logger.rls.appenderRefs=rls
logger.rls.appenderRef.rls.ref = Route_Finder

logger.rls.name = logging
logger.rls.level = info
logger.rls.additivity = false
logger.rls.appenderRefs=rls
logger.rls.appenderRef.rls.ref = Route_Finder

logger.otr.name = other
logger.otr.level = info
logger.otr.additivity = false
logger.otr.appenderRefs=otr
logger.otr.appenderRef.otr.ref = Route_Finder

rootLogger.level = trace
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = stdout
</code>```

答:
You can put log4j2.component.properties file in the classpath to control various aspects of Log4j 2 behavior.

For example content of log4j2.component.properties:

```<code># https://logging.apache.org/log4j/2.x/manual/configuration.html#SystemProperties

# If true use an InheritableThreadLocal to implement the ThreadContext map.
# Otherwise, use a plain ThreadLocal.
# (Maybe ignored if a custom ThreadContext map is specified.)
# Default is false

# Modern 2.10+
log4j2.isThreadContextMapInheritable=true

# Legacy for pre-2.10
isThreadContextMapInheritable=true
</code>```

This has priority over system properties, but it can be overridden by environment variable LOG4J_IS_THREAD_CONTEXT_MAP_INHERITABLE as described in the
documentation.

Body:
I am trying to log events of a Java application to separate log files based on a key set to the ThreadContext. But my key is not reaching the child thread (created on MouseEvent) even after setting "log4j2.isThreadContextMapInheritable" to "true" in system properties. Someone please help me to get this resolved.

My main method:

public class Application {
static {
    System.setProperty("log4j2.isThreadContextMapInheritable","true");
}

private final static Logger LOGGER = LogManager.getLogger(Application.class);

public static void main(String[] args) throws Exception
{
    ThreadContext.put("cfg","RLS");
    LOGGER.info("New window opening!!!"+ThreadContext.get("cfg"));
    newWindow();
}

private static void newWindow() throws Exception {
    ButtonFrame buttonFrame = new ButtonFrame("Button Demo");
    buttonFrame.setSize( 350, 275 );
    buttonFrame.setVisible( true );
}

}

ButtonFrame class:

public class ButtonFrame extends JFrame{
private final static Logger LOGGER = LogManager.getLogger(NewWindow.class);
JButton bChange;
JFrame frame = new JFrame("Our JButton listener example");

  public ButtonFrame(String title)
  {
    super( title );
    setLayout( new FlowLayout() );
    bChange = new JButton("Click Me!");
      bChange.addMouseListener(new MouseListener() {
          @Override
          public void mouseClicked(MouseEvent e) {
              try {
                  LOGGER.info("Mouse clicked!!!"+ThreadContext.get("cfg"));
                  JDialog d = new JDialog(frame, "HI", true);
                  d.setLocationRelativeTo(frame);
                  d.setVisible(true);
              } catch (Exception e1) {
                  e1.printStackTrace();
              }
          }

          @Override
          public void mousePressed(MouseEvent e) {}

          @Override
          public void mouseReleased(MouseEvent e) {}

          @Override
          public void mouseEntered(MouseEvent e) {}

          @Override
          public void mouseExited(MouseEvent e) {}
      });
    add( bChange );
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  }

}

log4j2.properties file:

appenders = rls,otr,routing

appender.rls.type = RollingFile
appender.rls.name = RollingFile_Rls
appender.rls.fileName = D:\\RLS\\rls_%d{MMdd}.log
appender.rls.filePattern = D:\\RLS\\rls_%d{MMdd}.log
appender.rls.layout.type = PatternLayout
appender.rls.layout.pattern = %d{ABSOLUTE} %level{length=1}
%markerSimpleName [%C{1}:%L] %m%n
appender.rls.policies.type = Policies
appender.rls.policies.time.type = TimeBasedTriggeringPolicy
appender.rls.policies.time.interval = 1
appender.rls.policies.time.modulate = true
appender.rls.policies.size.type = SizeBasedTriggeringPolicy
appender.rls.policies.size.size = 100MB
appender.rls.strategy.type = DefaultRolloverStrategy
appender.rls.strategy.max = 5
appender.otr.type = RollingFile
appender.otr.name = RollingFile_Otr
appender.otr.fileName = D:\\RLS\\otr_%d{MMdd}.log
appender.otr.filePattern = D:\\RLS\\otr_%d{MMdd}.log
appender.otr.layout.type = PatternLayout
appender.otr.layout.pattern = %d{ABSOLUTE} %level{length=1}
%markerSimpleName [%C{1}:%L] %m%n
appender.otr.policies.type = Policies
appender.otr.policies.time.type = TimeBasedTriggeringPolicy
appender.otr.policies.time.interval = 1
appender.otr.policies.time.modulate = true
appender.otr.policies.size.type = SizeBasedTriggeringPolicy
appender.otr.policies.size.size = 100MB
appender.otr.strategy.type = DefaultRolloverStrategy
appender.otr.strategy.max = 5

appender.routing.type = Routing
appender.routing.name = Route_Finder
appender.routing.routes.type = Routes
appender.routing.routes.pattern = $${ctx:cfg}
appender.routing.routes.route1.type = Route
appender.routing.routes.route1.ref = RollingFile_Rls
appender.routing.routes.route1.key = RLS
appender.routing.routes.route2.type = Route
appender.routing.routes.route2.ref = RollingFile_Otr
appender.routing.routes.route2.key = $${ctx:cfg}

loggers = rls,otr

logger.rls.name = logging
logger.rls.level = info
logger.rls.additivity = false
logger.rls.appenderRefs=rls
logger.rls.appenderRef.rls.ref = Route_Finder

logger.rls.name = logging
logger.rls.level = info
logger.rls.additivity = false
logger.rls.appenderRefs=rls
logger.rls.appenderRef.rls.ref = Route_Finder

logger.otr.name = other
logger.otr.level = info
logger.otr.additivity = false
logger.otr.appenderRefs=otr
logger.otr.appenderRef.otr.ref = Route_Finder

rootLogger.level = trace
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = stdout

Body:
You can put log4j2.component.properties file in the classpath to control various aspects of Log4j 2 behavior.

For example content of log4j2.component.properties:

# https://logging.apache.org/log4j/2.x/manual/configuration.html#SystemProperties

# If true use an InheritableThreadLocal to implement the ThreadContext map.
# Otherwise, use a plain ThreadLocal.
# (Maybe ignored if a custom ThreadContext map is specified.)
# Default is false

# Modern 2.10+
log4j2.isThreadContextMapInheritable=true

# Legacy for pre-2.10
isThreadContextMapInheritable=true

This has priority over system properties, but it can be overridden by environment variable LOG4J_IS_THREAD_CONTEXT_MAP_INHERITABLE as described in the
documentation.


问:
Making `matplotlib.pyplot.plot()` work with `PeriodIndex
I have a DataFrame (df) that has a PeriodIndex and corresponding column of integers (OrderQuantity). (Think of this as data about quantities sold in a day for a particular product). In order to do some simple visualization of this data using matplotlib.pyplot.plot(), I am having to convert the PeriodIndex into Timestamp, otherwise the plot() method throws an error TypeError: Axis must havefreqset to convert to Periods. It appears MatPlotLib tries to convert the PeriodIndex into  Periods, without realizing that it already has Periods.

So, for now, the following works:

```<code>import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(15,8))
plt.plot(df.index.to_timestamp(), df.OrderQuantity) // produces a valid plot
</code>```

I am wondering if there is a better way of plotting Periods without having to convert to a Timestamp, which pyplot will internally convert back to a Periods before generating the graph.

答:
pandas.DataFrame.plot() has a keyword argument ax to explicitly specify which Axes to plot on, so you can create a Figure based on two (or more) DataFrames. For example,

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

np.random.seed(42)

df1 = pd.DataFrame(
    np.random.randint(5, 20, size=7), columns=['foo'],
    index=pd.period_range('2019-05-30', periods=7, freq='D')
)
df2 = pd.DataFrame(
    np.random.randint(15, 40, size=7), columns=['bar'],
    index=pd.period_range('2019-05-30', periods=7, freq='D')
)

fig, ax = plt.subplots()
df1.plot(ax=ax)
df2.plot(ax=ax)
plt.show()
```

will produce the following plot.

Body:
I have a DataFrame (df) that has a PeriodIndex and corresponding column of integers (OrderQuantity). (Think of this as data about quantities sold in a day for a particular product). In order to do some simple visualization of this data using matplotlib.pyplot.plot(), I am having to convert the PeriodIndex into Timestamp, otherwise the plot() method throws an error TypeError: Axis must havefreqset to convert to Periods. It appears MatPlotLib tries to convert the PeriodIndex into  Periods, without realizing that it already has Periods.

So, for now, the following works:

import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(15,8))
plt.plot(df.index.to_timestamp(), df.OrderQuantity) // produces a valid plot

I am wondering if there is a better way of plotting Periods without having to convert to a Timestamp, which pyplot will internally convert back to a Periods before generating the graph.

Body:
pandas.DataFrame.plot() has a keyword argument ax to explicitly specify which Axes to plot on, so you can create a Figure based on two (or more) DataFrames. For example,

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

np.random.seed(42)

df1 = pd.DataFrame(
    np.random.randint(5, 20, size=7), columns=['foo'],
    index=pd.period_range('2019-05-30', periods=7, freq='D')
)
df2 = pd.DataFrame(
    np.random.randint(15, 40, size=7), columns=['bar'],
    index=pd.period_range('2019-05-30', periods=7, freq='D')
)

fig, ax = plt.subplots()
df1.plot(ax=ax)
df2.plot(ax=ax)
plt.show()

will produce the following plot.


问:
Right syntax for a while loop in a GitLab CI file
I want to write a while loop in a GitLab CI file and here is the syntax that I've tried but seems to not be working.

Is the while loop authorized in GitLab or YAML files? Or are there other ways to write it?

Here is where I used it:

```<code>  - while ($(curl -X GET ${URL} | jq -r '.task.status') != "SUCCESS")
   ANALYSIS_ID=$(curl -X GET ${URL} | jq -r '.task.analysisId')
</code>```

答:
So I did this to resolve my issue , its to create a script in which I ve wrote the loop while and this script return the value that I needed, and then I  called this script in my gitlab_ci file as below :

```<code>  - ANALYSIS_ID=$(**./checkUrl.sh** $URL)
</code>```

And if needed as an example the script that I used

```<code>  #!/bin/bash
    success="SUCCESS"
    condition="$(curl -X GET "$1" | jq -r '.task.status')"

    while [ "$condition" != "$success" ]
    do
    ANALYSIS_Id="$(curl -X GET "$1" | jq -r '.task.analysisId')"
    done
    return "$ANALYSIS_Id"
</code>```

Body:
I want to write a while loop in a GitLab CI file and here is the syntax that I've tried but seems to not be working.

Is the while loop authorized in GitLab or YAML files? Or are there other ways to write it?

Here is where I used it:

  - while ($(curl -X GET ${URL} | jq -r '.task.status') != "SUCCESS")
   ANALYSIS_ID=$(curl -X GET ${URL} | jq -r '.task.analysisId')

Body:
So I did this to resolve my issue , its to create a script in which I ve wrote the loop while and this script return the value that I needed, and then I  called this script in my gitlab_ci file as below :

  - ANALYSIS_ID=$(**./checkUrl.sh** $URL)

And if needed as an example the script that I used

  #!/bin/bash
    success="SUCCESS"
    condition="$(curl -X GET "$1" | jq -r '.task.status')"

    while [ "$condition" != "$success" ]
    do
    ANALYSIS_Id="$(curl -X GET "$1" | jq -r '.task.analysisId')"
    done
    return "$ANALYSIS_Id"


问:
How to expire a particular row when a date is reached?
I have a table for students, where each student has to get an ID card and this ID card is valid for one year

I want the student record to be expired when it reaches to the expiration date and the expiration date also needs to be updated

For example, if the expiration date is 01/01/2020 it should be turned to 01/01/2021.

答:
When saving the data to the table you must have a column "expiration".
to save the expiration, expirationDate = getDate()+1year;

when saving

```<code>Insert into students (expiration) values (expirationDate);
</code>```

when updating run it daily

```<code>UPDATE students
SET status = 'expired'
WHERE expirationDate < getDate();
</code>```

Body:
When saving the data to the table you must have a column "expiration".
to save the expiration, expirationDate = getDate()+1year;

when saving

Insert into students (expiration) values (expirationDate);

when updating run it daily

UPDATE students
SET status = 'expired'
WHERE expirationDate < getDate();


问:
Black berry camera programming
I want take pictures using black berry camera for my app, it is possible in v5.0 and yes then how?</p>

答: Take a look at samples that come with the BB SDK installation on your PC. There is CameraDemo sample. You can just try searching for CameraDemo.java on your HDD if you're unsure where those samples are.</p>

Title: Black berry camera programming


问:
Unable to install python packages - Could not found suitable TLS certificate bundle
I am struggling to make Python (Anaconda) work from last few days. I had tried installing pytorch few days back and it crashed in between. Hence forth, my Anaconda is giving errors while installing any packages. I have Windows 10, 64 bit user with Python 3.6.1. - Intel chipset.

I am unable to install any package - above is the issue.

I even tried uninstalling and installing Anaconda which is the only Python distribution I have on my machine.

Another error which I receive -

Any help in this matter would be of great great help!!

答:
Upgrade pip as follows:

```<code>curl https://bootstrap.pypa.io/get-pip.py | python
</code>```

Note: You may need to use  sudo python above if not in a virtual environment.

(Note that upgrading pip using pip i.e pip install --upgrade pip will also not upgrade it correctly. pip won't work unless using TLS >= 1.2.)

For PyCharm (virtualenv) users:

Run virtual environment with shell. (replace "./venv/bin/activate" to your own path)

```<code>source ./venv/bin/activate
</code>```

Run upgrade

```<code>curl https://bootstrap.pypa.io/get-pip.py | python
</code>```

Restart your PyCharm instance, and check your Python interpreter in Preference.

Body:
Upgrade pip as follows:

curl https://bootstrap.pypa.io/get-pip.py | python

Note: You may need to use  sudo python above if not in a virtual environment.

(Note that upgrading pip using pip i.e pip install --upgrade pip will also not upgrade it correctly. pip won't work unless using TLS >= 1.2.)

For PyCharm (virtualenv) users:

Run virtual environment with shell. (replace "./venv/bin/activate" to your own path)

source ./venv/bin/activate

Run upgrade

curl https://bootstrap.pypa.io/get-pip.py | python

Restart your PyCharm instance, and check your Python interpreter in Preference.


问:
Is there a way to make a child DIV's width wider than the parent DIV using CSS?
Is there a way to have a child DIV within a parent container DIV that is wider than its parent. The child DIV needs to be the same width as the browser viewport.

See example below:

The child DIV must stay as a child of the parent div. I know I can set arbitrary negative margins on the child div to make it wider but I can't work out how to essentially make it 100% width of the browser.

I know I can do this:

```<code>.child-div{
    margin-left: -100px;
    margin-right: -100px;
}
</code>```

But I need the child to be the same width as the browser which is dynamic.

Update

Thanks for your answers, it seems the closest answer so far is to make the child DIV position: absolute, and set the left and right properties to 0.

The next problem I have is that the parent has position: relative, which means that left and right properties are still relative to the parent div and not the browser, see example here: jsfiddle.net/v2Tja/2

I can't remove the position: relative from the parent without screwing everything else up.

答:
Flexbox can be used to make a child wider than its parent with three lines of CSS.

Only the child’s display, margin-left and width need to be set. margin-left depends on the child’s width. The formula is:

```<code>margin-left: calc(-.5 * var(--child-width) + 50%);
</code>```

CSS variables can be used to avoid manually calculating the left margin.

Demo #1: Manual calculation

.parent {
  background-color: aqua;
  height: 50vh;
  margin-left: auto;
  margin-right: auto;
  width: 50vw;
}

.child {
  background-color: pink;
  display: flex;
}

.wide {
  margin-left: calc(-37.5vw + 50%);
  width: 75vw;
}

.full {
  margin-left: calc(-50vw + 50%);
  width: 100vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div>
    parent
  </div>
  <div class="child wide">
    75vw
  </div>
  <div class="child full">
    100vw
  </div>
</div></code>```

Demo #2: Using CSS variables

.parent {
  background-color: aqua;
  height: 50vh;
  margin-left: auto;
  margin-right: auto;
  width: 50vw;
}

.child {
  background-color: pink;
  display: flex;
  margin-left: calc(-.5 * var(--child-width) + 50%);
  width: var(--child-width);
}

.wide {
  --child-width: 75vw;
}

.full {
  --child-width: 100vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div>
    parent
  </div>
  <div class="child wide">
    75vw
  </div>
  <div class="child full">
    100vw
  </div>
</div></code>```

Body:
Is there a way to have a child DIV within a parent container DIV that is wider than its parent. The child DIV needs to be the same width as the browser viewport.

See example below:

The child DIV must stay as a child of the parent div. I know I can set arbitrary negative margins on the child div to make it wider but I can't work out how to essentially make it 100% width of the browser.

I know I can do this:

.child-div{
    margin-left: -100px;
    margin-right: -100px;
}

But I need the child to be the same width as the browser which is dynamic.

Update

Thanks for your answers, it seems the closest answer so far is to make the child DIV position: absolute, and set the left and right properties to 0.

The next problem I have is that the parent has position: relative, which means that left and right properties are still relative to the parent div and not the browser, see example here: jsfiddle.net/v2Tja/2

I can't remove the position: relative from the parent without screwing everything else up.

Body:
Flexbox can be used to make a child wider than its parent with three lines of CSS.

Only the child’s display, margin-left and width need to be set. margin-left depends on the child’s width. The formula is:

margin-left: calc(-.5 * var(--child-width) + 50%);

CSS variables can be used to avoid manually calculating the left margin.

Demo #1: Manual calculation

.parent {
  background-color: aqua;
  height: 50vh;
  margin-left: auto;
  margin-right: auto;
  width: 50vw;
}

.child {
  background-color: pink;
  display: flex;
}

.wide {
  margin-left: calc(-37.5vw + 50%);
  width: 75vw;
}

.full {
  margin-left: calc(-50vw + 50%);
  width: 100vw;
}

<div class="parent">
  <div>
    parent
  </div>
  <div class="child wide">
    75vw
  </div>
  <div class="child full">
    100vw
  </div>
</div>

Demo #2: Using CSS variables

.parent {
  background-color: aqua;
  height: 50vh;
  margin-left: auto;
  margin-right: auto;
  width: 50vw;
}

.child {
  background-color: pink;
  display: flex;
  margin-left: calc(-.5 * var(--child-width) + 50%);
  width: var(--child-width);
}

.wide {
  --child-width: 75vw;
}

.full {
  --child-width: 100vw;
}

<div class="parent">
  <div>
    parent
  </div>
  <div class="child wide">
    75vw
  </div>
  <div class="child full">
    100vw
  </div>
</div>


问:
Deployment of Angular 7 PWA application in Tomcat Apache production server
I've created an Angular PWA application and built it by running: ng build --prod.

It has built the production ready application successfully.

I've ran the built application in local by running command: http-server -o, It was running as expected.

Problem:

When I've deployed in production's server tomcat apache webapp directory and ran it I am getting: Service worker is not registered or does not control the Start URL.

Service worker is not registering in my production environment.

Please Help me Thank you

答:
You need to have HTTPS connection to register a service worker. But still it works on localhost without HTTPS.

https://developers.google.com/web/fundamentals/primers/service-workers/#you_need_https


问:
Forgiving/Fuzzy search with LINQ
I'm attempting to implement a search against a DB that I inherited. The requirement states that the user must be able to search for an object by name. Unfortunately, an object could have multiple names associated with it. For example:

```<code>ID    Name
1     John and Jane Doe
2     Foo McFoo
3     Boo McBoo
</code>```

It's easy enough to implement a search when a single name exists in each record:

```<code>var objects =  from x in db.Foo
               where x.Name.Contains("Foo McFoo")
               select x;
</code>```

However, when multiple names exist, that approach does not work.

Question: Is it possible to write a search method that would return record one (John and Jane Doe) when someone uses the search terms John Doe or Jane Doe?

答:
I wonder how no one mentioned the Levenshtein distance algorithm.

It's an algorithm the tells the distance between two strings by an int.

Here's a SO post that you can find some implementations of this algorithm.

So with a distance function of signature int Distance(string x, string y), you can filter out high distances and order your results so that low distances appear on top of your results, using LINQ.

Note that this is going to be performance costly.

Title: Forgiving/Fuzzy search with LINQ

Body:
I'm attempting to implement a search against a DB that I inherited. The requirement states that the user must be able to search for an object by name. Unfortunately, an object could have multiple names associated with it. For example:

ID    Name
1     John and Jane Doe
2     Foo McFoo
3     Boo McBoo

It's easy enough to implement a search when a single name exists in each record:

var objects =  from x in db.Foo
               where x.Name.Contains("Foo McFoo")
               select x;

However, when multiple names exist, that approach does not work.

Question: Is it possible to write a search method that would return record one (John and Jane Doe) when someone uses the search terms John Doe or Jane Doe?


问:
when read data from file: output {'y': array([-0.21]), 'x': array([1.63])}
I will read data from a file, I have only two number in file are(1.63 , -0.21),output :

```<code>{'y': array([-0.21]), 'x': array([1.63])}
</code>```

I need the output like this:

```<code>position = {'x':  1.63 , 'y' : -0.21}
</code>```

this my code:

```<code>import pandas as pd
import numpy as np
def read():

    data = pd.read_csv('distance.csv', skipinitialspace=True, header=None)

    x0, y0 = np.array(data.ix[:,0]), np.array(data.ix[:,1])

    position = {'x':  x0 , 'y' : y0}
    print position

if __name__ == '__main__':

    try:
        read()
    except KeyboardInterrupt:
        rospy.loginfo('Shutting down')
</code>```

please help me

Thank you in advance

答:
Change this
x0, y0 = np.array(data.ix[:,0]), np.array(data.ix[:,1]) to x0, y0 = data.ix[:,0], data.ix[:,1]

Essentially you need to remove the np.array wrapping which converting your float to an nd.array

Body:
I will read data from a file, I have only two number in file are(1.63 , -0.21),output :

{'y': array([-0.21]), 'x': array([1.63])}

I need the output like this:

position = {'x':  1.63 , 'y' : -0.21}

this my code:

import pandas as pd
import numpy as np
def read():

    data = pd.read_csv('distance.csv', skipinitialspace=True, header=None)

    x0, y0 = np.array(data.ix[:,0]), np.array(data.ix[:,1])

    position = {'x':  x0 , 'y' : y0}
    print position

if __name__ == '__main__':

    try:
        read()
    except KeyboardInterrupt:
        rospy.loginfo('Shutting down')

please help me

Thank you in advance


问:
Why can't a sub implement an interface and handle event at the same time?
Why can't a sub implement an interface and handle event at the same time?

The following gives my a syntax error:

```<code>Sub MySub() Handles MyButton.Click Implements MyInterface.MyMethod
End Sub
</code>```

I know I could handle this kind of logic with another method, but that is not the point. I just want to understand the reasoning behind this.

答:
The syntax error is consistent with the language grammar, in §9.2.1 of the VB language specification1:

SubDeclaration  ::=

    [  Attributes  ]  [  ProcedureModifier+  ]  SubSignature  [  HandlesOrImplements  ]  LineTerminator

    Block

    End  Sub  StatementTerminator

and

HandlesOrImplements  ::=  HandlesClause  |  ImplementsClause

So only one is supported on any one method. The specification doesn't (on a quick view) include a rationale for this limitation. For that you'll need to talk to someone on the VB language design team at Microsoft.

1 This is included with an installation of VS under ‹VSRoot›\VB\Specifications\1033.

Body:
Why can't a sub implement an interface and handle event at the same time?

The following gives my a syntax error:

Sub MySub() Handles MyButton.Click Implements MyInterface.MyMethod
End Sub

I know I could handle this kind of logic with another method, but that is not the point. I just want to understand the reasoning behind this.


问:
Splitting a JS array into N arrays
Imagine I have an JS array like this:

```<code>var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
</code>```

What I want is to split that array into N smaller arrays. For instance:

```<code>split_list_in_n(a, 2)
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11]]

For N = 3:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

For N = 4:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

For N = 5:
[[1, 2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]
</code>```

For Python, I have this:

```<code>def split_list_in_n(l, cols):
    """ Split up a list in n lists evenly size chuncks """
    start = 0
    for i in xrange(cols):
        stop = start + len(l[i::cols])
        yield l[start:stop]
        start = stop
</code>```

For JS, the best right solution that I could come up with is a recursive function, but I don't like it because it's complicated and ugly. This inner function returns an array like this [1, 2, 3, null, 4, 5, 6, null, 7, 8], and then I have to loop it again and split it manually. (My first attempt was returning this: [1, 2, 3, [4, 5, 6, [7, 8, 9]]], and I decided to do it with the null separator).

```<code>function split(array, cols) {
    if (cols==1) return array;
    var size = Math.ceil(array.length / cols);
    return array.slice(0, size).concat([null]).concat(split(array.slice(size), cols-1));
}
</code>```

Here's a jsfiddle of that: http://jsfiddle.net/uduhH/

How would you do that? Thanks!

答:
If you happen to know the size of the chunks you want beforehand, there's a pretty elegant ES6 way of doing this:

const groupsOfFour = ([a,b,c,d, ...etc]) =>
  etc.length? [[a,b,c,d], ...groupsOfFour(etc)] : [[a,b,c,d]];

console.log(groupsOfFour([1,2,3,4,1,2,3,4,1,2,3,4]));```

I find this notation pretty useful for, for example parsing RGBA out of a Uint8ClampedArray.

Title: Splitting a JS array into N arrays

Body:
Imagine I have an JS array like this:

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

What I want is to split that array into N smaller arrays. For instance:

split_list_in_n(a, 2)
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11]]

For N = 3:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

For N = 4:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

For N = 5:
[[1, 2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]

For Python, I have this:

def split_list_in_n(l, cols):
    """ Split up a list in n lists evenly size chuncks """
    start = 0
    for i in xrange(cols):
        stop = start + len(l[i::cols])
        yield l[start:stop]
        start = stop

For JS, the best right solution that I could come up with is a recursive function, but I don't like it because it's complicated and ugly. This inner function returns an array like this [1, 2, 3, null, 4, 5, 6, null, 7, 8], and then I have to loop it again and split it manually. (My first attempt was returning this: [1, 2, 3, [4, 5, 6, [7, 8, 9]]], and I decided to do it with the null separator).

function split(array, cols) {
    if (cols==1) return array;
    var size = Math.ceil(array.length / cols);
    return array.slice(0, size).concat([null]).concat(split(array.slice(size), cols-1));
}

Here's a jsfiddle of that: http://jsfiddle.net/uduhH/

How would you do that? Thanks!

Body:
If you happen to know the size of the chunks you want beforehand, there's a pretty elegant ES6 way of doing this:

const groupsOfFour = ([a,b,c,d, ...etc]) =>
  etc.length? [[a,b,c,d], ...groupsOfFour(etc)] : [[a,b,c,d]];

console.log(groupsOfFour([1,2,3,4,1,2,3,4,1,2,3,4]));

I find this notation pretty useful for, for example parsing RGBA out of a Uint8ClampedArray.


问:
Adding a DOM element by changing innerHtml of a div prevents it to be found later with getElementById?
I have a div and I'm using javascript to add a new element inside it

Original Div:

```<code><div id="foo"></div>
</code>```

JavaScript:

```<code>document.getElementById('foo').innerHTML ="<div id='bar'></div>";
</code>```

Result

```<code><div id="foo">
  <div id="bar"></div>
</div>
</code>```

But after executing this code I try to retrieve the element (in order to focus on it) doing

```<code> document.getElementById('bar')
</code>```

But this returns an empty object.

So does adding an element using innerHtml not really add the element to the DOM? And what is the right way to add an element that could be retrieved later by getElementById?

答:
I would suggest using createElement and appendChild

    var barDiv = document.createElement('div');
    barDiv.id = 'bar';
    document.getElementById('foo').appendChild(barDiv);
    document.getElementById('bar').innerHTML = 'bar';

    console.log(document.getElementById('bar'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="foo">Foo</div></code>```

Body:
I have a div and I'm using javascript to add a new element inside it

Original Div:

JavaScript:

document.getElementById('foo').innerHTML ="

";

Result

But after executing this code I try to retrieve the element (in order to focus on it) doing

 document.getElementById('bar')

But this returns an empty object.

So does adding an element using innerHtml not really add the element to the DOM? And what is the right way to add an element that could be retrieved later by getElementById?

Body:
I would suggest using createElement and appendChild

    var barDiv = document.createElement('div');
    barDiv.id = 'bar';
    document.getElementById('foo').appendChild(barDiv);
    document.getElementById('bar').innerHTML = 'bar';

    console.log(document.getElementById('bar'));

<div id="foo">Foo</div>


问:
Unable to parse array of dictionary inside string
Currently I am working on bus booking module. After user set his departure and arrival city and date of journey, user will be shown a list of available buses. I have done that part successfully. But the problem which I am facing is that, each bus has it's own cancellation policy which is array of dictionary inside string. I am unable to parse it. Inside every dictionary of "apiAvailableBuses" there is "cancellationPolicy" key which has string as value which contains array of dictionary. I have removed other key value pairs from "apiAvailableBuses".

List of available Buses JSON response:

```<code>"apiAvailableBuses":[
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"9-12\",\"refundInPercentage\":\"25\"},{\"cutoffTime\":\"12-24\",\"refundInPercentage\":\"35\"},{\"cutoffTime\":\"24-48\",\"refundInPercentage\":\"50\"},{\"cutoffTime\":\"48-60\",\"refundInPercentage\":\"75\"},{\"cutoffTime\":\"60\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"6-24\",\"refundInPercentage\":\"70\"},{\"cutoffTime\":\"24\",\"refundInPercentage\":\"85\"}]"
   }
]
</code>```

Can anyone help me with a solution for this? If anyone can't understand my question please let me know.

Note: I am not using Codable in my project.

Thanks in advance.

答:
You can parse JSON string using the following method:</p>

```<code>// JSON Format
    let jsonResponse = ["apiAvailableBuses": [
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"9-12\",\"refundInPercentage\":\"25\"},{\"cutoffTime\":\"12-24\",\"refundInPercentage\":\"35\"},{\"cutoffTime\":\"24-48\",\"refundInPercentage\":\"50\"},{\"cutoffTime\":\"48-60\",\"refundInPercentage\":\"75\"},{\"cutoffTime\":\"60\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"6-24\",\"refundInPercentage\":\"70\"},{\"cutoffTime\":\"24\",\"refundInPercentage\":\"85\"}]"
        ]
        ]
    ]

// Function Calling
        setBuses(json: jsonResponse)

// Function to Parse JSON
func setBuses(json: Dictionary<String,Any>) {
    guard let buses = json["apiAvailableBuses"] as? [Dictionary<String,Any>] else { return }
    for (index, bus) in buses.enumerated() {
        print("\n\nBus #\(index+1)")
        guard let policies = convertToDictionary(text: bus["cancellationPolicy"] as! String) else { return }
        for (index, policy) in policies.enumerated() {
            print("\nPolicy #\(index+1)")
            print("cutoffTime #\(index+1) \(String(describing: policy["refundInPercentage"]))")
            print("refundInPercentage #\(index+1) \(String(describing: policy["cutoffTime"]))")
        }
    }
}

func convertToDictionary(text: String) -> [Dictionary<String,Any>]? {
    let data = text.data(using: .utf8)!
    do {
        if let jsonObj = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>] {
            return jsonObj
        } else {
            print("JSON Error")
        }
    } catch let error as NSError {
        print(error)
    }
    return nil
}
</code>```

Body:
Currently I am working on bus booking module. After user set his departure and arrival city and date of journey, user will be shown a list of available buses. I have done that part successfully. But the problem which I am facing is that, each bus has it's own cancellation policy which is array of dictionary inside string. I am unable to parse it. Inside every dictionary of "apiAvailableBuses" there is "cancellationPolicy" key which has string as value which contains array of dictionary. I have removed other key value pairs from "apiAvailableBuses".

List of available Buses JSON response:

"apiAvailableBuses":[
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"9-12\",\"refundInPercentage\":\"25\"},{\"cutoffTime\":\"12-24\",\"refundInPercentage\":\"35\"},{\"cutoffTime\":\"24-48\",\"refundInPercentage\":\"50\"},{\"cutoffTime\":\"48-60\",\"refundInPercentage\":\"75\"},{\"cutoffTime\":\"60\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"6-24\",\"refundInPercentage\":\"70\"},{\"cutoffTime\":\"24\",\"refundInPercentage\":\"85\"}]"
   }
]

Can anyone help me with a solution for this? If anyone can't understand my question please let me know.

Note: I am not using Codable in my project.

Thanks in advance.

Body:
You can parse JSON string using the following method:

// JSON Format
    let jsonResponse = ["apiAvailableBuses": [
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"9-12\",\"refundInPercentage\":\"25\"},{\"cutoffTime\":\"12-24\",\"refundInPercentage\":\"35\"},{\"cutoffTime\":\"24-48\",\"refundInPercentage\":\"50\"},{\"cutoffTime\":\"48-60\",\"refundInPercentage\":\"75\"},{\"cutoffTime\":\"60\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
        ],
        [
            "cancellationPolicy": "[{\"cutoffTime\":\"6-24\",\"refundInPercentage\":\"70\"},{\"cutoffTime\":\"24\",\"refundInPercentage\":\"85\"}]"
        ]
        ]
    ]

// Function Calling
        setBuses(json: jsonResponse)

// Function to Parse JSON
func setBuses(json: Dictionary<String,Any>) {
    guard let buses = json["apiAvailableBuses"] as? [Dictionary<String,Any>] else { return }
    for (index, bus) in buses.enumerated() {
        print("\n\nBus #\(index+1)")
        guard let policies = convertToDictionary(text: bus["cancellationPolicy"] as! String) else { return }
        for (index, policy) in policies.enumerated() {
            print("\nPolicy #\(index+1)")
            print("cutoffTime #\(index+1) \(String(describing: policy["refundInPercentage"]))")
            print("refundInPercentage #\(index+1) \(String(describing: policy["cutoffTime"]))")
        }
    }
}

func convertToDictionary(text: String) -> [Dictionary<String,Any>]? {
    let data = text.data(using: .utf8)!
    do {
        if let jsonObj = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>] {
            return jsonObj
        } else {
            print("JSON Error")
        }
    } catch let error as NSError {
        print(error)
    }
    return nil
}


问:
Trying to initialize an Image
This is me clicking "fix"
Error
I created a new class and init method for my data with 3 variables. One being the UIImage. It can't seem to locate the images in my assets folder.

I tried UIimage(named:  String).

Below is my Code

```<code>    class DataForMeals {
    var mealName: String
    var mealImage: UIImage
    var description: String

    init(mealName: String, mealImage: UIImage, description: String) {
        self.mealImage = mealImage
        self.mealName = mealName
        self.description = description
    }

class func mealData() ->[DataForMeals] {
        var meal: [DataForMeals] = []

        let meal1 = DataForMeals(mealName: "", mealImage: UIImage(named: ""),description: "")

</code>```

It's supposed to find the image by name.

答:
You can use this for calling the image from the assets.

```<code>UIImage(named: "image1")
</code>```

In your case, you need to pass the image name

```<code>let meal1 = DataForMeals(mealName: "Roti", mealImage: UIImage(named: "name1"),description: "Afternoon Meal")
</code>```

Title: Trying to initialize an Image

Body:
This is me clicking "fix"
Error
I created a new class and init method for my data with 3 variables. One being the UIImage. It can't seem to locate the images in my assets folder.

I tried UIimage(named:  String).

Below is my Code

    class DataForMeals {
    var mealName: String
    var mealImage: UIImage
    var description: String

    init(mealName: String, mealImage: UIImage, description: String) {
        self.mealImage = mealImage
        self.mealName = mealName
        self.description = description
    }

class func mealData() ->[DataForMeals] {
        var meal: [DataForMeals] = []

        let meal1 = DataForMeals(mealName: "", mealImage: UIImage(named: ""),description: "")

It's supposed to find the image by name.

Body:
You can use this for calling the image from the assets.

UIImage(named: "image1")

In your case, you need to pass the image name

let meal1 = DataForMeals(mealName: "Roti", mealImage: UIImage(named: "name1"),description: "Afternoon Meal")


问:
MySQL fetch X columns for each category_id
I don't know if this is possible in mysql via ONE query .

assuming I have a table "products" that has "id","category_id","product_name","price"

Case 1 : I want to fetch 5 products from each category where price is more than 100$

Case 2: I want to fetch

1-"3 products from category 1"

2- "5 products from category 2"

3- "3 products from category 2 where the price is more than 100 and is not fetched in point 2 above"

each case in ONE query , is that possible ?

PS : The table has about 100K rows ...

答:
Case 2 I think I've got...

```<code>  (
  select * from products where category_id = 1 limit 3
  )
union
  (
  select * from products where category_id = 2 limit 5
  )
union (
  select * from products where category_id = 2 and price > 100 limit 3
)
</code>```

Note that union will eliminate duplicates, union all will allow duplicates (and is therefor faster).

Have you seen?

mySQL Returning the top 5 of each category

That looks like what you're asking...

Body:
Case 2 I think I've got...

  (
  select * from products where category_id = 1 limit 3
  )
union
  (
  select * from products where category_id = 2 limit 5
  )
union (
  select * from products where category_id = 2 and price > 100 limit 3
)

Note that union will eliminate duplicates, union all will allow duplicates (and is therefor faster).

Have you seen?

mySQL Returning the top 5 of each category

That looks like what you're asking...