问:
Sphinx Error - WARNING "list-table" widths do not match the number of columns in table (1)
I'm working with Sphinx and the python Sphinx syntax is:

```<code>.. list-table:: Frozen Delights!
    :widths: 15 10 30 20
    :header-rows: 1

    * - Treat
        - Quantity
        - Description
    * - Albatross
        - 2.99
        - On a stick!
    * - Crunchy Frog
        - 1.49
        - If we took the bones out, it wouldn't be
        crunchy, now would it?
    * - Gannet Ripple
        - 1.99
        - On a stick!
</code>```

I keep getting the error when trying to generate the .rst file: WARNING "list-table" widths do not match the number of columns in table (1). I've tried several other examples from Sphinx documentation and several others, nothing appears to work.

Body:
I'm working with Sphinx and the python Sphinx syntax is:

.. list-table:: Frozen Delights!
    :widths: 15 10 30 20
    :header-rows: 1

    * - Treat
        - Quantity
        - Description
    * - Albatross
        - 2.99
        - On a stick!
    * - Crunchy Frog
        - 1.49
        - If we took the bones out, it wouldn't be
        crunchy, now would it?
    * - Gannet Ripple
        - 1.99
        - On a stick!

I keep getting the error when trying to generate the .rst file: WARNING "list-table" widths do not match the number of columns in table (1). I've tried several other examples from Sphinx documentation and several others, nothing appears to work.

Body:
I know this doesn't really answer your original question, but I'm having the same issue and the only solution for me was to switch to the other format supported by Sphinx:

+------------+------------+-----------+------------+-----------+
| Header 1   | Header 2   | Header 3  | Header 1   | Header 3  |
+============+============+===========+============+===========+
| body row 1 | column 2   | column 3  | body row 1 | column 3  |
+------------+------------+-----------+------------+-----------+
| body row 1 | column 2   | column 3  | body row 1 | column 3  |
+------------+------------+-----------+------------+-----------+
| body row 1 | column 2   | column 3  | body row 1 | column 3  |
+------------+------------+-----------+------------+-----------+
| body row 1 | column 2   | column 3  | body row 1 | column 3  |
+------------+------------+-----------+------------+-----------+


来源: stackexchange

问:
No such file or directory: 'profile_pics/img.jpg'
When a user attempts to upload a profile picture this error is displayed. However the image is successfully uploaded to the database and displayed in the app. I believe the error is something to do with the redirection after the form submits but I couldn't figure it out. I recently set my app up with aws s3 buckets so that might also have something to do with it but the images are successfully uploaded and pulled from the bucket so likely un related.

view:

```<code>def profile(request):
    if request.method == 'POST':
        p_form = ProfileUpdateForm(request.POST,
                                   request.FILES,
                                   instance=request.user.profile)
        if p_form.is_valid():
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')

    else:
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'p_form': p_form
    }

    return render(request, 'users/profile.html', context)
</code>```

model:

```<code>class Profile(models.Model):
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    ....
    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super(Profile,self).save(*args, **kwargs)

        img = Image.open(self.image.name)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)
</code>```

html

```<code><form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <fieldset class="form-group">
        <legend class="border-bottom mb-4">Update Profile</legend>
        {{ p_form|crispy }}
    </fieldset>
    <div class="form-group">
        <button class="action-btn" type="submit">Update</button>
    </div>
</form>
</code>```

答:
You can use this for resize or compress image.</p>
```<code>def compress(image):
                im = Image.open(image)
                out_put_size = (300,300)
                im.thumbnail(out_put_size)
                # create a BytesIO object
                im_io = BytesIO()
                # save image to BytesIO object
                im = im.resize([500,500])
                #resize image
                im = im.convert("RGB")
                im = im.save(im_io,'JPEG', quality=50)
                # create a django-friendly Files object
                new_image = File(im_io, name=image.name)
                return new_image

class Profile(models.Model):
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

   def save(self, *args, **kwargs):
      #image compression start
      if self.image:
         # call the compress function
         new_image = compress(self.image)
         # set self.image to new_image
         self.image = new_image
      #image compression end
      super(Profile,self).save(*args, **kwargs)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When a user attempts to upload a profile picture this error is displayed. However the image is successfully uploaded to the database and displayed in the app. I believe the error is something to do with the redirection after the form submits but I couldn't figure it out. I recently set my app up with aws s3 buckets so that might also have something to do with it but the images are successfully uploaded and pulled from the bucket so likely un related.

view:

def profile(request):
    if request.method == 'POST':
        p_form = ProfileUpdateForm(request.POST,
                                   request.FILES,
                                   instance=request.user.profile)
        if p_form.is_valid():
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')

    else:
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'p_form': p_form
    }

    return render(request, 'users/profile.html', context)

model:

class Profile(models.Model):
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    ....
    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, *args, **kwargs):
        super(Profile,self).save(*args, **kwargs)

        img = Image.open(self.image.name)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

html

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <fieldset class="form-group">
        <legend class="border-bottom mb-4">Update Profile</legend>
        {{ p_form|crispy }}
    </fieldset>

        <button class="action-btn" type="submit">Update</button>

</form>

Body:
You can use this for resize or compress image.

def compress(image):
                im = Image.open(image)
                out_put_size = (300,300)
                im.thumbnail(out_put_size)
                # create a BytesIO object
                im_io = BytesIO()
                # save image to BytesIO object
                im = im.resize([500,500])
                #resize image
                im = im.convert("RGB")
                im = im.save(im_io,'JPEG', quality=50)
                # create a django-friendly Files object
                new_image = File(im_io, name=image.name)
                return new_image

class Profile(models.Model):
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

   def save(self, *args, **kwargs):
      #image compression start
      if self.image:
         # call the compress function
         new_image = compress(self.image)
         # set self.image to new_image
         self.image = new_image
      #image compression end
      super(Profile,self).save(*args, **kwargs)


问:
Remove specific user from a numbered group that I don't know the number of
As Title states, I am trying to use Powershell to remove a user from an Active Directory group that has the naming scheme of Group # with group always being the same word but the # being anything 1-20.  Not sure which group the specific user is a part of so I am trying to use a wildcard "*" but it doesn't seem to want to work with

```<code>Import-Module ActiveDirectory
Remove-ADGroupMember -Identity "Group *" -Members "test"
</code>```

Thanks

答:
The -Identity parameter is for when you have a single distinct group identity (a distinguished name, SAMAccountName, security identifier, or object GUID of an existing group).

Instead, use Get-ADGroup with the -Filter parameter to search for the relevant groups, then pipe them to Remove-ADGroupMember:

```<code>Get-ADGroup -Filter "Name -like 'Group *'" |Remove-ADGroupMember -Members "test"
</code>```

Body:
As Title states, I am trying to use Powershell to remove a user from an Active Directory group that has the naming scheme of Group # with group always being the same word but the # being anything 1-20.  Not sure which group the specific user is a part of so I am trying to use a wildcard "*" but it doesn't seem to want to work with

Import-Module ActiveDirectory
Remove-ADGroupMember -Identity "Group *" -Members "test"

Thanks

Body:
The -Identity parameter is for when you have a single distinct group identity (a distinguished name, SAMAccountName, security identifier, or object GUID of an existing group).

Instead, use Get-ADGroup with the -Filter parameter to search for the relevant groups, then pipe them to Remove-ADGroupMember:

Get-ADGroup -Filter "Name -like 'Group *'" |Remove-ADGroupMember -Members "test"


问:
Moving data-frame columns as per defined extent
As shown below, let's assume we have a data frame with 1 'extent' column, and 10 'col' columns, of which only first 7 'cols' are filled in the beginning.

Note: Grey highlight in NA cells is just for aesthetics.

We need to move first 'extent' cells of col columns to the end by some vectorised formula or a function. The output should look like below:

I wrote following piece of code to do it, but it's not working:

```<code>df <- ifelse(df$extent > 0,
                  df[, c(1, 9:(9+df$extent), 2+df$extent:8,2:(1+df$extent),(9+df$extent):11)
                      ] ,df)
