问:
cant free dynamic matrix
As a part of my homework with C, I had to make a function which splits a string to all the words starting with the key(which is a letter) inserted.
Everything works great except for the free function,
When I try to free the dynamic matrix by function (rows and then skeleton)
I get an error that the program has triggered a breakpoint.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char **Split(char *str, char letter, int *size);
void free_mat(char **mat, int size);

int main() {
    int size, i;
    char letter;
    char STR[100];
    char **strings_arr;
    printf("Please enter a string:\n");
    flushall;
    gets(STR);
    printf("Please enter a letter for a check:\n");
    letter = getchar();
    strings_arr = Split(STR, letter, &size);

    if (size > 0) {
        printf("The number of words that starts with the letter '%c' in the string '%s' is: %d\n\n", letter, STR, size);
    }
    printf("The words are:\n");
    for (i = 0; i < size; i++) {
        printf("%d . %s\n", i+1,strings_arr[i]);
    }
    free_mat(strings_arr, size);
    return 0;
}

void free_mat(char **mat, int size)
{
    int i;
    for (i = 0; i < size; i++)
    {
        free(mat[i]);
    }
    free(mat);
}
char **Split(char *str, char letter, int *size) {
    int rows = 0, i, lengh = 0, j = 0, n = 0, m;
    char **strings_array;

    if ((str[0] == letter) || (str[0] == letter + 32) || str[0] == letter - 32) {
        rows++;
    }
    for (i = 0; str[i] != '\0'; i++) {
         if (str[i] == ' ') {
            if ((str[i + 1] == letter) || (str[i + 1] == letter + 32) || str[i + 1] == letter - 32) {
                rows++;
            }
        }
    }
    if (rows == 0) {
        printf("There are no words starting with '%c' letter in this string\n\n", letter);
    }
    i = 0;
    strings_array = (char*)malloc(rows * sizeof(char));
    if ((str[0] == letter) || (str[0] == letter + 32) || str[0] == letter - 32) {
        while (str[i] != ' ' && str[i] != '\0') {
            lengh++;
            i++;
        }
        strings_array[j] = (char*)malloc((lengh + 1) * sizeof(char));
        for (n = 0; n < lengh; n++) {
            strings_array[j][n] = str[n];
        }
        strings_array[j][n] = '\0';
        j++;
    }
    for (i = 1; str[i] != '\0'; i++) {
            if (letter == str[i] || letter == str[i] - 32 || letter == str[i] + 32) {
                lengh = 0;
                //k = 0;
                m = i;
                while (str[m] != ' ' && str[m] != '\0') {
                    lengh++;
                    m++;
                }
                strings_array[j] = (char*)malloc(lengh + 1);

                for (n = 0; n < lengh; n++) {
                    strings_array[j][n] = str[i++];
                }
                strings_array[j][n] = '\0';
                j++;
            }
    }
    *size = rows;   // sends back the number of words by referance
    return strings_array;
}
</code>```

Thanks!

答:
A breakpoint is something that you manually insert in the code from your IDE or equivalent. It is used for debugging. When you run the code it is intended to stop when it reaches a breakpoint. So just remove the breakpoint and it should work as expected.

Note: Remove only the breakpoint. Not the code on that line.

You mentioned in comments below that you're using Visual Studio 2015. Here is the documentation for breakpoints in that software: https://learn.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2019

But there are some other things about your code. First of all, use fgets instead of gets. Second, you seem to have posted the wrong version or something, because free_mat will not compile. However, that was easily solved by changing arr to mat.

There's also another error that xing mentioned in the comments. Change strings_array = (char*)malloc(rows * sizeof(char)) to strings_array = malloc(rows * sizeof(*strings_array)). The cast is not necessary, you picked the wrong type for the argument to sizeof and if you pass a dereferenced pointer instead of the type you'll save yourself a lot of problems in the future.

Title: cant free dynamic matrix

Body:
As a part of my homework with C, I had to make a function which splits a string to all the words starting with the key(which is a letter) inserted.
Everything works great except for the free function,
When I try to free the dynamic matrix by function (rows and then skeleton)
I get an error that the program has triggered a breakpoint.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char **Split(char *str, char letter, int *size);
void free_mat(char **mat, int size);

int main() {
    int size, i;
    char letter;
    char STR[100];
    char **strings_arr;
    printf("Please enter a string:\n");
    flushall;
    gets(STR);
    printf("Please enter a letter for a check:\n");
    letter = getchar();
    strings_arr = Split(STR, letter, &size);

    if (size > 0) {
        printf("The number of words that starts with the letter '%c' in the string '%s' is: %d\n\n", letter, STR, size);
    }
    printf("The words are:\n");
    for (i = 0; i < size; i++) {
        printf("%d . %s\n", i+1,strings_arr[i]);
    }
    free_mat(strings_arr, size);
    return 0;
}

void free_mat(char **mat, int size)
{
    int i;
    for (i = 0; i < size; i++)
    {
        free(mat[i]);
    }
    free(mat);
}
char **Split(char *str, char letter, int *size) {
    int rows = 0, i, lengh = 0, j = 0, n = 0, m;
    char **strings_array;

    if ((str[0] == letter) || (str[0] == letter + 32) || str[0] == letter - 32) {
        rows++;
    }
    for (i = 0; str[i] != '\0'; i++) {
         if (str[i] == ' ') {
            if ((str[i + 1] == letter) || (str[i + 1] == letter + 32) || str[i + 1] == letter - 32) {
                rows++;
            }
        }
    }
    if (rows == 0) {
        printf("There are no words starting with '%c' letter in this string\n\n", letter);
    }
    i = 0;
    strings_array = (char*)malloc(rows * sizeof(char));
    if ((str[0] == letter) || (str[0] == letter + 32) || str[0] == letter - 32) {
        while (str[i] != ' ' && str[i] != '\0') {
            lengh++;
            i++;
        }
        strings_array[j] = (char*)malloc((lengh + 1) * sizeof(char));
        for (n = 0; n < lengh; n++) {
            strings_array[j][n] = str[n];
        }
        strings_array[j][n] = '\0';
        j++;
    }
    for (i = 1; str[i] != '\0'; i++) {
            if (letter == str[i] || letter == str[i] - 32 || letter == str[i] + 32) {
                lengh = 0;
                //k = 0;
                m = i;
                while (str[m] != ' ' && str[m] != '\0') {
                    lengh++;
                    m++;
                }
                strings_array[j] = (char*)malloc(lengh + 1);

                for (n = 0; n < lengh; n++) {
                    strings_array[j][n] = str[i++];
                }
                strings_array[j][n] = '\0';
                j++;
            }
    }
    *size = rows;   // sends back the number of words by referance
    return strings_array;
}

Thanks!


来源: stackexchange

问:
bind number value with ngb-timepicker angular
I have a priceRuleobject which contains 4 attributes :

public hourStartTime: number,
public minuteStartTime: number,
public hourEndTime: number,
public minuteEndTime: number,
```

<p>And two <code>nbg-timepicker</code> :</p>

```
<ngb-timepicker [(ngModel)]="...">

</ngb-timepicker>

<ngb-timepicker [(ngModel)]="...">

</ngb-timepicker>
```

I don't know what to type to bind my values ( hourStartTime and minuteStartTim with the first timepicker, hourEndTime and minuteEndTime with the second timepicker ).

答:
In your component, you can define time like this:

```<code>time = {hour: 13, minute: 30};
</code>```

And in your HTML:

```<code><ngb-timepicker [ngModel]="time"></ngb-timepicker>
</code>```

In your case:

```<code>import {Component} from '@angular/core';

@Component({
  selector: 'ngbd-timepicker-basic',
  templateUrl: 'src/timepicker-basic.html'
})
export class NgbdTimepickerBasic {
  time = any;
  priceRule: any;
  constructor() {
    this.priceRule.hourStartTime = 13;
    this.priceRule.minuteStartTime = 50;
    time = { hour: this.priceRule.hourStartTime, minute: this.priceRule.minuteStartTime }
  }
}
</code>```

Update

Since ngb-timepicker expects an object of type

```<code>{ time: number, minute: number }
</code>```

So, if you don't want to use an extra variable, then you'll have to change the structure of priceRule a little bit. So
Instead of

```<code>export class PriceRule {
 public hourStartTime: number,
 public minuteStartTime: number,
 public hourEndTime: number,
 public minuteEndTime: number,
}
</code>```

It would be :

```<code>export class PriceRule {
  public startTime: { hour: number, minute: number };
  public endTime: { hour: number, minute: number };
}
</code>```

And in your component:

```<code>import {Component} from '@angular/core';

@Component({
  selector: 'ngbd-timepicker-basic',
  templateUrl: 'src/timepicker-basic.html'
})
export class NgbdTimepickerBasic {
  time = any;
  priceRule: any;
  constructor() {
    this.priceRule.startTime = { hour: 13, minute: 4 }
  }
}
</code>```

In in your HTML:

```<code><ngb-timepicker [ngModel]="priceRule.startTime"></ngb-timepicker>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a priceRuleobject which contains 4 attributes :

public hourStartTime: number,
public minuteStartTime: number,
public hourEndTime: number,
public minuteEndTime: number,

And two nbg-timepicker :

<ngb-timepicker [(ngModel)]="...">

</ngb-timepicker>

<ngb-timepicker [(ngModel)]="...">

</ngb-timepicker>

I don't know what to type to bind my values ( hourStartTime and minuteStartTim with the first timepicker, hourEndTime and minuteEndTime with the second timepicker ).

Body:
In your component, you can define time like this:

time = {hour: 13, minute: 30};

And in your HTML:

<ngb-timepicker [ngModel]="time"></ngb-timepicker>

In your case:

import {Component} from '@angular/core';

@Component({
  selector: 'ngbd-timepicker-basic',
  templateUrl: 'src/timepicker-basic.html'
})
export class NgbdTimepickerBasic {
  time = any;
  priceRule: any;
  constructor() {
    this.priceRule.hourStartTime = 13;
    this.priceRule.minuteStartTime = 50;
    time = { hour: this.priceRule.hourStartTime, minute: this.priceRule.minuteStartTime }
  }
}

Update

Since ngb-timepicker expects an object of type

{ time: number, minute: number }

So, if you don't want to use an extra variable, then you'll have to change the structure of priceRule a little bit. So
Instead of

export class PriceRule {
 public hourStartTime: number,
 public minuteStartTime: number,
 public hourEndTime: number,
 public minuteEndTime: number,
}

It would be :

export class PriceRule {
  public startTime: { hour: number, minute: number };
  public endTime: { hour: number, minute: number };
}

And in your component:

import {Component} from '@angular/core';

@Component({
  selector: 'ngbd-timepicker-basic',
  templateUrl: 'src/timepicker-basic.html'
})
export class NgbdTimepickerBasic {
  time = any;
  priceRule: any;
  constructor() {
    this.priceRule.startTime = { hour: 13, minute: 4 }
  }
}

In in your HTML:

<ngb-timepicker [ngModel]="priceRule.startTime"></ngb-timepicker>


问:
How to create virtual scrolling for images using React js
Whats my requirement: i have some images in my external folder and i need to import to component and display it and also have to use Virtual Scroll here i have to display 1 row in div and in that 1 row have to show 5-6 images

What i did : i consumed images using context from external folder and showed images in 1 rows in div and 5-6 images but i am facing issue unable to set it to Virtual scrolling

as i checked react-virtualized & react-window plugin but i am not sure how my data is used in that format

After using the react-tiny-virtual-list images are getting stacked

below is my code

```<code>class App extends React.Component{

  state={
    Response:[],

  }
  importAll(r) {
    return r.keys().map(r);
  }
  componentWillMount() {
    let data = this.importAll(require.context('./imageFolder/', false, /\.(png|jpe?g|svg)$/));
    this.setState({ Response:data})
  }

  render(){
    return(
      <div className="container" id="imagecontainer">
        <div className="viewport">
              {this.state.Response.map((image, index) =>    <img key={index} src={image} alt="info"></img>      )} }
           </div>

      </div>
    )
  }

 .container {
      padding: 0% 6%;
      height: 400px;
    }
    .viewport {
      height: -webkit-fill-available;
      width: 100%;
      border: 1px solid black;
      overflow: scroll;
    }