</code>```

I get the error as: "numerical expression has 3 elements: only the first used"

Please help me out.

答:
Inefficient, but a start:

myshift <- function(x, n = 1) { if (!length(x) || n == 0) return(x); x[(seq_along(x) - n - 1) %% length(x) + 1]; }
dat[-1] <- do.call(rbind, Map(function(z, n) myshift(z, n), asplit(as.matrix(dat[-1]), 1), dat$extent))
dat
#   extent   V1   V2 V3 V4 V5 V6 V7   V8   V9  V10
# 1      0    1    2  3  4  5  6  7 <NA> <NA> <NA>
# 2      1 <NA>    A  B  C  D  E  F    G <NA> <NA>
# 3      2 <NA> <NA>  a  b  c  d  e    f    g <NA>
```
<hr />
<p>Data</p>
<pre class="lang-r prettyprint-override"><code>dat <- structure(list(extent = 0:2, V1 = c("1", "A", "a"), V2 = c("2", "B", "b"), V3 = c("3", "C", "c"), V4 = c("4", "D", "d"), V5 = c("5", "E", "e"), V6 = c("6", "F", "f"), V7 = c("7", "G", "g"), V8 = c(NA, NA, NA), V9 = c(NA, NA, NA), V10 = c(NA, NA, NA)), row.names = c(NA, -3L), class = "data.frame")
</code>```

Body:
As shown below, let's assume we have a data frame with 1 'extent' column, and 10 'col' columns, of which only first 7 'cols' are filled in the beginning.

Note: Grey highlight in NA cells is just for aesthetics.

We need to move first 'extent' cells of col columns to the end by some vectorised formula or a function. The output should look like below:

I wrote following piece of code to do it, but it's not working:

df <- ifelse(df$extent > 0,
                  df[, c(1, 9:(9+df$extent), 2+df$extent:8,2:(1+df$extent),(9+df$extent):11)
                      ] ,df)

I get the error as: "numerical expression has 3 elements: only the first used"

Please help me out.

Body:
Inefficient, but a start:

myshift <- function(x, n = 1) { if (!length(x) || n == 0) return(x); x[(seq_along(x) - n - 1) %% length(x) + 1]; }
dat[-1] <- do.call(rbind, Map(function(z, n) myshift(z, n), asplit(as.matrix(dat[-1]), 1), dat$extent))
dat
#   extent   V1   V2 V3 V4 V5 V6 V7   V8   V9  V10
# 1      0    1    2  3  4  5  6  7 <NA> <NA> <NA>
# 2      1 <NA>    A  B  C  D  E  F    G <NA> <NA>
# 3      2 <NA> <NA>  a  b  c  d  e    f    g <NA>

Data

dat <- structure(list(extent = 0:2, V1 = c("1", "A", "a"), V2 = c("2", "B", "b"), V3 = c("3", "C", "c"), V4 = c("4", "D", "d"), V5 = c("5", "E", "e"), V6 = c("6", "F", "f"), V7 = c("7", "G", "g"), V8 = c(NA, NA, NA), V9 = c(NA, NA, NA), V10 = c(NA, NA, NA)), row.names = c(NA, -3L), class = "data.frame")


问:
Print a specific cell from a string array
I've created a class that includes people data named "Datiutente" and an object based on that class named "du". Every person has a name and a surname (with the set/get methods).

I want to create a system that can provide the user information on a specific person based on the position which they are stored in the array.

I tried using a variable named vd to ask the user which person wanted to visualize based on the position that a person gained in the array (inserted in the for cycle), but when I try to print with vd it just prints "Name: null". Same if I change "vd" to "1". It always prints "Null".

(Yes, I tested this when I already inserted some data.)

Here's the full code:

```<code>
package appartamento;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Appartamento {
    public static void main(String[] args) throws IOException {
        InputStreamReader input = new InputStreamReader(System.in);
        BufferedReader keyb = new BufferedReader(input);
        boolean attiva = true;

        do {
            System.out.println("what do you want to do?");
            System.out.println("1 - check for a person");
            System.out.println("2 - Add person");
            int choice = Integer.parseInt(keyb.readLine());
            Datiutente du[] = new Datiutente[10];

            if (choice == 2){
                System.out.println("How many people?");
                int hm = Integer.parseInt(keyb.readLine());

                for (int i=0;i<hm;i++){
                    du[i] = new Datiutente();
                    System.out.println("insert name:");
                    du[i].setName(keyb.readLine());
                    System.out.println("insert surname");
                    du[i].setSurname(keyb.readLine());
                }
            }

            if (choice == 1){
                System.out.println("which person are you searching?");
                int vd = Integer.parseInt(keyb.readLine());
                System.out.println("position: " + i);
                System.out.println("Name: "+  du[i]);
                System.out.println("Surname: " + du[i]);
            }
        } while (attiva = true);
    }
}
</code>```

and the class "Datiutente":

```<code>package appartamento;

public class Datiutente {
    private String name;
    private String surname;
    private String codfis;

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public void setSurname(String surname){
        this.surname = surname;
    }

    public String getSurname(){
        return surname;
    }
}
</code>```

答:
I found a way here:

You need to insert values on object creation, you can also use hashmaps

hashmap will benefit you more I think.

Code sample to fix your stuff.

```<code>class GFG {
    public static void main(String args[]){

    // Declaring an array of student
    Student[] arr;

    // Allocating memory for 2 objects
    // of type student
    arr = new Student[2];

    // Initializing the first element
    // of the array
    arr[0] = new Student(1701289270, "Satyabrata");

    // Initializing the second element
    // of the array
    arr[1] = new Student(1701289219, "Omm Prasad");

    // Displaying the student data
    System.out.println(
        "Student data in student arr 0: ");
    arr[0].display();

    System.out.println(
        "Student data in student arr 1: ");
    arr[1].display();
}
}

class Student {

public int id;
public String name;

// Student class constructor
Student(int id, String name)
{
    this.id = id;
    this.name = name;
}

// display() method to display
// the student data
public void display()
{
    System.out.println("Student id is: " + id + " "
                       + "and Student name is: "
                       + name);
    System.out.println();
}
}
</code>```

Body:
I've created a class that includes people data named "Datiutente" and an object based on that class named "du". Every person has a name and a surname (with the set/get methods).

I want to create a system that can provide the user information on a specific person based on the position which they are stored in the array.

I tried using a variable named vd to ask the user which person wanted to visualize based on the position that a person gained in the array (inserted in the for cycle), but when I try to print with vd it just prints "Name: null". Same if I change "vd" to "1". It always prints "Null".

(Yes, I tested this when I already inserted some data.)

Here's the full code:

package appartamento;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Appartamento {
    public static void main(String[] args) throws IOException {
        InputStreamReader input = new InputStreamReader(System.in);
        BufferedReader keyb = new BufferedReader(input);
        boolean attiva = true;

        do {
            System.out.println("what do you want to do?");
            System.out.println("1 - check for a person");
            System.out.println("2 - Add person");
            int choice = Integer.parseInt(keyb.readLine());
            Datiutente du[] = new Datiutente[10];

            if (choice == 2){
                System.out.println("How many people?");
                int hm = Integer.parseInt(keyb.readLine());

                for (int i=0;i<hm;i++){
                    du[i] = new Datiutente();
                    System.out.println("insert name:");
                    du[i].setName(keyb.readLine());
                    System.out.println("insert surname");
                    du[i].setSurname(keyb.readLine());
                }
            }

            if (choice == 1){
                System.out.println("which person are you searching?");
                int vd = Integer.parseInt(keyb.readLine());
                System.out.println("position: " + i);
                System.out.println("Name: "+  du[i]);
                System.out.println("Surname: " + du[i]);
            }
        } while (attiva = true);
    }
}

and the class "Datiutente":

package appartamento;

public class Datiutente {
    private String name;
    private String surname;
    private String codfis;

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public void setSurname(String surname){
        this.surname = surname;
    }

    public String getSurname(){
        return surname;
    }
}

Body:
I found a way here:

You need to insert values on object creation, you can also use hashmaps

hashmap will benefit you more I think.

Code sample to fix your stuff.

class GFG {
    public static void main(String args[]){

    // Declaring an array of student
    Student[] arr;

    // Allocating memory for 2 objects
    // of type student
    arr = new Student[2];

    // Initializing the first element
    // of the array
    arr[0] = new Student(1701289270, "Satyabrata");

    // Initializing the second element
    // of the array
    arr[1] = new Student(1701289219, "Omm Prasad");

    // Displaying the student data
    System.out.println(
        "Student data in student arr 0: ");
    arr[0].display();

    System.out.println(
        "Student data in student arr 1: ");
    arr[1].display();
}
}

class Student {

public int id;
public String name;

// Student class constructor
Student(int id, String name)
{
    this.id = id;
    this.name = name;
}

// display() method to display
// the student data
public void display()
{
    System.out.println("Student id is: " + id + " "
                       + "and Student name is: "
                       + name);
    System.out.println();
}
}


问:
how to Order the column values to make it more readable
this is example of my code. i need to reorder the values to be more readable.

```<code>data = {'code 1':[123, 422 , 123, 868, 422],
        'code 2':[53673, 3773, 387892, 17994, 2358]
         'Company':['GRM', 'SER', 'MEM','NOE', 'SEE']
          'Product_weight': [29,23,122,19,22]}
 df = pd.DataFrame(data)

</code>```

this is the actual table:

but i need it to be like this:

答:
Try using sort_values:

```<code>df = df.sort_values('code 1')
</code>```

Output:

```<code>>>> df
   code 1  code 2 Company  Product_weight
0     123   53673     GRM              29
2     123  387892     MEM             122
1     422    3773     SER              23
4     422    2358     SEE              22
3     868   17994     NOE              19
</code>```

Body:
this is example of my code. i need to reorder the values to be more readable.

data = {'code 1':[123, 422 , 123, 868, 422],
        'code 2':[53673, 3773, 387892, 17994, 2358]
         'Company':['GRM', 'SER', 'MEM','NOE', 'SEE']
          'Product_weight': [29,23,122,19,22]}
 df = pd.DataFrame(data)

this is the actual table:

but i need it to be like this:

Body:
Try using sort_values:

df = df.sort_values('code 1')

Output:

>>> df
   code 1  code 2 Company  Product_weight
0     123   53673     GRM              29
2     123  387892     MEM             122
1     422    3773     SER              23
4     422    2358     SEE              22
3     868   17994     NOE              19


问:
Property in Data is undefined inside methods() method
I'm brand new to Vue so trying to understand the basics so far. I'm using Vue 3.

My intention is to:

Create a select with the items in the array as options, this works.

Once the button is clicked, store the value of the select, this also works.

Push an object using the value of the select as an object's key's value

It's at this final stage that the error occurs, specifically the line getGeneMutationData: () => this.queryConstraints.push({

Error:

```<code>Uncaught TypeError: Cannot read properties of undefined (reading 'queryConstraints')
    at Proxy.getGeneMutationData (Query.vue?12c2:46:14)
    at eval (runtime-dom.esm-bundler.js?3191:380:1)
    at callWithErrorHandling (runtime-core.esm-bundler.js?a261:155:1)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?a261:164:1)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?a261:174:1)
    at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js?3191:366:39)
</code>```

I'm not sure why this isn't working, based on the documentation I'm not sure what's different in the approaches:

```<code>data() {
    return { count: 4 }
  },
  methods: {
    increment() {
      // `this` will refer to the component instance
      this.count++
    }
  }
</code>```

Here's a minimised of my code:

```<code><template>
  <select v-model="selectedGeneMutation">
    <option v-for="geneMutation in geneMutations" :key="geneMutation">{{geneMutation}}</option>
  </select>
  <input type="button" @click="getGeneMutationData">Get results</input>
</template>

<script>
  export default {
    name: 'Home',
    data: () => ({
      geneMutations: ['ACTC',
                      'MYBPC3'
      ],
      queryConstraints: [],
      selectedGeneMutation: ''
    }),
    setup() {},
    methods: {
      getGeneMutationData: () => this.queryConstraints.push({
        fieldPath: this.selectedGeneMutation,
        opStr: '==',
        value: true
      })
    }
  };
</script>
</code>```

Any help as to why I can't access the properties in 'data' would really be appreciated

答:
You should not mix composition and options API (this is not the same, also, there is no methods in composition API), try like following snippet (composition API) or you can move your methods to options API (remove setup function):

const { ref } = Vue
const App = {
  setup() {
    const geneMutations = ref(['ACTC', 'MYBPC3'])
    let queryConstraints = ref([])
    const selectedGeneMutation = ref('')
    const getGeneMutationData = () =>  {
      queryConstraints.value.push({
        fieldPath: selectedGeneMutation.value,
        opStr: '==',
        value: true
      })
    }
    return {
      geneMutations, queryConstraints, selectedGeneMutation, getGeneMutationData
    };
  }
}
Vue.createApp(App)
  .mount('#app')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@3.2.29/dist/vue.global.prod.js"></script>
<div id="app">
  <select v-model="selectedGeneMutation">
    <option v-for="geneMutation in geneMutations" :key="geneMutation">{{geneMutation}}</option>
  </select>
  <input type="button" @click="getGeneMutationData" value="Get results" />
  <h3>{{ queryConstraints }}</h3>
</div></code>```

Body:
I'm brand new to Vue so trying to understand the basics so far. I'm using Vue 3.

My intention is to:

Create a select with the items in the array as options, this works.

Once the button is clicked, store the value of the select, this also works.

Push an object using the value of the select as an object's key's value

It's at this final stage that the error occurs, specifically the line getGeneMutationData: () => this.queryConstraints.push({

Error:

Uncaught TypeError: Cannot read properties of undefined (reading 'queryConstraints')
    at Proxy.getGeneMutationData (Query.vue?12c2:46:14)
    at eval (runtime-dom.esm-bundler.js?3191:380:1)
    at callWithErrorHandling (runtime-core.esm-bundler.js?a261:155:1)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?a261:164:1)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?a261:174:1)
    at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js?3191:366:39)

I'm not sure why this isn't working, based on the documentation I'm not sure what's different in the approaches:

data() {
    return { count: 4 }
  },
  methods: {
    increment() {
      // `this` will refer to the component instance
      this.count++
    }
  }

Here's a minimised of my code:

<template>
  <select v-model="selectedGeneMutation">
    <option v-for="geneMutation in geneMutations" :key="geneMutation">{{geneMutation}}</option>
  </select>
  <input type="button" @click="getGeneMutationData">Get results</input>
</template>

Any help as to why I can't access the properties in 'data' would really be appreciated

Body:
You should not mix composition and options API (this is not the same, also, there is no methods in composition API), try like following snippet (composition API) or you can move your methods to options API (remove setup function):

const { ref } = Vue
const App = {
  setup() {
    const geneMutations = ref(['ACTC', 'MYBPC3'])
    let queryConstraints = ref([])
    const selectedGeneMutation = ref('')
    const getGeneMutationData = () =>  {
      queryConstraints.value.push({
        fieldPath: selectedGeneMutation.value,
        opStr: '==',
        value: true
      })
    }
    return {
      geneMutations, queryConstraints, selectedGeneMutation, getGeneMutationData
    };
  }
}
Vue.createApp(App)
  .mount('#app')

<script src="https://unpkg.com/vue@3.2.29/dist/vue.global.prod.js"></script>
<div id="app">
  <select v-model="selectedGeneMutation">
    <option v-for="geneMutation in geneMutations" :key="geneMutation">{{geneMutation}}</option>
  </select>
  <input type="button" @click="getGeneMutationData" value="Get results" />
  <h3>{{ queryConstraints }}</h3>
</div>


问:
Server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
I can push by clone project using ssh, but it doesn't work when I clone project with https.

The error message that it shows me is:

```<code>server certificate verification failed. CAfile: /etc/ssl/certs/cacertificates.crt CRLfile: none
</code>```

答:
I ran into this problem today with freedesktop.org, when using Git for Windows.  I updated my git version to 2.35 (from 2.28), and the problem was solved.  Probably the integrated shell environment in the windows version did not have updated certs.

Hopefully this helps someone who uses the Windows version.

Body:
I can push by clone project using ssh, but it doesn't work when I clone project with https.

The error message that it shows me is:

server certificate verification failed. CAfile: /etc/ssl/certs/cacertificates.crt CRLfile: none


问:
Problem with position:absolute on input
I have this code :

```<code><div class="areaButton">
    <input type="submit" value="Add">
</div>

.areaButton
{
    float:left;
    position:relative;
    width:200px;
    margin-left:18px;
    margin-right:18px;
    background-color:red;
}

.areaButton input
{
    position:absolute;
    right:0px;
    top:0px;
}
</code>```

but as you can see, the Input doesnt "feel" the container (where is the background-color:red;)?

答:
```<code><div class="areaButton">
    <div> THis is the are around the button</div>
    <input type="submit" value="Add">
</div>

.areaButton
{
    float:left;
    position:relative;
    width:200px;
    margin-left:18px;
    margin-right:18px;
    background-color:red;
}

.areaButton input
{
    position:absolute;
    right:0px;
    top:0px;
background-color:red;
border:5px solid yellow;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Problem with position:absolute on input

Body:
I have this code :

    <input type="submit" value="Add">

.areaButton
{
    float:left;
    position:relative;
    width:200px;
    margin-left:18px;
    margin-right:18px;
    background-color:red;
}

.areaButton input
{
    position:absolute;
    right:0px;
    top:0px;
}

but as you can see, the Input doesnt "feel" the container (where is the background-color:red;)?


问:
Python percentage function not working as intended
For a college project I need to output of the number of votes + the percentage of votes out of the total votes for each team that (input)(there are six in total).

I made the program using lists, and got to the part where i made a list with 7 elements: the total number of votes the program registered + the votes consecutively each team got.

I then use this list to run a function that changes the values of the indexes of the list to their percentage, with another function working as a percentage calculator. (Called 'porcentagem' that I tested out and works as intended.)

```<code>def porcentagem(p, w):
  pc = 100 * float(p)/float(w)
  return str(pc) + "%"
</code>```

```<code>def per(list):
    listF = [0,0,0,0,0,0,0]
    for x in list[1:7]:
        if x != 0:
            listF[x] = porcentagem(x, list[0])
        else:
            listF[x] = 0
    return listF
</code>```

For some reason when I input the votes, the results come all out of order. For example:
The list input is List = [6, 3, 2, 1, 0, 0, 0,] but the output is [0, '16.666666666666668%', '33.333333333333336%', '50.0%', 0, 0, 0] (Index 0 is the total if it wasn't clear, and

I have no idea what could be causing this, its changing the orders of the elements apparently (its supposed to come out as 50%, then 33,3...% etc..)

I'm 'new' at programming + spent two months not coding anything + english is not my first language and I'm learning python in portuguese, sorry if it looks obvious lol

答:
The x in for x in list[1:7]: returns the actual value, not the index. So x will be: 3, 2, 1, 0, 0, 0. That means the first listF[x] is listF[3] which is assigning to the 4th element.

A word of caution: list is a constructor for a built-in function, so if you use list as a variable, it might have unintended consequences. Change it to something like percentage_list.

Do something like the following:

```<code>def per(per_list):
    listF = [0,0,0,0,0,0,0]
    for i in range(1, len(per_list)):
        x = per_list[i]
        if x != 0:
            listF[i] = porcentagem(x, per_list[0])
        else:
            listF[i] = 0
    return listF
</code>```

Output: [0, '50.0%', '33.333333333333336%', '16.666666666666668%', 0, 0, 0]

Body:
For a college project I need to output of the number of votes + the percentage of votes out of the total votes for each team that (input)(there are six in total).

I made the program using lists, and got to the part where i made a list with 7 elements: the total number of votes the program registered + the votes consecutively each team got.

I then use this list to run a function that changes the values of the indexes of the list to their percentage, with another function working as a percentage calculator. (Called 'porcentagem' that I tested out and works as intended.)

def porcentagem(p, w):
  pc = 100 * float(p)/float(w)
  return str(pc) + "%"

def per(list):
    listF = [0,0,0,0,0,0,0]
    for x in list[1:7]:
        if x != 0:
            listF[x] = porcentagem(x, list[0])
        else:
            listF[x] = 0
    return listF

For some reason when I input the votes, the results come all out of order. For example:
The list input is List = [6, 3, 2, 1, 0, 0, 0,] but the output is [0, '16.666666666666668%', '33.333333333333336%', '50.0%', 0, 0, 0] (Index 0 is the total if it wasn't clear, and

I have no idea what could be causing this, its changing the orders of the elements apparently (its supposed to come out as 50%, then 33,3...% etc..)

I'm 'new' at programming + spent two months not coding anything + english is not my first language and I'm learning python in portuguese, sorry if it looks obvious lol

Body:
The x in for x in list[1:7]: returns the actual value, not the index. So x will be: 3, 2, 1, 0, 0, 0. That means the first listF[x] is listF[3] which is assigning to the 4th element.

A word of caution: list is a constructor for a built-in function, so if you use list as a variable, it might have unintended consequences. Change it to something like percentage_list.

Do something like the following:

def per(per_list):
    listF = [0,0,0,0,0,0,0]
    for i in range(1, len(per_list)):
        x = per_list[i]
        if x != 0:
            listF[i] = porcentagem(x, per_list[0])
        else:
            listF[i] = 0
    return listF

Output: [0, '50.0%', '33.333333333333336%', '16.666666666666668%', 0, 0, 0]


问:
imagePicker Flutter can't convert image to FIle
i wanna convert my photo from gallery to File i need that beacause i will take the image to firebase when i try convert to File, it will throw me error The argument type 'String' can't be assigned to the parameter type 'List'

My code:

```<code>File? _imageFile;
final picker = ImagePicker();

Future  getImage() async{
 final  photo = await _picker.pickImage(source: ImageSource.gallery);
_imageFile=File(photo!.path,""); #that line give error
 }