img {
  height: 250px;
  width: 150px;
  padding: 35px;
}

After implementing React-tiny-list
 <div id="container">
      <div id="viewport">
      <VirtualList
    height='400px'
    width='100%'
    itemCount={this.state.items.length}
    itemSize={20} // Also supports variable heights (array or function getter)
    style={{padding:'20px'}}
    renderItem={({index, style}) =>
      <div key={index} style={style}>

        <img key={index} src={this.state.items[index]} alt="info"></img>
      </div>
    }
  />
      </div>

    </div>
</code>```

答:
If you're having trouble implementing the virtual scroll, note that the order of the imports is important when doing this, so pay heed to this - it could be contributing to your issue. (An aside: There is an npm plugin for implementing a virtual list.)

An overview of the import order for virtual scroll is:

```<code>import * as React from 'react';
import Paper from '@material-ui/core/Paper';
import {
  Grid,
  VirtualTable,
  TableHeaderRow,
} [from material ui];

import {
  your-components
} from 'your-path';
</code>```

(above is non-specific, just a rough guide to the order)

You could also use a ScrollView if you are unable to implement a "Virtual scroll".
The following style will give you a horizontal scroll (as opposed to the default vertical), to enable you to display your images in a horizontally-scrollable row

```<code><ScrollView horizontal={true}>
</code>```

Hope this helps

Body:
Whats my requirement: i have some images in my external folder and i need to import to component and display it and also have to use Virtual Scroll here i have to display 1 row in div and in that 1 row have to show 5-6 images

What i did : i consumed images using context from external folder and showed images in 1 rows in div and 5-6 images but i am facing issue unable to set it to Virtual scrolling

as i checked react-virtualized & react-window plugin but i am not sure how my data is used in that format

After using the react-tiny-virtual-list images are getting stacked

below is my code

class App extends React.Component{

  state={
    Response:[],

  }
  importAll(r) {
    return r.keys().map(r);
  }
  componentWillMount() {
    let data = this.importAll(require.context('./imageFolder/', false, /\.(png|jpe?g|svg)$/));
    this.setState({ Response:data})
  }

  render(){
    return(

              {this.state.Response.map((image, index) =>          )} }

    )
  }

 .container {
      padding: 0% 6%;
      height: 400px;
    }
    .viewport {
      height: -webkit-fill-available;
      width: 100%;
      border: 1px solid black;
      overflow: scroll;
    }

img {
  height: 250px;
  width: 150px;
  padding: 35px;
}

After implementing React-tiny-list

      <VirtualList
    height='400px'
    width='100%'
    itemCount={this.state.items.length}
    itemSize={20} // Also supports variable heights (array or function getter)
    style={{padding:'20px'}}
    renderItem={({index, style}) =>

    }
  />

Body:
If you're having trouble implementing the virtual scroll, note that the order of the imports is important when doing this, so pay heed to this - it could be contributing to your issue. (An aside: There is an npm plugin for implementing a virtual list.)

An overview of the import order for virtual scroll is:

import * as React from 'react';
import Paper from '@material-ui/core/Paper';
import {
  Grid,
  VirtualTable,
  TableHeaderRow,
} [from material ui];

import {
  your-components
} from 'your-path';

(above is non-specific, just a rough guide to the order)

You could also use a ScrollView if you are unable to implement a "Virtual scroll".
The following style will give you a horizontal scroll (as opposed to the default vertical), to enable you to display your images in a horizontally-scrollable row

<ScrollView horizontal={true}>

Hope this helps


问:
How to get Discord.js bot to log variable for every user
I am creating a discord bot similar to Pokecord and would like to log 1 or more variables for every user. I am using Discord.js, JavaScript, and Node.js.
Is this possible?</p>

答:
To store a certain value or variable for each user, you have three main options. A database is probably your best choice.

1. Declaring a Map

See here for more about Maps in JavaScript.

Pros

- Simple and easy

- Contained completely within your code

Cons

- All values will be reset if the code stops

Example

When initializing your client, you can declare one of its properties as a Map, so you can easily access it elsewhere in your code:

client.money = new Map();
```

<p>Retrieving a user's balance:</p>

<pre class="lang-js prettyprint-override"><code>const ID = message.author.id; // or set it as the mentioned user's ID, etc.
console.log(client.money.get(ID));
</code>```

Setting a user's balance:

client.money.set(ID, 5);
```

<p>Adding to a user's balance:</p>

<pre class="lang-js prettyprint-override"><code>client.money.set(ID, client.money.get(ID) + 2);
</code>```

2. json File

Pros

- Separate file/organized

- Stays even after code stops running

Cons

- Slightly more complicated

- Speed, compared to DB

Example

money.json:

```<code>{ "userIDhere": 0 }
</code>```

Retrieving a user's balance:

const money = require('./money.json'); // path may vary
const ID = message.author.id; // or set it as the mentioned user's ID, etc.
console.log(money[ID]);
```

<p>Setting a user's balance:</p>

<pre class="lang-js prettyprint-override"><code>money[ID] = 3;
fs.writeFileSync('./money.json', JSON.stringify(money));
</code>```

Adding to a user's balance:

money[ID] += 8;
fs.writeFileSync('./money.json', JSON.stringify(money));
```

3. Database

Pros

- Speed

- Stays even after code stops running

- Easily accessible

Cons

- Harder setup

Your choice for a database is up to you, and setup and usage vary for each. Do some research for which is best for you.

Body:
To store a certain value or variable for each user, you have three main options. A database is probably your best choice.

1. Declaring a Map

See here for more about Maps in JavaScript.

Pros

- Simple and easy

- Contained completely within your code

Cons

- All values will be reset if the code stops

Example

When initializing your client, you can declare one of its properties as a Map, so you can easily access it elsewhere in your code:

client.money = new Map();

Retrieving a user's balance:

const ID = message.author.id; // or set it as the mentioned user's ID, etc.
console.log(client.money.get(ID));

Setting a user's balance:

client.money.set(ID, 5);

Adding to a user's balance:

client.money.set(ID, client.money.get(ID) + 2);

2. json File

Pros

- Separate file/organized

- Stays even after code stops running

Cons

- Slightly more complicated

- Speed, compared to DB

Example

money.json:

{ "userIDhere": 0 }

Retrieving a user's balance:

const money = require('./money.json'); // path may vary
const ID = message.author.id; // or set it as the mentioned user's ID, etc.
console.log(money[ID]);

Setting a user's balance:

money[ID] = 3;
fs.writeFileSync('./money.json', JSON.stringify(money));

Adding to a user's balance:

money[ID] += 8;
fs.writeFileSync('./money.json', JSON.stringify(money));

3. Database

Pros

- Speed

- Stays even after code stops running

- Easily accessible

Cons

- Harder setup

Your choice for a database is up to you, and setup and usage vary for each. Do some research for which is best for you.


问:
How to handle up button in toolbar - Kotlin
I have manually/programmatically set up an up button in my toolbar for a fragment page with the following code in onCreateOptionsMenu in the fragment:

```<code>(activity as AppCompatActivity).setSupportActionBar?.setDisplayHomeAsUpEnabled(true)
</code>```

Tapping the system back button will take the user back to the previous fragment but without an up button (that works) I think some users may get lost.

I am having difficulty trying to work out how to catch and handle the up button to pop the fragment off the back stack.

This SO post shows how to catch the the up button click however it is in Java and doesn't go on to explain how you would navigate up.

I think it needs to look something like the code below but there are errors everywhere:

The case android.R.id.home is showing an 'Incompatible types:Int and MenuItem' error?

onBackPressed() is showing an 'Unresolved reference' error.

Bad code:

```<code>override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item) {
            android.R.id.home -> {
                onBackPressed()
                return true
            }
            else -> return super.onOptionsItemSelected(item)
        }
}
</code>```

UPDATE:

A comment to another SO post has a potential solution in Kotlin. It catches the click on the up button and goes back to the previous fragment page but then the up button doesn't go away. So the up button now persists even on the top level fragment destinations in my app (the pages corresponding to each tab in the BottomNavigationView).

I think this might have to do with the fact that there is only one activity in my app and the way that I have set up the up button in the fragment as mentioned above? If so, is there a workaround or other way to set up the up button by referencing the fragment instead of the whole activity?

If it helps, this is the code in the RecyclerView inner ViewHolder class in the adapter.kt file that navigates to the fragment page in question:

```<code>class AdapterListItemDetails(val items: List<ItemsList>) : RecyclerView.Adapter<AdapterListItemDeatils.ItemsViewHolder>() {

    //overrides for OnCreateViewHolder, getItemCount, onBindViewHolder

    inner class ItemsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        var currentItem: ItemsList? = null
        var currentPosition: Int = 0

        init {
             itemView.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.goto_details, null))
        }

        fun setData(itemsList: ItemsList, position: Int) {
            itemView.tview_Keys.text = itemsList!!.nameText

            this.currentItem = itemsList
            this.currentPosition = position
        }
    }
}
</code>```

答:
Hi this is what i usually do:
in an activity find the navController from your navHostFragment