</code>```

EDIT: I DELETE "import 'dart:html';" and it work

答:
```<code>///I used this code for image picking and uploading the image to firebase
  File? _image;
            final picker = ImagePicker();
            ///pop-up to choose camera gallery while uploading image
              Future<void> _showChoiceDialog(BuildContext context) {
                return showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text(
                          "Choose option",
                          style: TextStyle(color: AppColors.hotelListDarkBlue),
                        ),
                        content: SingleChildScrollView(
                          child: ListBody(
                            children: [
                              Divider(
                                height: 1,
                                color: AppColors.baseLightBlueColor,
                              ),
                              ListTile(
                                onTap: () {
                                  Navigator.pop(context, _pickImage(ImageSource.gallery,context));
                                },
                                title: Text(
                                  "Gallery",
                                  style: TextStyle(color: AppColors.hotelListDarkBlue),
                                ),
                                leading: Icon(
                                  Icons.account_box,
                                  color: AppColors.baseLightBlueColor,
                                ),
                              ),
                              Divider(
                                height: 1,
                                color: AppColors.baseLightBlueColor,
                              ),
                              ListTile(
                                onTap: () {
                                  Navigator.pop(context, _pickImage(ImageSource.camera,context));
                                },
                                title: Text(
                                  "Camera",
                                  style: TextStyle(color: AppColors.hotelListDarkBlue,),
                                ),
                                leading: Icon(
                                  Icons.camera,
                                  color: AppColors.baseLightBlueColor,
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    });
              }

            ///ImageSource: Camera and Gallery.
              Future<Null> _pickImage(ImageSource source,context) async {
                final pickedImage =
                await ImagePicker().getImage(source: source);
                _image = pickedImage != null ? File(pickedImage.path) : null;
                if (_image != null) {
        //you can set your value
                  setState(() {
                    //state = AppState.picked;

                  });

                }
              }

    ///I use CachedNetworkImage o show image I used provider you can skip the step and set your image in imageUrl

            CachedNetworkImage(
                                              maxHeightDiskCache: 100,
                                              imageUrl: provider
                                                  .currentLoggedInUser!.profilePicture
                                                  .toString(),
                                              imageBuilder: (context, imageProvider) =>
                                                  Container(
                                                height: 120,
                                                width: 120,
                                                decoration: BoxDecoration(
                                                  shape: BoxShape.circle,
                                                  image: DecorationImage(
                                                      image: imageProvider,
                                                      fit: BoxFit.cover),
                                                  border: Border.all(
                                                      color: AppColors.white,
                                                      width: 2.0),
                                                ),
                                              ),
                                              placeholder: (context, url) =>
                                                  const CircularProgressIndicator(),
                                              errorWidget: (context, url, error) =>
                                                  Container(
                                                height: 120,
                                                width: 120,
                                                decoration: BoxDecoration(
                                                  color: Colors.white,
                                                  shape: BoxShape.circle,
                                                  image: DecorationImage(
                                                      fit: BoxFit.cover,
                                                      image: AssetImage(
                                                          'assets/managerPicture.jpeg')),
                                                  border: Border.all(
                                                      color: AppColors.white,
                                                      width: 2.0),
                                                ),
                                              ),
                                              fadeOutDuration:
                                                  const Duration(seconds: 1),
                                              fadeInDuration:
                                                  const Duration(seconds: 3),
                                            ),

    ///to upload image i used thise method
    String ?url;
      Future <String?>uploadImageToFirebase(File _image) async {
        User? currentUser = FirebaseAuth.instance.currentUser;
        String fileName = basename(_image.path);
        firebase_storage.Reference ref = firebase_storage.FirebaseStorage.instance
            .ref().child('uploads')
            .child('/$fileName');
        final metadata = firebase_storage.SettableMetadata(
            contentType: 'image/jpeg',
            customMetadata: {'picked-file-path': fileName});
        firebase_storage.UploadTask uploadTask;
        uploadTask = ref.putFile(io.File(_image.path), metadata);
        //String ?url;
        await uploadTask.whenComplete(() async {
          url = await uploadTask.snapshot.ref.getDownloadURL();
        });
        Future.value(uploadTask)
            .then((value) => {
          print("Upload file path ${value.ref.fullPath}"),
          FirebaseFirestore.instance.collection(FirestoreCollections.employees).doc(currentUser!.uid).update({'image': '$url'}),
        })
            .onError((error, stackTrace) =>
        {
          print("Upload file path error ${error.toString()} ")}
          );
        return url;
      }
</code>```

Body:
i wanna convert my photo from gallery to File i need that beacause i will take the image to firebase when i try convert to File, it will throw me error The argument type 'String' can't be assigned to the parameter type 'List'

My code:

File? _imageFile;
final picker = ImagePicker();

Future  getImage() async{
 final  photo = await _picker.pickImage(source: ImageSource.gallery);
_imageFile=File(photo!.path,""); #that line give error
 }

EDIT: I DELETE "import 'dart:html';" and it work


问:
what is the impact on Kafka topic partitions log when consumed using multiple Consumer groups?
My question is more related to performance rather than how they consume data in consumer groups.
We know that kafka create single PARTITION LOG on filesystem, which is accessed by all consumer group's consumer on that partition.

What will be the impact on accessing that PARTITION LOG file by multiple consumers from different consumer's group?

Increasing the consumer groups for a specific partition log will slow down accessing that partition or not?

How Kafka handles such concurrent file read I/Os on a single
partition log from multiple consumer groups to same parition?

答:
Kafka uses memory-mapped files so reads typically should be served from the memory rather than from the disk.

From Kafka 2.4, Kafka consumers can fetch data from closest follower replicas as well which means that if your partition is replicated across different brokers, then different consumers belonging to different consumer groups consuming the same partition can be served by different brokers thus reducing the load on your leader broker.

In previous versions of Kafka, if multiple consumer groups start consuming messages from the same partition and since that partition leader is responsible for serving those read requests, you can observe some slowness and this is due to several factors including your hardware, OS etc.

Also note that partitions are divided into segments in Kafka where each segment is a file on the disk in the partition directory. Different consumers may be consuming different segments of the same partition.


问:
difference between data mining and machine learning
I am new to this area.

In my image,

Data mining means to retrieve useful information from data with respect to a data model.
Machine learning seeks to identify behavior patterns in data, and them build various models based on observed patterns.

答:
The terms are not overly strict in defintion, but basically I think what you're saying is correct.
Machine learning involves algorithm identification and finessing, whereas data mining implies a more static algorithm that is applied to fixed data. The output of machine learning is information of course, but also new algorithms identified through the process. Data mining seeks to apply a pre-existing algorithm over data.</p>


问:
Count co-occurrences of two words but the order is not important in r
WHAT I WANT: I want to count co-occurrence of two words. But I don't care the order they appear in the string.

MY PROBLEM: I don't know how to deal When two given words appear in different order.

SO FAR: I use unnest_token function to split the string by words using the "skip_ngrams" option for the token argument. Then I filtered the combination of exactly two words. I use separate to create word1 and word2 columns. Finally, I count the occurrence.

The output that I get is like this:

```<code># A tibble: 3 × 3
  word1 word2      n
  <chr> <chr>  <dbl>
1 a     c          3
2 b     a          1
3 c     a          5
</code>```

But words "a" and "c" occur in a different order so they are counted as a different element. What I want is this:

```<code># A tibble: 2 × 3
  word1 word2      n
  <chr> <chr>  <dbl>
1 a     c          8
2 b     a          1
</code>```

MY DATA: My data looks like this and this is the whole process with different data but the same problem. In this case "a b" and "c a" should take a value of n = 2.

library(tidyverse)
library(tidytext)
enframe(c("a b c a d e")) %>%
  unnest_tokens(skipgram, value, token = "skip_ngrams", n = 5) %>%
  mutate(n_words = str_count(skipgram, pattern = "\\S+")) %>%
  filter(n_words == 2) %>%
  separate(col = skipgram, into = c("word1", "word2"), sep = "\\s+") %>%
  count(word1, word2)
#> # A tibble: 9 × 3
#>   word1 word2     n
#>   <chr> <chr> <int>
#> 1 a     b         1
#> 2 a     c         1
#> 3 a     d         1
#> 4 a     e         1
#> 5 b     a         1
#> 6 b     c         1
#> 7 c     a         1
#> 8 c     d         1
#> 9 d     e         1
```

Created on 2022-02-09 by the reprex package (v2.0.1)

答:
We may use pmin/pmax to sort the columns by row before applying the count

```<code>library(tidytext)
library(dplyr)
library(stringr)
library(tidyr)
enframe(c("a b c a d e")) %>%
  unnest_tokens(skipgram, value, token = "skip_ngrams", n = 5) %>%
  mutate(n_words = str_count(skipgram, pattern = "\\S+")) %>%
  filter(n_words == 2) %>%
  separate(col = skipgram, into = c("word1", "word2"),
      sep = "\\s+") %>%
  transmute(word11 = pmin(word1, word2), word22 = pmax(word1, word2)) %>%
  count(word11, word22)
</code>```

-output

```<code># A tibble: 7 × 3
  word11 word22     n
  <chr>  <chr>  <int>
1 a      b          2
2 a      c          2
3 a      d          1
4 a      e          1
5 b      c          1
6 c      d          1
7 d      e          1
</code>```

Body:
WHAT I WANT: I want to count co-occurrence of two words. But I don't care the order they appear in the string.

MY PROBLEM: I don't know how to deal When two given words appear in different order.

SO FAR: I use unnest_token function to split the string by words using the "skip_ngrams" option for the token argument. Then I filtered the combination of exactly two words. I use separate to create word1 and word2 columns. Finally, I count the occurrence.

The output that I get is like this:

# A tibble: 3 × 3
  word1 word2      n
  <chr> <chr>  <dbl>
1 a     c          3
2 b     a          1
3 c     a          5

But words "a" and "c" occur in a different order so they are counted as a different element. What I want is this:

# A tibble: 2 × 3
  word1 word2      n
  <chr> <chr>  <dbl>
1 a     c          8
2 b     a          1

MY DATA: My data looks like this and this is the whole process with different data but the same problem. In this case "a b" and "c a" should take a value of n = 2.

library(tidyverse)
library(tidytext)
enframe(c("a b c a d e")) %>%
  unnest_tokens(skipgram, value, token = "skip_ngrams", n = 5) %>%
  mutate(n_words = str_count(skipgram, pattern = "\\S+")) %>%
  filter(n_words == 2) %>%
  separate(col = skipgram, into = c("word1", "word2"), sep = "\\s+") %>%
  count(word1, word2)
#> # A tibble: 9 × 3
#>   word1 word2     n
#>   <chr> <chr> <int>
#> 1 a     b         1
#> 2 a     c         1
#> 3 a     d         1
#> 4 a     e         1
#> 5 b     a         1
#> 6 b     c         1
#> 7 c     a         1
#> 8 c     d         1
#> 9 d     e         1

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
We may use pmin/pmax to sort the columns by row before applying the count

library(tidytext)
library(dplyr)
library(stringr)
library(tidyr)
enframe(c("a b c a d e")) %>%
  unnest_tokens(skipgram, value, token = "skip_ngrams", n = 5) %>%
  mutate(n_words = str_count(skipgram, pattern = "\\S+")) %>%
  filter(n_words == 2) %>%
  separate(col = skipgram, into = c("word1", "word2"),
      sep = "\\s+") %>%
  transmute(word11 = pmin(word1, word2), word22 = pmax(word1, word2)) %>%
  count(word11, word22)

-output

# A tibble: 7 × 3
  word11 word22     n
  <chr>  <chr>  <int>
1 a      b          2
2 a      c          2
3 a      d          1
4 a      e          1
5 b      c          1
6 c      d          1
7 d      e          1


问:
Delegate mouse events to all children in a JavaFX StackPane
I'm trying to come up with a solution to allow multiple Pane nodes handle mouse events independently when assembled into a StackPane

```<code>StackPane
   Pane 1
   Pane 2
   Pane 3
</code>```

I'd like to be able to handle mouse events in each child, and the first child calling consume() stops the event going to the next child.

I'm also aware of setPickOnBounds(false), but this does not solve all cases as some of the overlays will be pixel based with Canvas, i.e. not involving the scene graph.

I've tried various experiments with Node.fireEvent(). However these always lead to recursion ending in stack overflow. This is because the event is propagated from the root scene and triggers the same handler again.

What I'm looking for is some method to trigger the event handlers on the child panes individually without the event travelling through its normal path.

My best workaround so far is to capture the event with a filter and manually invoke the handler. I'd need to repeat this for MouseMoved etc

```<code>parent.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
    for (Node each : parent.getChildren()) {
        if (!event.isConsumed()) {
            each.getOnMouseClicked().handle(event);
        }
    }
    event.consume();
});
</code>```

However this only triggers listeners added with setOnMouseClicked, not addEventHandler, and only on that node, not child nodes.

Another sort of solution is just to accept JavaFX doesn't work like this, and restructure the panes like this, this will allow normal event propagation to take place.

```<code>Pane 1
   Pane 2
      Pane 3
</code>```

Example

```<code>import javafx.application.Application;
import javafx.event.Event;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class EventsInStackPane extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    private static class DebugPane extends Pane {
        public DebugPane(Color color, String name) {
            setBackground(new Background(new BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY)));
            setOnMouseClicked(event -> {
                System.out.println("setOnMouseClicked " + name + " " + event);
            });
            addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
                System.out.println("addEventHandler " + name + " " + event);
            });
            addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
                System.out.println("addEventFilter " + name + " " + event);
            });
        }

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        DebugPane red = new DebugPane(Color.RED, "red");
        DebugPane green = new DebugPane(Color.GREEN, "green");
        DebugPane blue = new DebugPane(Color.BLUE, "blue");
        setBounds(red, 0, 0, 400, 400);
        setBounds(green, 25, 25, 350, 350);
        setBounds(blue, 50, 50, 300, 300);

        StackPane parent = new StackPane(red, green, blue);
        eventHandling(parent);

        primaryStage.setScene(new Scene(parent));
        primaryStage.show();
    }

    private void eventHandling(StackPane parent) {
        parent.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            if (!event.isConsumed()) {
                for (Node each : parent.getChildren()) {
                    Event copy = event.copyFor(event.getSource(), each);
                    parent.fireEvent(copy);
                    if (copy.isConsumed()) {
                        break;
                    }
                }
            }
            event.consume();
        });
    }
    private void setBounds(DebugPane panel, int x, int y, int width, int height) {
        panel.setLayoutX(x);
        panel.setLayoutY(y);
        panel.setPrefWidth(width);
        panel.setPrefHeight(height);
    }
}
</code>```

答:
Using the hint from @jewelsea I was able to use a custom chain. I've done this from a "catcher" Pane which is added to the front of the StackPane. This then builds a chain using all the children, in reverse order, excluding itself.</p>
```<code>private void eventHandling(StackPane parent) {
    Pane catcher = new Pane() {
        @Override
        public EventDispatchChain buildEventDispatchChain(EventDispatchChain tail) {
            EventDispatchChain chain = super.buildEventDispatchChain(tail);
            for (int i = parent.getChildren().size() - 1; i >= 0; i--) {
                Node child = parent.getChildren().get(i);
                if (child != this) {
                    chain = chain.prepend(child.getEventDispatcher());
                }
            }
            return chain;
        }
    };
    parent.getChildren().add(catcher);
}
</code>```

Body:
I'm trying to come up with a solution to allow multiple Pane nodes handle mouse events independently when assembled into a StackPane

StackPane
   Pane 1
   Pane 2
   Pane 3

I'd like to be able to handle mouse events in each child, and the first child calling consume() stops the event going to the next child.

I'm also aware of setPickOnBounds(false), but this does not solve all cases as some of the overlays will be pixel based with Canvas, i.e. not involving the scene graph.

I've tried various experiments with Node.fireEvent(). However these always lead to recursion ending in stack overflow. This is because the event is propagated from the root scene and triggers the same handler again.

What I'm looking for is some method to trigger the event handlers on the child panes individually without the event travelling through its normal path.

My best workaround so far is to capture the event with a filter and manually invoke the handler. I'd need to repeat this for MouseMoved etc

parent.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
    for (Node each : parent.getChildren()) {
        if (!event.isConsumed()) {
            each.getOnMouseClicked().handle(event);
        }
    }
    event.consume();
});

However this only triggers listeners added with setOnMouseClicked, not addEventHandler, and only on that node, not child nodes.

Another sort of solution is just to accept JavaFX doesn't work like this, and restructure the panes like this, this will allow normal event propagation to take place.

Pane 1
   Pane 2
      Pane 3

Example

import javafx.application.Application;
import javafx.event.Event;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class EventsInStackPane extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    private static class DebugPane extends Pane {
        public DebugPane(Color color, String name) {
            setBackground(new Background(new BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY)));
            setOnMouseClicked(event -> {
                System.out.println("setOnMouseClicked " + name + " " + event);
            });
            addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
                System.out.println("addEventHandler " + name + " " + event);
            });
            addEventFilter(MouseEvent.MOUSE_CLICKED, event -> {
                System.out.println("addEventFilter " + name + " " + event);
            });
        }

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        DebugPane red = new DebugPane(Color.RED, "red");
        DebugPane green = new DebugPane(Color.GREEN, "green");
        DebugPane blue = new DebugPane(Color.BLUE, "blue");
        setBounds(red, 0, 0, 400, 400);
        setBounds(green, 25, 25, 350, 350);
        setBounds(blue, 50, 50, 300, 300);

        StackPane parent = new StackPane(red, green, blue);
        eventHandling(parent);

        primaryStage.setScene(new Scene(parent));
        primaryStage.show();
    }

    private void eventHandling(StackPane parent) {
        parent.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            if (!event.isConsumed()) {
                for (Node each : parent.getChildren()) {
                    Event copy = event.copyFor(event.getSource(), each);
                    parent.fireEvent(copy);
                    if (copy.isConsumed()) {
                        break;
                    }
                }
            }
            event.consume();
        });
    }
    private void setBounds(DebugPane panel, int x, int y, int width, int height) {
        panel.setLayoutX(x);
        panel.setLayoutY(y);
        panel.setPrefWidth(width);
        panel.setPrefHeight(height);
    }
}

Body:
Using the hint from @jewelsea I was able to use a custom chain. I've done this from a "catcher" Pane which is added to the front of the StackPane. This then builds a chain using all the children, in reverse order, excluding itself.

private void eventHandling(StackPane parent) {
    Pane catcher = new Pane() {
        @Override
        public EventDispatchChain buildEventDispatchChain(EventDispatchChain tail) {
            EventDispatchChain chain = super.buildEventDispatchChain(tail);
            for (int i = parent.getChildren().size() - 1; i >= 0; i--) {
                Node child = parent.getChildren().get(i);
                if (child != this) {
                    chain = chain.prepend(child.getEventDispatcher());
                }
            }
            return chain;
        }
    };
    parent.getChildren().add(catcher);
}


问:
Presto: Difference in hours between two timestamps?
The below gives me results like 1 00:00:00.000 However, I'd like the number of hours elapsed as a float or double.

SELECT FROM_UNIXTIME(ds2) - FROM_UNIXTIME(ds1)
```
<p>Does something like the below exist?</p>
<pre class="lang-sql prettyprint-override"><code>SELECT HOURS(FROM_UNIXTIME(ds2) - FROM_UNIXTIME(ds1))
</code>```

答:
Yes. You are looking for date_diff:

select date_diff('hour', now(), now() + interval '1' hour)
```

Output:

_col0

1

Body:
The below gives me results like 1 00:00:00.000 However, I'd like the number of hours elapsed as a float or double.

SELECT FROM_UNIXTIME(ds2) - FROM_UNIXTIME(ds1)

Does something like the below exist?

SELECT HOURS(FROM_UNIXTIME(ds2) - FROM_UNIXTIME(ds1))

Body:
Yes. You are looking for date_diff:

select date_diff('hour', now(), now() + interval '1' hour)

Output:

_col0

1


问:
Merge array of dynamically generated objects into single object
I'm struggling to convert the below JSON into expected JSON format using JavaScript.

Current JSON :

```<code>    {
  "furniture": {
    "matter": [
      {
        "matter1": "Matter 1 value"
      },
      {
        "matter2": "Matter 2 value"
      },
      {
        "matter3": "Matter 3 value"
      }
    ],
    "suspense": [
      {
        "suspense1": "suspense 1 value"
      },
      {
        "suspense2": "suspense 2 value"
      }
    ],
    "Direct": [
      {
        "System": "System value"
      }
    ],
    "Road": [
      {
        "Road key 1 ": "Road value "
      }
    ]
  }
}
</code>```

expected JSON:

```<code>{
  "furniture": {
    "matter": {
      "matter1": "Matter 1 value",
      "matter2": "Matter 2 value",
      "matter3": "Matter 3 value"
    },
    "suspense": {
      "suspense1": "suspense 1 value",
      "suspense2": "suspense 2 value"
    },
    "Direct": {
      "System": "System value"
    },
    "Road": {
      "Road key 1 ": "Road value "
    }
  }
}
</code>```

Note: furniture in above code is only static. Apart from that all keys and values are dynamically generated.

答:
You could look for arrays and create a joined object, otherwise flat the deeper level.

const
    flat = object => Object.fromEntries(Object
        .entries(object)
        .map(([k, v]) => [k, Array.isArray(v)
            ? Object.assign({}, ...v)
            : v && typeof v === 'object' ? flat(v) : v
        ])),
    data = { furniture: { matter: [{ matter1: "Matter 1 value" }, { matter2: "Matter 2 value" }, { matter3: "Matter 3 value" }], suspense: [{ suspense1: "suspense 1 value" }, { suspense2: "suspense 2 value" }], Direct: [{ System: "System value" }], Road: [{ "Road key 1 ": "Road value " }] }, Diversity: { "Sistema de direção": "Hidráulica" } },
    result = flat(data);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm struggling to convert the below JSON into expected JSON format using JavaScript.

Current JSON :

    {
  "furniture": {
    "matter": [
      {
        "matter1": "Matter 1 value"
      },
      {
        "matter2": "Matter 2 value"
      },
      {
        "matter3": "Matter 3 value"
      }
    ],
    "suspense": [
      {
        "suspense1": "suspense 1 value"
      },
      {
        "suspense2": "suspense 2 value"
      }
    ],
    "Direct": [
      {
        "System": "System value"
      }
    ],
    "Road": [
      {
        "Road key 1 ": "Road value "
      }
    ]
  }
}

expected JSON:

{
  "furniture": {
    "matter": {
      "matter1": "Matter 1 value",
      "matter2": "Matter 2 value",
      "matter3": "Matter 3 value"
    },
    "suspense": {
      "suspense1": "suspense 1 value",
      "suspense2": "suspense 2 value"
    },
    "Direct": {
      "System": "System value"
    },
    "Road": {
      "Road key 1 ": "Road value "
    }
  }
}

Note: furniture in above code is only static. Apart from that all keys and values are dynamically generated.

Body:
You could look for arrays and create a joined object, otherwise flat the deeper level.

const
    flat = object => Object.fromEntries(Object
        .entries(object)
        .map(([k, v]) => [k, Array.isArray(v)
            ? Object.assign({}, ...v)
            : v && typeof v === 'object' ? flat(v) : v
        ])),
    data = { furniture: { matter: [{ matter1: "Matter 1 value" }, { matter2: "Matter 2 value" }, { matter3: "Matter 3 value" }], suspense: [{ suspense1: "suspense 1 value" }, { suspense2: "suspense 2 value" }], Direct: [{ System: "System value" }], Road: [{ "Road key 1 ": "Road value " }] }, Diversity: { "Sistema de direção": "Hidráulica" } },
    result = flat(data);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Getting first day of every week in 6 months
I'm trying to figure out how can I get the the first day of week for the last 6 months and can't get to a working solution.

If I write date("Y-m-d 00:00:00", strtotime("-1 week", date("Y-m-d")); It just subtracts 7 days from the current date; what I want to do is to always return the date of Monday from that week.

Expected result:

```<code>2011-8-8 00:00:00
2011-8-1 00:00:00
2011-7-25 00:00:00
2011-7-18 00:00:00
etc
</code>```

答:
I'd recommend DateTime::createFromFormat.

Pre-PHP 5.3, you can use strtotime instead:

```<code><?php
define('NUM_WEEKS', 10);