```<code>val navController = this.findNavController(R.id.myNavHostFragment)
</code>```

Make sure it's connected to the ActionBar

```<code>NavigationUI.setupActionBarWithNavController(this, navController)
</code>```

Then simply override onSupportNavigateUp, find your navController then navigate up

```<code>override fun onSupportNavigateUp(): Boolean{
    val navController = this.findNavController(R.id.myNavHostFragment)
    return navController.navigateUp()
}
</code>```

Body:
I have manually/programmatically set up an up button in my toolbar for a fragment page with the following code in onCreateOptionsMenu in the fragment:

(activity as AppCompatActivity).setSupportActionBar?.setDisplayHomeAsUpEnabled(true)

Tapping the system back button will take the user back to the previous fragment but without an up button (that works) I think some users may get lost.

I am having difficulty trying to work out how to catch and handle the up button to pop the fragment off the back stack.

This SO post shows how to catch the the up button click however it is in Java and doesn't go on to explain how you would navigate up.

I think it needs to look something like the code below but there are errors everywhere:

The case android.R.id.home is showing an 'Incompatible types:Int and MenuItem' error?

onBackPressed() is showing an 'Unresolved reference' error.

Bad code:

override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item) {
            android.R.id.home -> {
                onBackPressed()
                return true
            }
            else -> return super.onOptionsItemSelected(item)
        }
}

UPDATE:

A comment to another SO post has a potential solution in Kotlin. It catches the click on the up button and goes back to the previous fragment page but then the up button doesn't go away. So the up button now persists even on the top level fragment destinations in my app (the pages corresponding to each tab in the BottomNavigationView).

I think this might have to do with the fact that there is only one activity in my app and the way that I have set up the up button in the fragment as mentioned above? If so, is there a workaround or other way to set up the up button by referencing the fragment instead of the whole activity?

If it helps, this is the code in the RecyclerView inner ViewHolder class in the adapter.kt file that navigates to the fragment page in question:

class AdapterListItemDetails(val items: List<ItemsList>) : RecyclerView.Adapter<AdapterListItemDeatils.ItemsViewHolder>() {

    //overrides for OnCreateViewHolder, getItemCount, onBindViewHolder

    inner class ItemsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        var currentItem: ItemsList? = null
        var currentPosition: Int = 0

        init {
             itemView.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.goto_details, null))
        }

        fun setData(itemsList: ItemsList, position: Int) {
            itemView.tview_Keys.text = itemsList!!.nameText

            this.currentItem = itemsList
            this.currentPosition = position
        }
    }
}

Body:
Hi this is what i usually do:
in an activity find the navController from your navHostFragment

val navController = this.findNavController(R.id.myNavHostFragment)

Make sure it's connected to the ActionBar

NavigationUI.setupActionBarWithNavController(this, navController)

Then simply override onSupportNavigateUp, find your navController then navigate up

override fun onSupportNavigateUp(): Boolean{
    val navController = this.findNavController(R.id.myNavHostFragment)
    return navController.navigateUp()
}


问:
Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress
How do I fix the error below?

Your PHP installation appears to be missing the MySQL extension which is required by WordPress.

I use my NAS with a telnet connection.

I installed FFP 0.7

My php.ini is in: ffp/etc/php.ini and I uncommented everything I thought to be of use.

Below is a portion of my php.ini file;

```<code>;If you wish to have an extension loaded automatically, use the following
; syntax:
;
;   extension=modulename.extension
;
; For example, on Windows:
;
extension=msql.dll
;
; ... or under UNIX:
;
extension=msql.so
;
; ... or with a path:
;
extension=/ffp/lib/extensions/no-debug-non-zts-20100525/mysql.so
;

extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_pdo_mssql.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll
extension=php_pgsql.dll
extension=pdo.so
extension=pdo_sqlite.so
extension=sqlite.so
extension=pdo_mysql.so
</code>```

The outstanding issue is that when I run in phpinfo(), I see the module MySQLi activated but not MySQL.

MySQL is working as expected just as PHP and Lighttpd web server.

I equally have phpmyadmin working.

It's on a Zyxel NSA310.

Also, when mysqld is started, it creates a shortcut from my root to: ffp/opt/mysql.. and every time I restart my NAS the shortcut is deleted.

Does anyone might know a trick for this?

答:
On Oracle Linux 7.x running PHP version 7.3.x you need to run sudo yum install php-mysqlnd in order to install the missing MySQL extension for PHP.

Remember to restart PHP and or your server for the changes to take effect.

Body:
How do I fix the error below?

Your PHP installation appears to be missing the MySQL extension which is required by WordPress.

I use my NAS with a telnet connection.

I installed FFP 0.7

My php.ini is in: ffp/etc/php.ini and I uncommented everything I thought to be of use.

Below is a portion of my php.ini file;

;If you wish to have an extension loaded automatically, use the following
; syntax:
;
;   extension=modulename.extension
;
; For example, on Windows:
;
extension=msql.dll
;
; ... or under UNIX:
;
extension=msql.so
;
; ... or with a path:
;
extension=/ffp/lib/extensions/no-debug-non-zts-20100525/mysql.so
;

extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_pdo_mssql.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll
extension=php_pgsql.dll
extension=pdo.so
extension=pdo_sqlite.so
extension=sqlite.so
extension=pdo_mysql.so

The outstanding issue is that when I run in phpinfo(), I see the module MySQLi activated but not MySQL.

MySQL is working as expected just as PHP and Lighttpd web server.

I equally have phpmyadmin working.

It's on a Zyxel NSA310.

Also, when mysqld is started, it creates a shortcut from my root to: ffp/opt/mysql.. and every time I restart my NAS the shortcut is deleted.

Does anyone might know a trick for this?


问:
How to detect if CSS @font-face is NOT used on a page?
For the purpose of Javascript based automated unused CSS removal we are looking for a solution to detect if a @font-face block is used on a page.

Is there an easy way to verify if a font is in use in the HTML?

The method getComputedStyle() would require to test each individual HTML element and would not be efficient.

 ...

```

答:
There is no API you can use or CSS selector for computed styles. (Old example with jQuery)
The only options you have is to iterate over the entire DOM, or simply use the Chrome css coverage

If you want to automate your solution you can always extend Chrome Dev tools


问:
Min and Max values of Float and Double types in Kotlin
It's simple to find out what the exact min and max values for Int and Long integers are in Kotlin:

Signed 32 bit Integer:

```<code>Int.MIN_VALUE       // -2147483648
Int.MAX_VALUE       //  2147483647
</code>```

Signed 64 bit Integer:

```<code>Long.MIN_VALUE      // -9223372036854775808
Long.MAX_VALUE      //  9223372036854775807
</code>```

However, if I try to print Float or Double types' ranges of min and max values, I'll get unbalanced numbers (where both values will be expressed using a scientific notation).

Signed 32 bit Floating Point Number:

```<code>Float.MIN_VALUE     //  1.4e-45
Float.MAX_VALUE     //  3.4028235e38
</code>```

Signed 64 bit Floating Point Number:

```<code>Double.MIN_VALUE    //  4.9e-324
Double.MAX_VALUE    //  1.7976931348623157e308
</code>```

Why the positive and negative values of Float and Double types are so "unbalanced"?

答:
The conceptual definition of MIN_VALUE is different for integers vs floating-point numbers.

Int.MIN_VALUE is the largest negative value.

Float.MIN_VALUE is the smallest positive value.

In other words, 1.4E-45 is 0.00[40 zeroes]0014, and not a very large negative number. The largest possible negative value is represented by -1 * Float.MAX_VALUE.

Body:
It's simple to find out what the exact min and max values for Int and Long integers are in Kotlin:

Signed 32 bit Integer:

Int.MIN_VALUE       // -2147483648
Int.MAX_VALUE       //  2147483647

Signed 64 bit Integer:

Long.MIN_VALUE      // -9223372036854775808
Long.MAX_VALUE      //  9223372036854775807

However, if I try to print Float or Double types' ranges of min and max values, I'll get unbalanced numbers (where both values will be expressed using a scientific notation).

Signed 32 bit Floating Point Number:

Float.MIN_VALUE     //  1.4e-45
Float.MAX_VALUE     //  3.4028235e38

Signed 64 bit Floating Point Number:

Double.MIN_VALUE    //  4.9e-324
Double.MAX_VALUE    //  1.7976931348623157e308

Why the positive and negative values of Float and Double types are so "unbalanced"?


问:
Alternative to VS for editing RS reports?
VS works I guess, but it's definitely pretty clunky in a lot of ways, and I was just wondering if there was some third-party alternative that's better.</p>

答: How about the first version of report builder? That was designed as a stripped down tool that is easy to use without all the "bloat" of visual studio</p>

ContentLicense: CC BY-SA 3.0


问:
Java: Design pattern for Pre and Post processing like Servlet filters offer
I need help in figuring out a design pattern. Requirements are as below:

MUST have a provision to support Pre processing before method call. Any one can extend API and add pre-processors

Similar to above but want Post processing

Closest example I can think of is Servlet filters which can be used to do pre and post processing but I want to do that in a simple Java application which will not be deployed on a server

答:
As far design pattern is considered, you can use Proxy design pattern which provides the ability to process before and after. You can check cglib dynamic proxy or you can learn more about AOP(Aspect oriented programming) for pre and post operation on a method. Still if you are interested to achieve the same with core java only, you can use JDK dynamic proxy using invocation handler. I provide complete example, please go through it.

AOP using dynamic proxy : https://github.com/debjava/aopusingjdkdynamicproxy

Pre-Processing : https://github.com/debjava/aopusingjdkdynamicproxy/blob/master/src/main/java/com/ddlab/rnd/aop/BeforeHandler.java

Post-Processing: https://github.com/debjava/aopusingjdkdynamicproxy/blob/master/src/main/java/com/ddlab/rnd/aop/AfterHandler.java

Apart from that, you can refer to the comments.


问:
How can I deserialize instances of a type that has read-only back-references to some container type also being deserialized?
Let's say I have two types, a Document and a Child.  The Child is nested fairly deeply within the Document, and contains a back-reference to the parent that must needs be passed into its constructor.  How can I deserialize such an object graph with Json.NET and pass the parent into the child's constructor?

Here's a concrete example, inspired by Pass constructor arguments when deserializing into a List(Of T) by Ama:

Class Document
    Public Property MyObjects as List(Of Child) = new List(Of Child)()
End Class

Class Child
    Private ReadOnly _Parent As Document

    Sub New(Parent As Document)
        _Parent = Parent
    End Sub

    Property Foo As String
    Property Bar As String

    Function GetParent() As Document
        Return _Parent
    End Function
End Class
```

<p>With the corresponding JSON:</p>