$dates = Array();
$dates[] = strtotime('Monday');

for ($i = 0; $i < NUM_WEEKS-1; $i++)
    $dates[] = strtotime('-1 week', $dates[$i]);

foreach ($dates as $date)
    echo strftime('%c', $date) . "\n";
?>
</code>```

Output:

```<code>Mon Aug 22 00:00:00 2011
Mon Aug 15 00:00:00 2011
Mon Aug  8 00:00:00 2011
Mon Aug  1 00:00:00 2011
Mon Jul 25 00:00:00 2011
Mon Jul 18 00:00:00 2011
Mon Jul 11 00:00:00 2011
Mon Jul  4 00:00:00 2011
Mon Jun 27 00:00:00 2011
Mon Jun 20 00:00:00 2011
</code>```

Live demo.

Body:
I'm trying to figure out how can I get the the first day of week for the last 6 months and can't get to a working solution.

If I write date("Y-m-d 00:00:00", strtotime("-1 week", date("Y-m-d")); It just subtracts 7 days from the current date; what I want to do is to always return the date of Monday from that week.

Expected result:

2011-8-8 00:00:00
2011-8-1 00:00:00
2011-7-25 00:00:00
2011-7-18 00:00:00
etc

Body:
I'd recommend DateTime::createFromFormat.

Pre-PHP 5.3, you can use strtotime instead:

<?php
define('NUM_WEEKS', 10);

$dates = Array();
$dates[] = strtotime('Monday');

for ($i = 0; $i < NUM_WEEKS-1; $i++)
    $dates[] = strtotime('-1 week', $dates[$i]);

foreach ($dates as $date)
    echo strftime('%c', $date) . "\n";
?>

Output:

Mon Aug 22 00:00:00 2011
Mon Aug 15 00:00:00 2011
Mon Aug  8 00:00:00 2011
Mon Aug  1 00:00:00 2011
Mon Jul 25 00:00:00 2011
Mon Jul 18 00:00:00 2011
Mon Jul 11 00:00:00 2011
Mon Jul  4 00:00:00 2011
Mon Jun 27 00:00:00 2011
Mon Jun 20 00:00:00 2011

Live demo.


问:
Rmarkdown in loop, "knit html" button different output than rmarkdown::render
edit

This issue is not (necessarily) only related to {htmlTable}. The same happens when rendering a html table which has been styled with the {kableExtra} package (see also this thread).

original question

I'm working in RMarkdown, trying to render a document with htmltables from the htmlTable package in a loop. When I push the "Knit" button in RStudio, everything works great. But when I use the render() function, the htmltables in the loop don't get printed, but the table just before the loop does.
I read that "knit" button and the render function does the same, so I don't understand whats wrong?

This is a working example of a .Rmd file with a hmtlTables:

```<code>---
output: html_document
---

## htmlTables

```{r, results='asis'}
library(data.table)
library(htmlTable)
library(ggplot2)
a <- data.table(matrix(seq(1, 100, 5), ncol = 2))
htmlTable(a)
for (i in 10:11) {
    cat( paste('## title no.', i, '\n' ) )
    print(ggplot(a*i, aes(x = V1, y = V2)) + geom_point())
    print(htmlTable(a*i))
    cat('\n')
}
```
</code>```

I need to generate many reports automatically with different parameters, so I need to get this working with render().

答:
This depends on how the viewer is detected.

To check this :

```<code>---
title: "Check viewer"
output: html_document
---

```{r viewer, echo=FALSE}
getOption("viewer")
```
</code>```

With knit button:

```<code>Check viewer
## NULL
</code>```

With rmarkdown::render:

```<code>
Check viewer

## function (url, height = NULL)
## {
##     if (!is.character(url) || (length(url) != 1))
##         stop("url must be a single element character vector.",
##             call. = FALSE)
##     if (identical(height, "maximize"))
##         height <- -1
##     if (!is.null(height) && (!is.numeric(height) || (length(height) !=
##         1)))
##         stop("height must be a single element numeric vector or 'maximize'.",
##             call. = FALSE)
##     invisible(.Call("rs_viewer", url, height, PACKAGE = "(embedding)"))
## }
## <environment: 0x0000020ccb7f26d8>
</code>```

knit button executes rendering in an environment without defined viewer, whereas rmardown::render in RStudio console uses interactive viewer.

htmlTable allows to set options(htmlTable.cat = TRUE), so that print works, ie doesn't use interactive viewer, see ?htmlTable::htmlTable.

The print-function relies on the [base::interactive()] function
for determining if the output should be sent to a browser or to the terminal.
In vignettes and other directly knitted documents you may need to either set
useViewer = FALSE alternatively set options(htmlTable.cat = TRUE).

```<code>---
output: html_document
---

## htmlTables

```{r, results='asis'}
options(htmlTable.cat = TRUE)
library(data.table)
library(htmlTable)
library(ggplot2)
a <- data.table(matrix(seq(1, 100, 5), ncol = 2))
htmlTable(a)
for (i in 10:11) {
    cat( paste('## title no.', i, '\n' ) )
    print(ggplot(a*i, aes(x = V1, y = V2)) + geom_point())
    print(htmlTable(a*i))
    cat('\n')
}
```
</code>```

Body:
edit

This issue is not (necessarily) only related to {htmlTable}. The same happens when rendering a html table which has been styled with the {kableExtra} package (see also this thread).

original question

I'm working in RMarkdown, trying to render a document with htmltables from the htmlTable package in a loop. When I push the "Knit" button in RStudio, everything works great. But when I use the render() function, the htmltables in the loop don't get printed, but the table just before the loop does.
I read that "knit" button and the render function does the same, so I don't understand whats wrong?

This is a working example of a .Rmd file with a hmtlTables:

---
output: html_document
---

## htmlTables

```{r, results='asis'}
library(data.table)
library(htmlTable)
library(ggplot2)
a <- data.table(matrix(seq(1, 100, 5), ncol = 2))
htmlTable(a)
for (i in 10:11) {
    cat( paste('## title no.', i, '\n' ) )
    print(ggplot(a*i, aes(x = V1, y = V2)) + geom_point())
    print(htmlTable(a*i))
    cat('\n')
}
```

I need to generate many reports automatically with different parameters, so I need to get this working with render().

Body:
This depends on how the viewer is detected.

To check this :

---
title: "Check viewer"
output: html_document
---

```{r viewer, echo=FALSE}
getOption("viewer")
```

With knit button:

Check viewer
## NULL

With rmarkdown::render:

Check viewer

## function (url, height = NULL)
## {
##     if (!is.character(url) || (length(url) != 1))
##         stop("url must be a single element character vector.",
##             call. = FALSE)
##     if (identical(height, "maximize"))
##         height <- -1
##     if (!is.null(height) && (!is.numeric(height) || (length(height) !=
##         1)))
##         stop("height must be a single element numeric vector or 'maximize'.",
##             call. = FALSE)
##     invisible(.Call("rs_viewer", url, height, PACKAGE = "(embedding)"))
## }
## <environment: 0x0000020ccb7f26d8>

knit button executes rendering in an environment without defined viewer, whereas rmardown::render in RStudio console uses interactive viewer.

htmlTable allows to set options(htmlTable.cat = TRUE), so that print works, ie doesn't use interactive viewer, see ?htmlTable::htmlTable.

The print-function relies on the [base::interactive()] function
for determining if the output should be sent to a browser or to the terminal.
In vignettes and other directly knitted documents you may need to either set
useViewer = FALSE alternatively set options(htmlTable.cat = TRUE).

---
output: html_document
---

## htmlTables

```{r, results='asis'}
options(htmlTable.cat = TRUE)
library(data.table)
library(htmlTable)
library(ggplot2)
a <- data.table(matrix(seq(1, 100, 5), ncol = 2))
htmlTable(a)
for (i in 10:11) {
    cat( paste('## title no.', i, '\n' ) )
    print(ggplot(a*i, aes(x = V1, y = V2)) + geom_point())
    print(htmlTable(a*i))
    cat('\n')
}
```


Title: How to get row number according to row partitioning in r

Body:
I am trying to give ranknumber according to qtr wise here is the inpt and output

INPUT:-

year   qtr  month   day          salry
2001    q1  jan     1           1000.00
2001    q1  jan     2           1500.00
2001    q1  feb     1           3000.00
2001    q1  feb     2           2100.00
2001    q1  march   1          1000.00
2001    q1  march   2          1200.00
2001    q2  april   1          1300.00
2001    q2  april   2          1900.00
2001    q2  may     1          1000.00
2001    q2  may     2          1800.00
2001    q2  june    1          1600.00
2001    q2  june    2          1900.00
2001    q3  july    1          2000.00
2001    q3  july    2          1800.00
2001    q3  august  1          2100.00
2001    q3  august  2          1500.00
2001    q3  sept    1          1700.00
2001    q3  sept    2          1400.00
2001    q4  oct     1          1300.00
2001    q4  oct     2          1200.00
2001    q4  nov     1          1100.00
2001    q4  nov     2          1700.00
2001    q4  dec     1          1000.00
2001    q4  dec     2          1700.00

OUTPUT:-

year    qtr     month  day  salry      rank
2001    q1      feb     1   3000.00     1
2001    q1      feb     2   2100.00     2
2001    q1      jan     2   1500.00     3
2001    q1      march   2   1200.00     4
2001    q1      jan     1   1000.00     5
2001    q1      march   1   1000.00     6
2001    q2      april   2   1900.00     1
2001    q2      june    2   1900.00     2
2001    q2      may     2   1800.00     3
2001    q2      june    1   1600.00     4
2001    q2      april   1   1300.00     5
2001    q2      may     1   1000.00     6
2001    q3      august  1   2100.00     1
2001    q3      july    1   2000.00     2
2001    q3      july    2   1800.00     3
2001    q3      sept    1   1700.00     4
2001    q3      august  2   1500.00     5
2001    q3      sept    2   1400.00     6
2001    q4      nov     2   1700.00     1
2001    q4      dec     2   1700.00     2
2001    q4      oct     1   1300.00     3
2001    q4      oct     2   1200.00     4
2001    q4      nov     1   1100.00     5
2001    q4      dec     1   1000.00     6

Body:
dplyr

library(dplyr)
dat %>%
  group_by(year, qtr) %>%
  mutate(rank2 = row_number()) %>%
  ungroup()
# # A tibble: 24 x 7
#     year qtr   month   day salry  rank rank2
#    <int> <chr> <chr> <int> <dbl> <int> <int>
#  1  2001 q1    feb       1  3000     1     1
#  2  2001 q1    feb       2  2100     2     2
#  3  2001 q1    jan       2  1500     3     3
#  4  2001 q1    march     2  1200     4     4
#  5  2001 q1    jan       1  1000     5     5
#  6  2001 q1    march     1  1000     6     6
#  7  2001 q2    april     2  1900     1     1
#  8  2001 q2    june      2  1900     2     2
#  9  2001 q2    may       2  1800     3     3
# 10  2001 q2    june      1  1600     4     4
# # ... with 14 more rows

base R

dat$rank3 <- ave(seq_len(nrow(dat)), dat[c("year","qtr")], FUN = seq_along)
head(dat, 10)
#    year qtr month day salry rank rank3
# 1  2001  q1   feb   1  3000    1     1
# 2  2001  q1   feb   2  2100    2     2
# 3  2001  q1   jan   2  1500    3     3
# 4  2001  q1 march   2  1200    4     4
# 5  2001  q1   jan   1  1000    5     5
# 6  2001  q1 march   1  1000    6     6
# 7  2001  q2 april   2  1900    1     1
# 8  2001  q2  june   2  1900    2     2
# 9  2001  q2   may   2  1800    3     3
# 10 2001  q2  june   1  1600    4     4


问:
Python - How can I line up the equals sign of all my equations?
Currently in maths class we are working on gcd and I have written a Python script on my NumWorks calculator.

Here is the code I already wrote :

```<code>def div(n):
  return [x for x in range(1,n+1) if n%x==0]