```{
  "MyObjects": [
    {
      "Foo": "foo",
      "Bar": "bar"
    }
  ]
}
```

Notes:

The parent reference in Child is read-only and must be passed into the constructor.

I cannot modify the class definitions for Document and Child.

Document and Child are more complicated that shown here, so loading into a JToken hierarchy then constructing manually is not preferred.

How can I deserialize JSON to such a data model, constructing the list of children with the parent properly initialized?

答:
Since the definitions for Document and Child cannot be modified, one way to do this would be with a custom contract resolver that returns contracts that track the current document being deserialized in some ThreadLocal(Of Stack(Of Document)) stack, and allocate instances of MyObject using the topmost document.

The following contract resolver does the job:

Public Class DocumentContractResolver
    Inherits DefaultContractResolver

    Private ActiveDocuments As ThreadLocal(Of Stack(Of Document)) = New ThreadLocal(Of Stack(Of Document))(Function() New Stack(Of Document))

    Protected Overrides Function CreateContract(ByVal objectType As Type) As JsonContract
        Dim contract = MyBase.CreateContract(objectType)
        Me.CustomizeDocumentContract(contract)
        Me.CustomizeMyObjectContract(contract)
        Return contract
    End Function

    Private Sub CustomizeDocumentContract(ByVal contract As JsonContract)
        If GetType(Document).IsAssignableFrom(contract.UnderlyingType) Then
            contract.OnDeserializingCallbacks.Add(Sub(o, c) ActiveDocuments.Value.Push(CType(o, Document)))
            contract.OnDeserializedCallbacks.Add(Sub(o, c) ActiveDocuments.Value.Pop())
        End If
    End Sub

    Private Sub CustomizeMyObjectContract(ByVal contract As JsonContract)
        If (GetType(Child) = contract.UnderlyingType) Then
            contract.DefaultCreator = Function() New Child(ActiveDocuments.Value.Peek())
            contract.DefaultCreatorNonPublic = false
        End If
    End Sub
End Class
```

<p>And then use it like:</p>

<pre class="lang-vb prettyprint-override"><code>Dim contractResolver = New DocumentContractResolver() ' Cache this statically somewhere
Dim settings = New JsonSerializerSettings() With { .ContractResolver = contractResolver }

Dim doc2 = JsonConvert.DeserializeObject(Of Document)(jsonString, settings)
</code>```

And in c#:

public class DocumentContractResolver : DefaultContractResolver
{
    ThreadLocal<Stack<Document>> ActiveDocuments = new ThreadLocal<Stack<Document>>(() => new Stack<Document>());

    protected override JsonContract CreateContract(Type objectType)
    {
        var contract = base.CreateContract(objectType);
        CustomizeDocumentContract(contract);
        CustomizeMyObjectContract(contract);
        return contract;
    }

    void CustomizeDocumentContract(JsonContract contract)
    {
        if (typeof(Document).IsAssignableFrom(contract.UnderlyingType))
        {
            contract.OnDeserializingCallbacks.Add((o, c) => ActiveDocuments.Value.Push((Document)o));
            contract.OnDeserializedCallbacks.Add((o, c) => ActiveDocuments.Value.Pop());
        }
    }

    void CustomizeMyObjectContract(JsonContract contract)
    {
        if (typeof(Child) == contract.UnderlyingType)
        {
            contract.DefaultCreator = () => new Child(ActiveDocuments.Value.Peek());
            contract.DefaultCreatorNonPublic = false;
        }
    }
}
```

Notes:

If an exception occurs during deserialization the ActiveDocuments might not get cleared properly.  You might want to add a serialization error handler to do that.

As explained in Newtonsoft's performance tips,

To avoid the overhead of recreating contracts every time you use JsonSerializer you should create the contract resolver once and reuse it.

ThreadLocal<T> is disposable, so if you don't plan to cache your WordContractResolver you should probably make it disposable also, and dispose of the threadlocal in the dispose method.

Demo fiddles here (vb.net) and here (c#).

Body:
Let's say I have two types, a Document and a Child.  The Child is nested fairly deeply within the Document, and contains a back-reference to the parent that must needs be passed into its constructor.  How can I deserialize such an object graph with Json.NET and pass the parent into the child's constructor?

Here's a concrete example, inspired by Pass constructor arguments when deserializing into a List(Of T) by Ama:

Class Document
    Public Property MyObjects as List(Of Child) = new List(Of Child)()
End Class

Class Child
    Private ReadOnly _Parent As Document

    Sub New(Parent As Document)
        _Parent = Parent
    End Sub

    Property Foo As String
    Property Bar As String

    Function GetParent() As Document
        Return _Parent
    End Function
End Class

With the corresponding JSON:

{
  "MyObjects": [
    {
      "Foo": "foo",
      "Bar": "bar"
    }
  ]
}

Notes:

The parent reference in Child is read-only and must be passed into the constructor.

I cannot modify the class definitions for Document and Child.

Document and Child are more complicated that shown here, so loading into a JToken hierarchy then constructing manually is not preferred.

How can I deserialize JSON to such a data model, constructing the list of children with the parent properly initialized?

Body:
Since the definitions for Document and Child cannot be modified, one way to do this would be with a custom contract resolver that returns contracts that track the current document being deserialized in some ThreadLocal(Of Stack(Of Document)) stack, and allocate instances of MyObject using the topmost document.

The following contract resolver does the job:

Public Class DocumentContractResolver
    Inherits DefaultContractResolver

    Private ActiveDocuments As ThreadLocal(Of Stack(Of Document)) = New ThreadLocal(Of Stack(Of Document))(Function() New Stack(Of Document))

    Protected Overrides Function CreateContract(ByVal objectType As Type) As JsonContract
        Dim contract = MyBase.CreateContract(objectType)
        Me.CustomizeDocumentContract(contract)
        Me.CustomizeMyObjectContract(contract)
        Return contract
    End Function

    Private Sub CustomizeDocumentContract(ByVal contract As JsonContract)
        If GetType(Document).IsAssignableFrom(contract.UnderlyingType) Then
            contract.OnDeserializingCallbacks.Add(Sub(o, c) ActiveDocuments.Value.Push(CType(o, Document)))
            contract.OnDeserializedCallbacks.Add(Sub(o, c) ActiveDocuments.Value.Pop())
        End If
    End Sub

    Private Sub CustomizeMyObjectContract(ByVal contract As JsonContract)
        If (GetType(Child) = contract.UnderlyingType) Then
            contract.DefaultCreator = Function() New Child(ActiveDocuments.Value.Peek())
            contract.DefaultCreatorNonPublic = false
        End If
    End Sub
End Class

And then use it like:

Dim contractResolver = New DocumentContractResolver() ' Cache this statically somewhere
Dim settings = New JsonSerializerSettings() With { .ContractResolver = contractResolver }

Dim doc2 = JsonConvert.DeserializeObject(Of Document)(jsonString, settings)

And in c#:

public class DocumentContractResolver : DefaultContractResolver
{
    ThreadLocal<Stack<Document>> ActiveDocuments = new ThreadLocal<Stack<Document>>(() => new Stack<Document>());

    protected override JsonContract CreateContract(Type objectType)
    {
        var contract = base.CreateContract(objectType);
        CustomizeDocumentContract(contract);
        CustomizeMyObjectContract(contract);
        return contract;
    }

    void CustomizeDocumentContract(JsonContract contract)
    {
        if (typeof(Document).IsAssignableFrom(contract.UnderlyingType))
        {
            contract.OnDeserializingCallbacks.Add((o, c) => ActiveDocuments.Value.Push((Document)o));
            contract.OnDeserializedCallbacks.Add((o, c) => ActiveDocuments.Value.Pop());
        }
    }

    void CustomizeMyObjectContract(JsonContract contract)
    {
        if (typeof(Child) == contract.UnderlyingType)
        {
            contract.DefaultCreator = () => new Child(ActiveDocuments.Value.Peek());
            contract.DefaultCreatorNonPublic = false;
        }
    }
}

Notes:

If an exception occurs during deserialization the ActiveDocuments might not get cleared properly.  You might want to add a serialization error handler to do that.

As explained in Newtonsoft's performance tips,

To avoid the overhead of recreating contracts every time you use JsonSerializer you should create the contract resolver once and reuse it.

ThreadLocal<T> is disposable, so if you don't plan to cache your WordContractResolver you should probably make it disposable also, and dispose of the threadlocal in the dispose method.

Demo fiddles here (vb.net) and here (c#).


问:
Pyinstaller on project with modules
I am trying to do a one file exe on my python 3.7 project with Pyinstaller. I have structured the project with package and modules and when I start the project from the terminal (Mac) it's working fine.

From terminal and in a folder one step above the project -

```<code>python3 -m my_module.mymain
</code>```

I have tried -

```<code>pyinstaller --onefile --windowed my_module.mymain
pyinstaller --onefile --windowed my_module.mymain.py
pyinstaller --onefile --windowed mymain
pyinstaller --onefile --windowed mymain.py
</code>```

the last two in the same folder as the mymain.py.

Nothing of the above works, thanks for any help.

答:
First a python shell then import the wanted module and do :

import my_module
print(my_module.__file__)
```

<p>Then you will have the file of your module, then simply do pyinstaller on this file.</p>

<p>If that doesn't work create a micro python file just firing your module and execute pyinstaller on this file.</p>

<p>PS:</p>

```pyinstaller --onefile --windowed my_module.mymain.py
```

Doesn't work because here you never said to pyinstaller to read from module, here pyinstaller try to read a file named my_module.mymain.py in the current directory.

Title: Pyinstaller on project with modules

Body:
I am trying to do a one file exe on my python 3.7 project with Pyinstaller. I have structured the project with package and modules and when I start the project from the terminal (Mac) it's working fine.

From terminal and in a folder one step above the project -

python3 -m my_module.mymain

I have tried -

pyinstaller --onefile --windowed my_module.mymain
pyinstaller --onefile --windowed my_module.mymain.py
pyinstaller --onefile --windowed mymain
pyinstaller --onefile --windowed mymain.py

the last two in the same folder as the mymain.py.

Nothing of the above works, thanks for any help.

Body:
First a python shell then import the wanted module and do :

import my_module
print(my_module.__file__)

Then you will have the file of your module, then simply do pyinstaller on this file.

If that doesn't work create a micro python file just firing your module and execute pyinstaller on this file.

PS:

pyinstaller --onefile --windowed my_module.mymain.py

Doesn't work because here you never said to pyinstaller to read from module, here pyinstaller try to read a file named my_module.mymain.py in the current directory.


问:
Hyphen and vertical line in bash
I am trying to decipher the following code:

```<code>awk '{print "aws s3 cp ###"$4" - | gunzip | awk -F $\"\\t\" '"'"'BEGIN {OFS = FS} {if ($287 == \"0\" && tolower($295)) print $11}'"'"' > "gensub(/.+\/(.+tsv\.gz)/,output_path"\\1.txt",$4)}'
</code>```

However, I am not sure about a couple of things:

1) What "-" does. I know "|" is used for piping but I really am not sure about "-" except in the context of negating some option. I tried googling "ubuntu hyphen/minus/dash" but nothing came up related to this

2) I am not sure about print "aws s3 cp ###"$4" either. It normally prints the lines satisfying the if conditions but here it takes an aws command string, following by $4 which I know is a column index

3) Also, I know that awk -F followed by a sign will designate the sign as the separator but here there is no sign. I do not understand the default behaviour in this case.

答:
That is a truly awful command line.

1) The hyphen is an option to the aws s3 cp command. It's unusual to see it used this way but it means that the destination of the copy is STDOUT and thus gets piped into gunzip. It's much more common to see a hyphen represent STDIN for data being piped into a command.

2) The print is outputting the aws s3 cp command along with all the rest of the pipeline (including an embedded instance of another AWK command).

3) The "sign" for the -F here is a tab character using (improperly) Bash's translation quoting ($" "). It should have used Bash's ANSI quoting ($' ') which allows for interpreting backslash escapes (\t represents the tab character). In any case, it's wasted since AWK can understand \t for -F without any special quoting.

This appears to be a variable that must be set elsewhere: output_path

The pipeline that is output by the outer AWK command will need to be fed to the shell in order to be executed.

Title: Hyphen and vertical line in bash

Body:
I am trying to decipher the following code:

awk '{print "aws s3 cp ###"$4" - | gunzip | awk -F $\"\\t\" '"'"'BEGIN {OFS = FS} {if ($287 == \"0\" && tolower($295)) print $11}'"'"' > "gensub(/.+\/(.+tsv\.gz)/,output_path"\\1.txt",$4)}'

However, I am not sure about a couple of things:

1) What "-" does. I know "|" is used for piping but I really am not sure about "-" except in the context of negating some option. I tried googling "ubuntu hyphen/minus/dash" but nothing came up related to this

2) I am not sure about print "aws s3 cp ###"$4" either. It normally prints the lines satisfying the if conditions but here it takes an aws command string, following by $4 which I know is a column index

3) Also, I know that awk -F followed by a sign will designate the sign as the separator but here there is no sign. I do not understand the default behaviour in this case.


问:
How to check edittext's text is email address or not?
how to check the text of edittext is email address or not without using javascript and regular expression?
Here I used inputtype="textEmailAddress" this is working but no error message is display.

答:
With android.util.Patterns and Kotlin it's very simple. One line function which return Boolean value.</p>

```<code>fun validateEmail(email: String) = Patterns.EMAIL_ADDRESS.matcher(email)
</code>```

Body:
With android.util.Patterns and Kotlin it's very simple. One line function which return Boolean value.

fun validateEmail(email: String) = Patterns.EMAIL_ADDRESS.matcher(email)


问:
How to go about formatting 1200 to 1.2k in java
I'd like to format following numbers into the numbers next to them with java:

```<code>1000 to 1k
5821 to 5.8k
10500 to 10k
101800 to 101k
2000000 to 2m
7800000 to 7.8m
92150000 to 92m
123200000 to 123m
</code>```

The number on the right will be long or integer the number on the left will be string.
How should I approach this. I already did little algorithm for this but I thought there might be already something invented out there that does nicer job at it and doesn't require additional testing if I start dealing with billions and trillions :)

Additional Requirements:

The format should have maximum of 4 characters

The above means 1.1k is OK 11.2k is not. Same for 7.8m is OK 19.1m is not. Only one digit before decimal point is allowed to have decimal point. Two digits before decimal point means not digits after decimal point.

No rounding is necessary.  (Numbers being displayed with k and m appended are more of analog gauge indicating approximation not precise article of logic. Hence rounding is irrelevant mainly due to nature of variable than can increase or decrees several digits even while you are looking at the cached result.)

答:
The ICU lib has a rule based formatter for numbers, which can be used for number spellout etc. I think using ICU would give you a readable and maintanable solution.

[Usage]

The right class is RuleBasedNumberFormat. The format itself can be stored as separate file (or as String constant, IIRC).

Example from http://userguide.icu-project.org/formatparse/numbers

```<code>double num = 2718.28;
NumberFormat formatter =
    new RuleBasedNumberFormat(RuleBasedNumberFormat.SPELLOUT);
String result = formatter.format(num);
System.out.println(result);
</code>```

The same page shows Roman numerals, so I guess your case should be possible, too.

Body:
I'd like to format following numbers into the numbers next to them with java:

1000 to 1k
5821 to 5.8k
10500 to 10k
101800 to 101k
2000000 to 2m
7800000 to 7.8m
92150000 to 92m
123200000 to 123m

The number on the right will be long or integer the number on the left will be string.
How should I approach this. I already did little algorithm for this but I thought there might be already something invented out there that does nicer job at it and doesn't require additional testing if I start dealing with billions and trillions :)

Additional Requirements:

The format should have maximum of 4 characters

The above means 1.1k is OK 11.2k is not. Same for 7.8m is OK 19.1m is not. Only one digit before decimal point is allowed to have decimal point. Two digits before decimal point means not digits after decimal point.

No rounding is necessary.  (Numbers being displayed with k and m appended are more of analog gauge indicating approximation not precise article of logic. Hence rounding is irrelevant mainly due to nature of variable than can increase or decrees several digits even while you are looking at the cached result.)

Body:
The ICU lib has a rule based formatter for numbers, which can be used for number spellout etc. I think using ICU would give you a readable and maintanable solution.

[Usage]

The right class is RuleBasedNumberFormat. The format itself can be stored as separate file (or as String constant, IIRC).

Example from http://userguide.icu-project.org/formatparse/numbers

double num = 2718.28;
NumberFormat formatter =
    new RuleBasedNumberFormat(RuleBasedNumberFormat.SPELLOUT);
String result = formatter.format(num);
System.out.println(result);

The same page shows Roman numerals, so I guess your case should be possible, too.


问:
Can I see the backlog as a treeview when filtering out done items on Azure Boards?
I'm using the basic work item process in Azure DevOps.

If I look at my backlog without any filters, then it shows me a hierarchy, with epics as the top-level items, then issues and then work items.

If I filter this to only show items that are to do or doing, it shows them as a flat list, not a hierarchy.

Is there any way to see the items as a hierarchy, but filter out done items?

Update following Shayki Abramczyk's comment

The options button doesn't include an option to show parents...

答:
Go to the Work Item Query tab and create a work item query. Configure it to Tree view and let it follow the parent/child relation.

You can filter on the top level (top part of the query editor) and the lower levels (bottom part of the query editor). Use the State in filter to select multiple states. You can't multi-select them in the UI, so typing is required:

PS: The , is the list separator in most languages, but sometimes you need to use ;.

If you want to see parents when ANY child leaf is still open, set the Filter: Match top-level items first to Filter: Match child-level items first.

To specify the order, add the Backlog Priority field to the query and use the table header to sort by it:

Or use the Sorting option in the "Choose Columns" fly-out:

Note: The exact field name differs per Process template. Backlog Priority is for the Scrum Template, Stackrank for CMMI and Agile and Basic:

An easy way to get started is to take the board view closest to what you want and save it as a work item query.


问:
In unordered_map of C++11, how to update the value of a particular key?
In Java's hashmap:

```<code>map.put(key, new_value)
</code>```

will update the entry of key=key with new_value if it exists in the hashmap.

What's the correct way to do the similar thing in unordered_map of C++11?

I haven't found an API like updateXXX, and the documentation says the unordered_map::insert function will succeed only when there isn't any such pair with a key.

答:
If the type value has no default constructor you can use:

```<code>map.emplace(key, new_value).first->second = new_value;
</code>```

This also has all the other advantages of emplace vs [] operator and insert.

Body:
In Java's hashmap:

map.put(key, new_value)

will update the entry of key=key with new_value if it exists in the hashmap.

What's the correct way to do the similar thing in unordered_map of C++11?

I haven't found an API like updateXXX, and the documentation says the unordered_map::insert function will succeed only when there isn't any such pair with a key.

Body:
If the type value has no default constructor you can use:

map.emplace(key, new_value).first->second = new_value;

This also has all the other advantages of emplace vs [] operator and insert.


问:
By click on icon hide first parent
On click delete icon how can i remove first parent? I mean div with class box. I try everything and I haven't come to the solution yet

var deleteIcon = document.querySelectorAll('.delete-icon');
var box = document.querySelectorAll('.box');

deleteIcon.forEach(function(icon) {
        icon.addEventListener("click", function() {
            box.style.display = "none";
            // icon.style.display = "none";
        });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  width: 150px;
  height: 200px;
  background-color: #ccc;
  display: inline-block;
  margin: 10px;
  position: relative;
}

.delete-icon {
  position: absolute;
  bottom: 10px;
  right: 10px;
  cursor: pointer;
}</code>```

<link href"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" rel="stylesheet">

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

```

答:
You can select parent element by element object's parentElement property.

And to delete use 'remove' or removeChild method.

var deleteIcon = document.querySelectorAll('.delete-icon');
var box = document.querySelectorAll('.box');

deleteIcon.forEach(function(icon) {
  icon.addEventListener("click", function() {
    let parent = this.parentElement.parentElement;
    parent.parentElement.removeChild(parent);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  width: 150px;
  height: 200px;
  background-color: #ccc;
  display: inline-block;
  position: relative;
  margin: 5px;
}

.icon-test {
  position: absolute;
  bottom: 10px;
  right: 10px;
  cursor: pointer;
  height: 40px;
  width: 40px;
  background-color: #f99;
  border-radius: 50%;
}

.delete-icon {
  display: flex;
  height: 40px;
  width: 40px;
  align-items: center;
  justify-content: center;
}

.delete-icon::before {
  content: '\00D7';
  font-weight: bold;
  color: white;
  font-size: 2em;
}</code>```

<link href "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" rel="stylesheet">

1

2

3

4

    bla bla

box 1

1

2

3

4

    bla bla

box 2

1

2

3

4

    bla bla

box 3

1

2

3

4

    bla bla

box 4

1

2

3

4

    bla bla

box 5

1

2

3

4

    bla bla

box 6

```

Title: By click on icon hide first parent

Body:
On click delete icon how can i remove first parent? I mean div with class box. I try everything and I haven't come to the solution yet

var deleteIcon = document.querySelectorAll('.delete-icon');
var box = document.querySelectorAll('.box');

deleteIcon.forEach(function(icon) {
        icon.addEventListener("click", function() {
            box.style.display = "none";
            // icon.style.display = "none";
        });
    });

.box {
  width: 150px;
  height: 200px;
  background-color: #ccc;
  display: inline-block;
  margin: 10px;
  position: relative;
}

.delete-icon {
  position: absolute;
  bottom: 10px;
  right: 10px;
  cursor: pointer;
}

<link href"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" rel="stylesheet">

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

1

2

3

4

     bla bla

nothing1

nothing2

nothing3

Body:
You can select parent element by element object's parentElement property.

And to delete use 'remove' or removeChild method.

var deleteIcon = document.querySelectorAll('.delete-icon');
var box = document.querySelectorAll('.box');

deleteIcon.forEach(function(icon) {
  icon.addEventListener("click", function() {
    let parent = this.parentElement.parentElement;
    parent.parentElement.removeChild(parent);
  });
});

.box {
  width: 150px;
  height: 200px;
  background-color: #ccc;
  display: inline-block;
  position: relative;
  margin: 5px;
}

.icon-test {
  position: absolute;
  bottom: 10px;
  right: 10px;
  cursor: pointer;
  height: 40px;
  width: 40px;
  background-color: #f99;
  border-radius: 50%;
}

.delete-icon {
  display: flex;
  height: 40px;
  width: 40px;
  align-items: center;
  justify-content: center;
}

.delete-icon::before {
  content: '\00D7';
  font-weight: bold;
  color: white;
  font-size: 2em;
}

<link href "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" rel="stylesheet">
<div class="box">
  <ul class="nothing">
    <li class="blabla">1</li>
    <li class="blabla">2</li>
    <li class="blabla">3</li>
    <li class="blabla">4</li>
    <span>bla bla</span>
  </ul>
  <div>box 1</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>

<div class="box">
  <ul class="nothing">
    <li class="blabla">1</li>
    <li class="blabla">2</li>
    <li class="blabla">3</li>
    <li class="blabla">4</li>
    <span>bla bla</span>
  </ul>
  <div>box 2</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>

<div class="box">
  <ul class="nothing">
    <li class="blabla">1</li>
    <li class="blabla">2</li>
    <li class="blabla">3</li>
    <li class="blabla">4</li>
    <span>bla bla</span>
  </ul>
  <div>box 3</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>

<div class="box">
  <ul class="nothing">
    <li class="blabla">1</li>
    <li class="blabla">2</li>
    <li class="blabla">3</li>
    <li class="blabla">4</li>
    <span>bla bla</span>
  </ul>
  <div>box 4</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>

<div class="box">
  <ul class="nothing">
    <li class="blabla">1</li>
    <li class="blabla">2</li>
    <li class="blabla">3</li>
    <li class="blabla">4</li>
    <span>bla bla</span>
  </ul>
  <div>box 5</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>

<div class="box">
  <ul class="nothing">
    <li class="blabla">1</li>
    <li class="blabla">2</li>
    <li class="blabla">3</li>
    <li class="blabla">4</li>
    <span>bla bla</span>
  </ul>
  <div>box 6</div>

  <div class="icon-test">
    <i class="fas fa-times-circle delete-icon"></i>
  </div>
</div>


问:
cakePHP query using find() method
how can I convert this query to use cakePHP's method find() ?

query:

```<code>SELECT Ch.id, COUNT( DU.d_id ) AS a, SUM(DU.d_id) AS b
FROM c AS Ch
LEFT JOIN du AS DU ON DU.c_id = Ch.id AND MONTH( DU.created ) = MONTH( NOW( ) )
LEFT JOIN d AS D ON DU.d_id = D.id
GROUP BY Ch.id
</code>```

答:
```<code>$Ch->find(
    'all',
    'fields' => array(
               'Ch.id','COUNT( DU.d_id ) AS a', 'SUM(DU.d_id) AS b'),
    'joins'  => array(
                      array(
                            'table' => 'du',
                            'alias' => 'DU',
                            'type' => 'LEFT',
                            'conditions' => array('DU.c_id = Ch.id AND MONTH( DU.created ) = MONTH( NOW( )')),
                       array(
                            'table' => 'd',
                            'alias' => 'D',
                            'type' => 'LEFT',
                            'conditions' => array('DU.c_id = Ch.id AND MONTH( DU.created ) = MONTH( NOW( )')),
    'group' => 'Ch.id');
</code>```

I haven't tested. More info on Cake JOINs:

http://book.cakephp.org/view/1018/find

Title: cakePHP query using find() method

Body:
how can I convert this query to use cakePHP's method find() ?

query:

SELECT Ch.id, COUNT( DU.d_id ) AS a, SUM(DU.d_id) AS b
FROM c AS Ch
LEFT JOIN du AS DU ON DU.c_id = Ch.id AND MONTH( DU.created ) = MONTH( NOW( ) )
LEFT JOIN d AS D ON DU.d_id = D.id
GROUP BY Ch.id

Body:
$Ch->find(
    'all',
    'fields' => array(
               'Ch.id','COUNT( DU.d_id ) AS a', 'SUM(DU.d_id) AS b'),
    'joins'  => array(
                      array(
                            'table' => 'du',
                            'alias' => 'DU',
                            'type' => 'LEFT',
                            'conditions' => array('DU.c_id = Ch.id AND MONTH( DU.created ) = MONTH( NOW( )')),
                       array(
                            'table' => 'd',
                            'alias' => 'D',
                            'type' => 'LEFT',
                            'conditions' => array('DU.c_id = Ch.id AND MONTH( DU.created ) = MONTH( NOW( )')),
    'group' => 'Ch.id');

I haven't tested. More info on Cake JOINs:

http://book.cakephp.org/view/1018/find


问:
Android ConstraintLayout baseline constraint not visible
Learning ConstraintLayout and running into this issue where the baseline constraint handle does not become visible even as a text view is selected.

Using Android Studio 3.4.1, Show All Constraints is selected.

gradle:

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.example.myapplication"
    minSdkVersion 28
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

答:
In the visual editor select the wanted TextView.

Right-click on it.

Select "Show Baseline"

Body:
Learning ConstraintLayout and running into this issue where the baseline constraint handle does not become visible even as a text view is selected.

Using Android Studio 3.4.1, Show All Constraints is selected.

gradle:

apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.example.myapplication"
    minSdkVersion 28
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


问:
System.Random producing the same random number
Despite the Random generator only being created once, the output is always the same random result (for all three test outputs).

A test snippet from a slightly larger script:

```<code>   let myRandGen = System.Random()
   let getRandomObject =
      let options = [|"Bob"; "Jim"; "Jane"|]
      let randIndex  = myRandGen.Next(options.Length)
      options.[randIndex]

   printfn "New one: %s" getRandomObject
   printfn "New two: %s" getRandomObject
   printfn "New three: %s" getRandomObject
</code>```

I need the output to be random for each call, which it currently isn't.

Example output:

```<code>New one: Jane
New two: Jane
New three: Jane
</code>```

答:
This works for me:</p>

```<code>   let myRandGen = System.Random()
   let getRandomObject () =
      let options = [|"Bob"; "Jim"; "Jane"|]
      let randIndex  = myRandGen.Next(options.Length)
      options.[randIndex]

   printfn "New one: %s" (getRandomObject())
   printfn "New two: %s" (getRandomObject())
   printfn "New three: %s" (getRandomObject())

</code>```

Body:
Despite the Random generator only being created once, the output is always the same random result (for all three test outputs).

A test snippet from a slightly larger script:

   let myRandGen = System.Random()
   let getRandomObject =
      let options = [|"Bob"; "Jim"; "Jane"|]
      let randIndex  = myRandGen.Next(options.Length)
      options.[randIndex]

   printfn "New one: %s" getRandomObject
   printfn "New two: %s" getRandomObject
   printfn "New three: %s" getRandomObject

I need the output to be random for each call, which it currently isn't.

Example output:

New one: Jane
New two: Jane
New three: Jane

Body:
This works for me:

   let myRandGen = System.Random()
   let getRandomObject () =
      let options = [|"Bob"; "Jim"; "Jane"|]
      let randIndex  = myRandGen.Next(options.Length)
      options.[randIndex]

   printfn "New one: %s" (getRandomObject())
   printfn "New two: %s" (getRandomObject())
   printfn "New three: %s" (getRandomObject())


问:
How can Java prevent duplicated number creation with Random class?
I'm learning Java by reading the book "JAVA, How To Program", and I have reached chapter 7 which talks about array and arrays manipulations. In section 7.5 (case study: card shuffling and dealing simulation), it presents a program that creates a deck of cards, shuffles it and displays the shuffled cards without any duplicates.

In the program it uses the method shuffle to shuffle the cards after creating them. The method uses random object to create a random number between 0 and 51 to select a card from the deck and assign it to an array. The code:

```<code> public void shuffle() {
     // after shuffling, dealing should start at deck[ 0 ] again
     currentCard = 0; // reinitialize currentCard

     // for each Card, pick another random Card (0-51) and swap them
     for (int first = 0; first < deck.length; first++) {
         // select a random number between 0 and 51
         int second = randomNumbers.nextInt( NUMBER_OF_CARDS );

         // swap current Card with randomly selected Card
         Card temp = deck[ first ];
         deck[ first ] = deck[ second ];
         deck[ second ] = temp;
    }
}
</code>```

What if int second = randomNumbers.nextInt( Number_OF_CARDS );
generates a random number that is already selected? Wouldn't be there any duplicates in the deck? If this not the case, why duplicated numbers are not given by this line? What am I missing?

I have learnt that random numbers are generated "almost" equally between the range given, but there is still a chance for generating a number that is already generated before.

答:
Here is an algorithm that I learned many years ago.  The key is to continually decrement the limit for the random number so you you won't replace what has already been replaced.

public class ShuffleDemo {
   int max = 10;

   public static void main(String[] args) {
      new ShuffleDemo().shuffle();
   }

   public void shuffle() {
      // start off with an array of 1 to max
      int[] vals = IntStream.rangeClosed(0, max).toArray();
      while (max > 0) {
         int selection = ThreadLocalRandom.current().nextInt(max);
         int temp = vals[max - 1];
         vals[max - 1] = vals[selection];
         vals[selection] = temp;
         max--;
      }

      System.out.println(Arrays.toString(vals));
   } // end method
}

```

It is still possible for a card to end up in its original position. But then, that can also happen with a real deck

Body:
I'm learning Java by reading the book "JAVA, How To Program", and I have reached chapter 7 which talks about array and arrays manipulations. In section 7.5 (case study: card shuffling and dealing simulation), it presents a program that creates a deck of cards, shuffles it and displays the shuffled cards without any duplicates.

In the program it uses the method shuffle to shuffle the cards after creating them. The method uses random object to create a random number between 0 and 51 to select a card from the deck and assign it to an array. The code:

 public void shuffle() {
     // after shuffling, dealing should start at deck[ 0 ] again
     currentCard = 0; // reinitialize currentCard

     // for each Card, pick another random Card (0-51) and swap them
     for (int first = 0; first < deck.length; first++) {
         // select a random number between 0 and 51
         int second = randomNumbers.nextInt( NUMBER_OF_CARDS );

         // swap current Card with randomly selected Card
         Card temp = deck[ first ];
         deck[ first ] = deck[ second ];
         deck[ second ] = temp;
    }
}

What if int second = randomNumbers.nextInt( Number_OF_CARDS );
generates a random number that is already selected? Wouldn't be there any duplicates in the deck? If this not the case, why duplicated numbers are not given by this line? What am I missing?

I have learnt that random numbers are generated "almost" equally between the range given, but there is still a chance for generating a number that is already generated before.

Body:
Here is an algorithm that I learned many years ago.  The key is to continually decrement the limit for the random number so you you won't replace what has already been replaced.

public class ShuffleDemo {
   int max = 10;

   public static void main(String[] args) {
      new ShuffleDemo().shuffle();
   }

   public void shuffle() {
      // start off with an array of 1 to max
      int[] vals = IntStream.rangeClosed(0, max).toArray();
      while (max > 0) {
         int selection = ThreadLocalRandom.current().nextInt(max);
         int temp = vals[max - 1];
         vals[max - 1] = vals[selection];
         vals[selection] = temp;
         max--;
      }

      System.out.println(Arrays.toString(vals));
   } // end method
}

It is still possible for a card to end up in its original position. But then, that can also happen with a real deck


问:
How to generate a dataset using tensor in Tensorflow
I need a Dataset kind of tensor, shape=[160000, 1, 2], I want to generate
combination like below, but from 0 to 400</p>

```<code>[[[0 0]]

[[0 1]]

[[0 2]]

[[0 3]]

[[1 0]]

[[1 1]]

[[1 2]]

[[1 3]]

[[2 0]]

[[2 1]]

[[2 2]]

[[2 3]]]
</code>```

答:
First create a numpy array and create tensor by using it. The following code outputs a tensor of shape = [160000, 1, 2] where each value is between 0 to 400.

```<code>import numpy as np
import tensorflow as tf
arr = np.random.random_integers(low=0, high=400, size=(160000, 1, 2))
tensor = tf.constant(arr)
</code>```

Body:
I need a Dataset kind of tensor, shape=[160000, 1, 2], I want to generate
combination like below, but from 0 to 400

[[[0 0]]

[[0 1]]

[[0 2]]

[[0 3]]

[[1 0]]

[[1 1]]

[[1 2]]

[[1 3]]

[[2 0]]

[[2 1]]

[[2 2]]

[[2 3]]]

Body:
First create a numpy array and create tensor by using it. The following code outputs a tensor of shape = [160000, 1, 2] where each value is between 0 to 400.

import numpy as np
import tensorflow as tf
arr = np.random.random_integers(low=0, high=400, size=(160000, 1, 2))
tensor = tf.constant(arr)


问:
how can display image from this query in php throw json
```<code>"NewsML":   [
        {
 "Identification": {"NewsIdentifier":       {
        "ProviderId": "timesofindia.com",
        "NewsItemId": "7954765"
      }},
      "NewsLines":       {
        "HeadLine": "I want KKR to win for Ganguly: Shah Rukh",
        "DateLine": "IANS, Apr 12, 2011, 04.41am IST"
      },
      "NewsComponent":       [
                {
          "Role": {"@FormalName": "WebURL"},
          "ContentItem":           {
            "MediaType": {"@FormalName": "Link"},
            "DataContent": {"media-caption": "http://timesofindia.indiatimes.com/sports/cricket/ipl-2011/news/I-want-KKR-to-win-for-Ganguly-Shah-Rukh/articleshow/7954765.cms"}
          }
        },
                {
          "Role": {"@FormalName": "Caption"},
          "ContentItem":           {
            "MediaType": {"@FormalName": "Text"},
            "DataContent": {"media-caption": "Aware of the negative vibes in Kolkata after the exclusion of Dada from the team, Shah Rukh Khan dedicated his team's victory to Sourav Ganguly."}
          }
        },
                {
          "Role": {"@FormalName": "Keywords"},
          "ContentItem":           {
            "MediaType": {"@FormalName": "Text"},
            "DataContent": {"media-keyword": "Sourav Ganguly, Shah Rukh Khan, KKR, IPL"}
          }
        },
                {
          "Role": {"@FormalName": "Photo"},
          "ContentItem":           {
            "@Href": "http://timesofindia.indiatimes.com/photo.cms?photoid=7954812&phototype=1&width=400&height=300",
            "MediaType": {"@FormalName": "Photo"},
            "Format": {"@FormalName": "JPEG Baseline"},
            "Characteristics":             [
                            {
                "@FormalName": "Width",
                "@Value": "450"
              },
                            {
                "@FormalName": "Height",
                "@Value": "300"
              }
            ]
          }
        },
                {
          "Role": {"@FormalName": "Photo-Caption"},
          "ContentItem":           {
            "MediaType": {"@FormalName": "Text"},
            "DataContent": {"media-caption": "Kolkata Knight Riders owner Saha Rukh Khan greets his supporters during their IPL match against Deccan Chargers at Eden Gardens. (PTI photo)"}
          }
        },
                {
          "Role": {"@FormalName": "Thumb"},
          "ContentItem":           {
            "@Href": "http://timesofindia.indiatimes.com/thumb.cms?photoid=7954812",
            "MediaType": {"@FormalName": "Photo"},
            "Format": {"@FormalName": "JPEG Baseline"}
          }
        },
                {
          "Role": {"@FormalName": "Story"},
          "ContentItem":           {
            "MediaType": {"@FormalName": "Text"},
            "DataContent": {"body": {"body.content": "KOLKATA: Aware of the negative vibes in Kolkata after the exclusion of local boy Sourav Ganguly from the team, Kolkata Knight Riders co-owner Shah Rukh Khan on Monday night dedicated his team's nine-run victory to Sourav Ganguly and the sports loving people of the city.\n\nI came back only for the fans. I wanted to do this for Knight Riders, the fans of Kolkata, I wanted to do this for Sourav Ganguly.\n\nI want my team KKR to win the IPL for Kolkata and Sourav Ganguly, said the matinee idol.\n\nI am very happy. It was really a cool moment. (Skipper Gautam) Gambhir and (Jacques) Kallis were really cool. It was really a cool moment as our team is unused to wins, said Shah Rukh Khan after KKR clinched their first win in IPL edition four.\n\nShah Rukh also expressed his disappointment over unnecessary controversies revolving the team for the last three seasons.\n\nA win is always welcome. We had lot of unnecessary controversies in the last three seasons, said Shah Rukh. "}}
          }
        }
      ]
    },
      }
]
</code>```

答:
So, you want to display it to user? Maybe I misunderstood you, but you can just parse it in php with json_decode();

Also, you can parse JSON output from php with JQuery and add image to HTML DOM.


问:
How do you update the firebase database when a user joins and leaves using discord.js + node.js
Once I've created X database using firebase how do you update the database when a user leaves (using discord.js + node.js). I have this already.

```<code>bot.on('guildCreate', async gData => {
  db.collection('guilds').doc(gData.id).set({
    'guildID': gData.id,
    'guildName': gData.name,
    'guildOwner': gData.owner.user.username,
    'guildOwnerID': gData.owner.id,
    'guildMemberCount': gData.memberCount,
    'prefix': '!'
  });
});
</code>```

This creates my entries on my database

答:
The events you need are guildMemberAdd and guildMemberRemove, and you can use them like so:

bot.on('guildMemberAdd', member => {
  // database query
});

bot.on('guildMemberRemove', member => {
  // database query
});
```

Discord.js Docs

Body:
Once I've created X database using firebase how do you update the database when a user leaves (using discord.js + node.js). I have this already.

bot.on('guildCreate', async gData => {
  db.collection('guilds').doc(gData.id).set({
    'guildID': gData.id,
    'guildName': gData.name,
    'guildOwner': gData.owner.user.username,
    'guildOwnerID': gData.owner.id,
    'guildMemberCount': gData.memberCount,
    'prefix': '!'
  });
});

This creates my entries on my database

Body:
The events you need are guildMemberAdd and guildMemberRemove, and you can use them like so:

bot.on('guildMemberAdd', member => {
  // database query
});

bot.on('guildMemberRemove', member => {
  // database query
});

Discord.js Docs


问:
backward difference encoding
This tutorial discussed the information about BackWard difference encoding:

Backward Difference Encoding

This technique falls under the contrast coding system for categorical features. A feature of K categories, or levels, usually enters a regression as a sequence of K-1 dummy variables. In backward difference coding, the mean of the dependent variable for a level is compared with the mean of the dependent variable for the prior level. This type of coding may be useful for a nominal or an ordinal variable.

If you want to learn other contrast coding methods you can check out this resource.

The code structure is pretty much the same as any method in the category_encoders library, just this time you will call BackwardDifferenceEncoder from it

as it said, it will transform k categories into k-1 binary categories.

I used this method on its database. For 'carriers', we had 11 categories and what we received after encoding is also 11 categories. Isn't it supposed to be 10 categories or 10 columns of binary values?

```<code>df_flights = pd.read_csv('https://raw.githubusercontent.com/ismayc/pnwflights14/master/data/flights.csv')

df_flights.head()

df_flights['carrier'].unique()
</code>```

so we have 11 unique categories.

```<code>!pip install category_encoders
import category_encoders as ce
cat_df_flights = df_flights.select_dtypes(include=['object']).copy()
encoder = ce.BackwardDifferenceEncoder(cols=['carrier'])
df_bd = encoder.fit_transform(cat_df_flights)

df_bd.head()
</code>```

the outcome is also 11 columns of binary data but based on what this tutorial said, it should be 10...

答: I am unsure but probably it's because you can infer the remaining class. For instance, imagine you have two colors {red, blue} and you want encode that variable. One option is to create two columns, one for red and other for blue, but you could also create just n - 1 columns for example "red"; if the value is 1 then the sample is red otherwise is blue.

Title: backward difference encoding

Body:
This tutorial discussed the information about BackWard difference encoding:

Backward Difference Encoding

This technique falls under the contrast coding system for categorical features. A feature of K categories, or levels, usually enters a regression as a sequence of K-1 dummy variables. In backward difference coding, the mean of the dependent variable for a level is compared with the mean of the dependent variable for the prior level. This type of coding may be useful for a nominal or an ordinal variable.

If you want to learn other contrast coding methods you can check out this resource.

The code structure is pretty much the same as any method in the category_encoders library, just this time you will call BackwardDifferenceEncoder from it

as it said, it will transform k categories into k-1 binary categories.

I used this method on its database. For 'carriers', we had 11 categories and what we received after encoding is also 11 categories. Isn't it supposed to be 10 categories or 10 columns of binary values?

df_flights = pd.read_csv('https://raw.githubusercontent.com/ismayc/pnwflights14/master/data/flights.csv')

df_flights.head()

df_flights['carrier'].unique()

so we have 11 unique categories.

!pip install category_encoders
import category_encoders as ce
cat_df_flights = df_flights.select_dtypes(include=['object']).copy()
encoder = ce.BackwardDifferenceEncoder(cols=['carrier'])
df_bd = encoder.fit_transform(cat_df_flights)

df_bd.head()

the outcome is also 11 columns of binary data but based on what this tutorial said, it should be 10...


问:
Filter only if variable condition is not undefined
This is my router:

```<code>reportRoutes.route('/:id').get(async (req, res) => {
    try{
        let id = req.params.id
        console.log(req.query)
        let team = req.query.team
        let league_acronym = req.query.league
        console.log('team',team)
        let regex = new RegExp( id, 'i')
        const report = await Report.find({ title: regex })
            .populate({path: 'like'})
            .populate({
                path: 'player',
                populate: [{ path: 'team' },
                {
                    path: 'team',
                    populate: {
                        path: 'league'
                    }
                }
            ]
            })

            if(league_acronym) {
                newReport = report.filter((v,i) => {
                    return v.player.team.league.acronym === league_acronym  && v.player.team.team_name === team
                })
                res.json(newReport)
            } else{
                res.json(report)
            }
    }  catch (e) {
        res.status(500).send()
    }
})
</code>```

I'm trying to setup a filter that goes through report and returns newReport.

The conditions that it will filter on are based on query string parameters.

Because query string parameters will not always be present, I need a way to filter on a condition, only if the condition exists. Thoughts?

答:
You could check for the respective conditions only if there is a value in league_acronym and team

```<code>newReport = report.filter(v =>
  (!league_acronym || v.player.team.league.acronym === league_acronym)
  && (!team || v.player.team.team_name === team)
)
</code>```

Body:
This is my router:

reportRoutes.route('/:id').get(async (req, res) => {
    try{
        let id = req.params.id
        console.log(req.query)
        let team = req.query.team
        let league_acronym = req.query.league
        console.log('team',team)
        let regex = new RegExp( id, 'i')
        const report = await Report.find({ title: regex })
            .populate({path: 'like'})
            .populate({
                path: 'player',
                populate: [{ path: 'team' },
                {
                    path: 'team',
                    populate: {
                        path: 'league'
                    }
                }
            ]
            })

            if(league_acronym) {
                newReport = report.filter((v,i) => {
                    return v.player.team.league.acronym === league_acronym  && v.player.team.team_name === team
                })
                res.json(newReport)
            } else{
                res.json(report)
            }
    }  catch (e) {
        res.status(500).send()
    }
})

I'm trying to setup a filter that goes through report and returns newReport.

The conditions that it will filter on are based on query string parameters.

Because query string parameters will not always be present, I need a way to filter on a condition, only if the condition exists. Thoughts?

Body:
You could check for the respective conditions only if there is a value in league_acronym and team

newReport = report.filter(v =>
  (!league_acronym || v.player.team.league.acronym === league_acronym)
  && (!team || v.player.team.team_name === team)
)


问:
Why HTML selection returns random string?
I have a <select> form on my webpage containing 4 options with values from 1 to 4, when choosing an option the form should return one of the numbers but it returns 6 random characters instead.

The page does not contain any JavaScript and it is running on my local network, I've also disabled JavaScript on my browser.

The PHP i'm using to retrieve the value is the following:

```<code>if (isset($_POST[$key])) {
    return $_POST[$key];
}
</code>```

I removed any form of validation, i simply retrieve the value with $_POST and if set it prints out 6 random characters ( every time i submit the form ).

The form is the following:

```<code><form action="/select_country" method="post" >
<select name="Country" class="country-selection">
    <option required="" selected="" disabled="" style="color: #b5b5be;">Country Location</option>
    <option value="1" >Asia</option>
    <option value="2" >Australia</option>
    <option value="3" >United States</option>
    <option value="4" >Europe</option>
</select>
</form>
</code>```

Expected result: 1 or 2 or 3 or 4

Actual result: czWe8m or alBwKD and so on...

EDIT:

The $_GET was a typo, sorry for that. Corrected.

I'm retrieving other input data from the same form using the same PHP code, the other tags are simple text and number <input> and they're working just fine:

<input name="Title" type="text" placeholder="Insert Title" maxlength="100" required="">
```

<pre class="lang-html prettyprint-override"><code><input name="Description" style="width:100%" type="text" placeholder="Insert Description" maxlength="1000" required="">
</code>```

答:
Your form has a select input and is set to use POST.
When it does submit the PHP will show you what was selected in the value
$_POST["Country"]

your first option is missing a value - so if that is submitted it may not show up as if they answered it. I suggest adding value="" so that it will be in the POST and you can validate that an option was chosen. Also, you need a submit button.

```<code><form action="/select_country" method="post" >
<select name="Country" class="country-selection">
    <option value="" required="" selected="" disabled="" style="color: #b5b5be;">Country Location</option>
    <option value="1" >Asia</option>
    <option value="2" >Australia</option>
    <option value="3" >United States</option>
    <option value="4" >Europe</option>
</select>
<input type="submit">
</form>
</code>```

and then:

```<code><?php
if (isset($_POST["Country"]) {
    if ($_POST["Country"] == "") {
        // error you must select an option
    }
    //other validation here but this should be 1,2,3 or 4
    // keep in mind anyone can mess with the form and submit other things maliciously so do validate

}
</code>```

Body:
I have a <select> form on my webpage containing 4 options with values from 1 to 4, when choosing an option the form should return one of the numbers but it returns 6 random characters instead.

The page does not contain any JavaScript and it is running on my local network, I've also disabled JavaScript on my browser.

The PHP i'm using to retrieve the value is the following:

if (isset($_POST[$key])) {
    return $_POST[$key];
}

I removed any form of validation, i simply retrieve the value with $_POST and if set it prints out 6 random characters ( every time i submit the form ).

The form is the following:

<form action="/select_country" method="post" >
<select name="Country" class="country-selection">
    <option required="" selected="" disabled="" style="color: #b5b5be;">Country Location</option>
    <option value="1" >Asia</option>
    <option value="2" >Australia</option>
    <option value="3" >United States</option>
    <option value="4" >Europe</option>
</select>
</form>

Expected result: 1 or 2 or 3 or 4

Actual result: czWe8m or alBwKD and so on...

EDIT:

The $_GET was a typo, sorry for that. Corrected.

I'm retrieving other input data from the same form using the same PHP code, the other tags are simple text and number <input> and they're working just fine:

<input name="Title" type="text" placeholder="Insert Title" maxlength="100" required="">

<input name="Description" style="width:100%" type="text" placeholder="Insert Description" maxlength="1000" required="">

Body:
Your form has a select input and is set to use POST.
When it does submit the PHP will show you what was selected in the value
$_POST["Country"]

your first option is missing a value - so if that is submitted it may not show up as if they answered it. I suggest adding value="" so that it will be in the POST and you can validate that an option was chosen. Also, you need a submit button.

<form action="/select_country" method="post" >
<select name="Country" class="country-selection">
    <option value="" required="" selected="" disabled="" style="color: #b5b5be;">Country Location</option>
    <option value="1" >Asia</option>
    <option value="2" >Australia</option>
    <option value="3" >United States</option>
    <option value="4" >Europe</option>
</select>
<input type="submit">
</form>

and then:

<?php
if (isset($_POST["Country"]) {
    if ($_POST["Country"] == "") {
        // error you must select an option
    }
    //other validation here but this should be 1,2,3 or 4
    // keep in mind anyone can mess with the form and submit other things maliciously so do validate

}


问:
facebook graph api friends_religion_politics permission problems
I'm working with facebook graph's api trying to get the users religion and political field.  I have the friends_religion_politics permission set and signed in but when I test the application on my account I only get one of my friends religion and political fields.

The general inquiry I'm making is:
https://graph.facebook.com/me/friends?access_token=%3Ctoken%3E&fields=religion,political

Confusingly enough when I run just that I get 4 friends religion and political views but still far from all of theres.

Am I doing something wrong on the permissions or is it something like the default privacy settings doesn't give apps acess to those fields?

答:
I am not sure that the access token has necessary permission to get political views. The fact that you are getting 4 friends whose political views you can see, does not mean that the permission setting is working properly.

When I queried my friends political view from Facebook reference api site, I was able to get political views of two of my friends. May be those two friends have  customized their privacy setting to allow everyone to see their political view. (By the way the political opition of both those friends were   "political": "Not Interested In Politics (Nil)",
).

I will create a test case. In case, if you have a  friend to help you with, you can ask him to open up his political view and then query again. And also ask one of your friend whose political view is already visible to your application, to see if he did customize his privacy setting.

Also I hope that you have an expiring access token. May be you have an offline_access permission and this creates an long living access token. You should try invalidating your token if you think this could be your problem.

ContentLicense: CC BY-SA 2.5


问:
How to compare function instance object with an empty object
I wrote a test case for a function,where the expected object is like below,

"point": {
  "events": {}
}
```

<p>But what I am receiving is like below,</p>

<pre class="lang-js prettyprint-override"><code>"point": {
  "events": Object {
    "click": [Function click],
  }
</code>```

The code of the function that I am testing,

function testing() {
  "point": {
    "events": {
      "click": function() {
        return false;
      }
    }
  }
}
```

Here my test case is getting failed because of this,can anyone please help me.Thanks.

答:
your question is not clear, but you can do something like this. hope it helps

function testFunct(){}
const emptyObj = {};

console.log(typeof testFunct)
console.log(typeof emptyObj)```

Body:
I wrote a test case for a function,where the expected object is like below,

"point": {
  "events": {}
}

But what I am receiving is like below,

"point": {
  "events": Object {
    "click": [Function click],
  }

The code of the function that I am testing,

function testing() {
  "point": {
    "events": {
      "click": function() {
        return false;
      }
    }
  }
}

Here my test case is getting failed because of this,can anyone please help me.Thanks.