def pgcd(x,y):
  a = x
  b = y

  while b > 0:
    reste = a % b
    print(a, "=", a//b, "*", b, "+", a%b)
    a,b = b,reste

  return "PGCD("+str(x)+";"+str(y)+") = " + str(a)
</code>```

And it ouputs this :

```<code>pgcd(178,52)
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0
</code>```

I want it to output that :

```<code>178 = 3 * 52 + 22
 52 = 2 * 22 + 8
 22 = 2 * 8 + 6
  8 = 1 * 6 + 2
  6 = 3 * 2 + 0
</code>```

I've read many articles online but I have no idea how to put that into my code.

Thanks in advance.

答:
Use str.format() to achieve this:

'{0: >{width}}'.format(178, 3)
'{0: >{width}}'.format(52, 3)
```
<p>Will output</p>
```178
 52
```

Body:
Currently in maths class we are working on gcd and I have written a Python script on my NumWorks calculator.

Here is the code I already wrote :

def div(n):
  return [x for x in range(1,n+1) if n%x==0]

def pgcd(x,y):
  a = x
  b = y

  while b > 0:
    reste = a % b
    print(a, "=", a//b, "*", b, "+", a%b)
    a,b = b,reste

  return "PGCD("+str(x)+";"+str(y)+") = " + str(a)

And it ouputs this :

pgcd(178,52)
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0

I want it to output that :

178 = 3 * 52 + 22
 52 = 2 * 22 + 8
 22 = 2 * 8 + 6
  8 = 1 * 6 + 2
  6 = 3 * 2 + 0

I've read many articles online but I have no idea how to put that into my code.

Thanks in advance.

Body:
Use str.format() to achieve this:

'{0: >{width}}'.format(178, 3)
'{0: >{width}}'.format(52, 3)

Will output

178
 52


问:
jQuery - Change text in an input field after it's created
How can I write a script that will change an input field's text value, but the field is not yet created?

The script is loaded before the input field is created.  It needs to know that when any input with a certain class is created, it will then have some text put in to its value.  Can this be done with live()?

To clarify, the order of events are:

1 - Application-wide JavaScript for the page is loaded.  This contains script something along the lines of:

```<code>$('.myDiv input').each(function() {
    $(this).val('some text');
});
</code>```

2 - A second page-specific script is now loaded, which dynamically creates an input on the page, with no value.  I CANNOT MODIFY THIS SCRIPT. This is important, I need a solution that does not modify this script (otherwise I wouldn't be posting here).

```<code>$('.myDiv').html('<input type="text" />');
</code>```

答:
Yes, live() will do what you want. It will work as long as you use jQuery to add the elements dynamically.

The jQuery.live() api is clear on this

Use live() to bind on focus or blur or keyup whenever you want to change the value of the input field.

```<code>$('.clickme').live('click', function() {
  // Live handler called.
});
</code>```

UPDATE: assuming you cant change the input elements in any way before the are added.

```<code>$('#container').bind("DOMSubtreeModified",function() {
   $('input.myClass:not(.alreadyChanged)').val("whatever you want to change it to");
   $('input.myClass:not(.alreadyChanged)').addClass('.alreadyChanged');
}
</code>```

This way you don't need to use live() when a new element is added to the DOM, the function is automatically triggered.

Body:
How can I write a script that will change an input field's text value, but the field is not yet created?

The script is loaded before the input field is created.  It needs to know that when any input with a certain class is created, it will then have some text put in to its value.  Can this be done with live()?

To clarify, the order of events are:

1 - Application-wide JavaScript for the page is loaded.  This contains script something along the lines of:

$('.myDiv input').each(function() {
    $(this).val('some text');
});

2 - A second page-specific script is now loaded, which dynamically creates an input on the page, with no value.  I CANNOT MODIFY THIS SCRIPT. This is important, I need a solution that does not modify this script (otherwise I wouldn't be posting here).

$('.myDiv').html('<input type="text" />');

Body:
Yes, live() will do what you want. It will work as long as you use jQuery to add the elements dynamically.

The jQuery.live() api is clear on this

Use live() to bind on focus or blur or keyup whenever you want to change the value of the input field.

$('.clickme').live('click', function() {
  // Live handler called.
});

UPDATE: assuming you cant change the input elements in any way before the are added.

$('#container').bind("DOMSubtreeModified",function() {
   $('input.myClass:not(.alreadyChanged)').val("whatever you want to change it to");
   $('input.myClass:not(.alreadyChanged)').addClass('.alreadyChanged');
}

This way you don't need to use live() when a new element is added to the DOM, the function is automatically triggered.


问:
App with Docker Image and Memory allocation
I came across a questionnaire on Containers and Buildpacks. I could not find the answer to the following questions :

What buildpack is used to stage docker apps?

I would assume a non-docker app would require a buildpack which would produce the container image during the staging process. For a docker based application a buildpack is not relevant since it is already a container image . Is this correct understanding ?

When you allocate 1G to an app, how much memory does the application receive? What
component determines this?

I would assume, the actual application (For example: my_sample_spring_boot_app)would receive less memory than 1G , since some part of teh memory would be utilised for Infra + Stack + runtime etc.  Is this correct understanding ?

Could you please help me with some guidance

答:
What buildpack is used to stage docker apps?
I would assume a non-docker app would require a buildpack which would produce the container image during the staging process. For a docker based application a buildpack is not relevant since it is already a container image . Is this correct understanding ?

That sounds like a trick question. When you run Docker images on Cloud Foundry, no buildpacks run.

There are different app lifecycles to run each type of app. So when you have source code to build and run, the buildpacks app lifecycle takes that, runs the buildpacks, and generates a droplet from them. The droplet is then run.

With a Docker image, the docker app lifecycle is used. No build/stage happens since that's assumed to happen externally, and the image is just ready to be run.

When you allocate 1G to an app, how much memory does the application receive? What component determines this?
I would assume, the actual application (For example: my_sample_spring_boot_app)would receive less memory than 1G , since some part of teh memory would be utilised for Infra + Stack + runtime etc. Is this correct understanding ?

Correct. If you allocate a 1G memory limit then everything running in the container must all fit within that 1G limit.

Your application will get most of that memory, but there are a couple of small processes that run in every container: an init process (i.e. PID1), an SSHD (for cf ssh) and in most CF versions there's also an envoy proxy (for TLS termination in the container). I haven't looked recently, but a while back this took up around 24M. If anyone has measured recently, please comment.

Everything has to fit under the memory limit. If your application forks, perhaps because it forks worker processes or if you fork and run sub-processes as part of the application. Everything you run has to all stay under the 1G limit.

Last note. For Java apps, 1G is the total memory size of the container. NOT your JVM heap. That's a common misconception. The entire JVM process and all its different memory regions (heap, metaspace, threads, direct memory, code cache, etc...) have to fit within the 1G limit.


问:
Use of CDK in Codepipeline
xI have a requirement wherein I need to execute certain CDK command inside the stage. I am not sure on how to use it within a stage

Tried certain things all I can understand is that you can run certain Shell command inside a stage.

```<code> with open('<some-config.json>') as f:
            lines = f.readlines()
        print(lines)
        string_param = aws_ssm.StringParameter(
            self, "StringParameterWithoutSlash",
            parameter_name="<some-config>",
            string_value="{}".format(lines)
        )
</code>```

I have the below CDK pipeline.

```<code>       pipeline.add_stage(
            stage_name="Source",
            actions=[
                codepipeline_actions.CodeCommitSourceAction(
                    action_name="CodeCommit-Source",
                    repository=code_repo,
                    branch="master",
                    output=source_output,
                )
            ],
        )

        pipeline.add_stage(
            stage_name="Build-Test",
            actions=[
                codepipeline_actions.CodeBuildAction(
                    action_name="Build-Test",
                    project=build_project,
                    input=source_output,
                    outputs=[build_output],
                )
            ],
        )

</code>```

I want to execute certain cdk commands inside the CDK pipeline so that when the pipeline is executed the cdk commands run.

Tried certain things but couldn't find any method that I can use.

答:
You can't deploy CDK constructs directly from codepipeline.Pipeline.  That's the specialty of the pipelines.CodePipeline Construct.  Swapping pipelines isn't necessary, though.

Here's a solution that keeps the OP's codepipeline.Pipeline.  It avoids deploying new resources in the pipeline.

Add the ssm.Parameter Constructs to the CDK Stack. At synth-time the names are known, the values dummy placeholders. The actual parameter values will be set later by a Lambda invoked during the pipeline executions.

Add a Function Construct to the CDK Stack. The lambda will be called as a pipeline action. The lambda should have an environment variable PARAMS_JSON, through which it will receive the params values when invoked. The Lambda's job is to call the boto3 put_parameter() API to overwrite the parameter values with the values in the env var.

Set the value of PARAMS_JSON using shell commands in a pipeline action. <some-config.json> will be available at this time from the input artifacts.

Add a LambdaInvokeAction that refers to the Function you added above.  Where exactly in the pipeline you place steps 3 and 4 will depend on the details of your use case.

An advantage of this approach the Parameters and Lambda are tied to the Stack lifecycle.  The parameters will be created, updated and destroyed together with the Stack, even though the Stack does not know the parameter values.

Title: Use of CDK in Codepipeline

Body:
xI have a requirement wherein I need to execute certain CDK command inside the stage. I am not sure on how to use it within a stage

Tried certain things all I can understand is that you can run certain Shell command inside a stage.

 with open('<some-config.json>') as f:
            lines = f.readlines()
        print(lines)
        string_param = aws_ssm.StringParameter(
            self, "StringParameterWithoutSlash",
            parameter_name="<some-config>",
            string_value="{}".format(lines)
        )

I have the below CDK pipeline.

       pipeline.add_stage(
            stage_name="Source",
            actions=[
                codepipeline_actions.CodeCommitSourceAction(
                    action_name="CodeCommit-Source",
                    repository=code_repo,
                    branch="master",
                    output=source_output,
                )
            ],
        )

        pipeline.add_stage(
            stage_name="Build-Test",
            actions=[
                codepipeline_actions.CodeBuildAction(
                    action_name="Build-Test",
                    project=build_project,
                    input=source_output,
                    outputs=[build_output],
                )
            ],
        )

I want to execute certain cdk commands inside the CDK pipeline so that when the pipeline is executed the cdk commands run.

Tried certain things but couldn't find any method that I can use.


问:
Wordpress on Azure, 504, media not uploading, can't remove a plugin
I'm at the end of the line,

I get inconsistant 504 Gateway Time-out, plugins disable or not.

I try and upload media and see the progress bar go up but when it reached the 100% I get that the image is to big (which it's not). Sometimes I will get 504's here with an eventual 502 and then the  web app seems to restart

I'm trying to clear some plugins since that might be the issue but when I try and delete a couple
of plugins, it doesn't. The text says deleting but it never goes.

I checked the permissions and they seem fine (drwxr-xr-x 1 Unknown+User Unknown+Group).
I've tried all 7 steps from WPBeginngers.  https://www.wpbeginner.com/wp-tutorials/how-to-fix-the-504-gateway-timeout-error-in-wordpress/  [clear cache and reload, VPN, Firewall, Proxy, DNS, Database, plugins-n-theme]
Plenty of ram, space, memory alocation (to my best ability and other staff here).
I've disabled all of the plugins and theme with no differences.
The debug.log file has nothing.
No cache plugins on.

Why can I find the issue?! What else can I try?

PS, I AM THE HOST, so please no 'contact your host'

答:
After multiple days working with Microsoft Support, we tested theories flip on and off almost every switch possible.
We went back and started a process of elemination.
After reviewing the Application Gateway settings we moved to the App Service. We tried simple readme.html files with success in KUDU. We tried a 'hello world' php file and we got the gateway error or The page cannot be displayed because an internal server error has occurred.
Typical steps for WordPress reestablishment didn't prove fruitful either. Plugins, memeory allocation in .user.ini and such.
We then looked at changing the PHP version to see if we would get different errors.
PS, log files were not working.
At this time, Azure only offered PHP 7.4 so we couldn't switch it back and forth for trials. It's at this point we descided to rebuild the App Service and see if we can get a simple site up. This was a succeess.

Our final assessment was that the PHP engine had failed or had issues. The site was eventually copied over and as the files came up the sites started to show life.

If you run in this issue, you may have the option to lower or increase the PHP version. We could have tried to rebuild the PHP on the server but creating the new App Service was a better choice. It allowed us to also eleminate that the grouping of the App Service was faulty.

It has been days now and the sites are stable, there are no reports of gateways or down pages.


问:
CameraStream Trait webrtc
I see on the google home document that google CameraStream webrtc currently supports 1-way (half duplex) communication. When will it support two-way intercom?</p>

答:
Duplex webrtc is not yet supported by CameraStream trait, but Google is constantly monitoring feature requests on its public tracker.

You can file a request on the public tracker(here), and check for more information in regards to this feature development.

Title: CameraStream Trait webrtc


问:
How can I test LDAP connection using JNDI
I get an exception javax.naming.NameNotFountException: [LDAP: error code 32 - No Such Object]; remaining name = 'DC=my-company, DC=group'

The cause of it could be, that the DN 'DC=my-company, DC=group' is invalid. But such exception occurs also then if I set ldapAdServer, ldapUsername, ldapPassword to unvalid values. So, I suppose my LDAP connection was not properly set.

How can I test LDAP connection whether it was created successfully?

答:
No Such Object is an error returned by a directory server when the object of the request does not exist. Use the correct base object instead of dc=my-company,dc=com.

If you do not know the base object, you may be able to discover the directory prefix (or naming context) by querying the root DSE. If you do not know the correct base object, you can use the prefix or naming context as the base object until you discover the base object (which should be closer to your data than the prefix or naming context).

More generally speaking, JNDI should not be used if you know for certain that your directory server will be accessed via LDAP. You will be able to quickly develop working, practical code that is more easily understood by others and more efficient if you use a professional quality LDAP SDK such as the one from UnboundID. The standard edition is free of cost and comes with the source code.