问:
What is the difference between MOV and LEA?
I would like to know what the difference between these instructions is:

```<code>MOV AX, [TABLE-ADDR]
</code>```

and

```<code>LEA AX, [TABLE-ADDR]
</code>```

答:
None of the previous answers quite got to the bottom of my own confusion, so I'd like to add my own.

What I was missing is that lea operations treat the use of parentheses different than how mov does.

Think of C. Let's say I have an array of long that I call array. Now the expression array[i] performs a dereference, loading the value from memory at the address array + i * sizeof(long) [1].

On the other hand, consider the expression &array[i]. This still contains the sub-expression array[i], but no dereferencing is performed! The meaning of array[i] has changed. It no longer means to perform a deference but instead acts as a kind of a specification, telling & what memory address we're looking for.  If you like, you could alternatively think of the & as "cancelling out" the dereference.

Because the two use-cases are similar in many ways, they share the syntax array[i], but the existence or absence of a & changes how that syntax is interpreted. Without &, it's a dereference and actually reads from the array. With &, it's not. The value array + i * sizeof(long) is still calculated, but it is not dereferenced.

The situation is very similar with mov and lea. With mov, a dereference occurs that does not happen with lea. This is despite the use of parentheses that occurs in both. For instance, movq (%r8), %r9 and leaq (%r8), %r9. With mov, these parentheses mean "dereference"; with lea, they don't. This is similar to how array[i] only means "dereference" when there is no &.

An example is in order.

Consider the code

```<code>movq (%rdi, %rsi, 8), %rbp
</code>```

This loads the value at the memory location %rdi + %rsi * 8 into the register %rbp. That is: get the value in the register %rdi and the value in the register %rsi. Multiply the latter by 8, and then add it to the former. Find the value at this location and place it into the register %rbp.

This code corresponds to the C line x = array[i];, where array becomes %rdi and i becomes %rsi and x becomes %rbp. The 8 is the length of the data type contained in the array.

Now consider similar code that uses lea:

```<code>leaq (%rdi, %rsi, 8), %rbp
</code>```

Just as the use of movq corresponded to dereferencing, the use of leaq here corresponds to not dereferencing. This line of assembly corresponds to the C line x = &array[i];. Recall that & changes the meaning of array[i] from dereferencing to simply specifying a location. Likewise, the use of leaq changes the meaning of (%rdi, %rsi, 8) from dereferencing to specifying a location.

The semantics of this line of code are as follows: get the value in the register %rdi and the value in the register %rsi. Multiply the latter by 8, and then add it to the former. Place this value into the register %rbp.  No load from memory is involved, just arithmetic operations [2].

Note that the only difference between my descriptions of leaq and movq is that movq does a dereference, and leaq doesn't. In fact, to write the leaq description, I basically copy+pasted the description of movq, and then removed "Find the value at this location".

To summarize: movq vs. leaq is tricky because they treat the use of parentheses, as in (%rsi) and (%rdi, %rsi, 8), differently. In movq (and all other instruction except lea), these parentheses denote a genuine dereference, whereas in leaq they do not and are purely convenient syntax.

[1] I've said that when array is an array of long, the expression array[i] loads the value from the address array + i * sizeof(long). This is true, but there's a subtlety that should be addressed. If I write the C code

```<code>long x = array[5];
</code>```

this is not the same as typing

```<code>long x = *(array + 5 * sizeof(long));
</code>```

It seems that it should be based on my previous statements, but it's not.

What's going on is that C pointer addition has a trick to it. Say I have a pointer p pointing to values of type T. The expression p + i does not mean "the position at p plus i bytes". Instead, the expression p + i actually means "the position at p plus i * sizeof(T) bytes".

The convenience of this is that to get "the next value" we just have to write p + 1 instead of p + 1 * sizeof(T).

This means that the C code long x = array[5]; is actually equivalent to

```<code>long x = *(array + 5)
</code>```

because C will automatically multiply the 5 by sizeof(long).

So in the context of this StackOverflow question, how is this all relevant? It means that when I say "the address array + i * sizeof(long)", I do not mean for "array + i * sizeof(long)" to be interpreted as a C expression. I am doing the multiplication by sizeof(long) myself in order to make my answer more explicit, but understand that due to that, this expression should not be read as C. Just as normal math that uses C syntax.

[2] Side note: because all lea does is arithmetic operations, its arguments don't actually have to refer to valid addresses. For this reason, it's often used to perform pure arithmetic on values that may not be intended to be dereferenced. For instance, cc with -O2 optimization translates

```<code>long f(long x) {
  return x * 5;
}
</code>```

into the following (irrelevant lines removed):

```<code>f:
  leaq (%rdi, %rdi, 4), %rax  # set %rax to %rdi + %rdi * 4
  ret
</code>```

Body:
I would like to know what the difference between these instructions is:

MOV AX, [TABLE-ADDR]

and

LEA AX, [TABLE-ADDR]

Body:
None of the previous answers quite got to the bottom of my own confusion, so I'd like to add my own.

What I was missing is that lea operations treat the use of parentheses different than how mov does.

Think of C. Let's say I have an array of long that I call array. Now the expression array[i] performs a dereference, loading the value from memory at the address array + i * sizeof(long) [1].

On the other hand, consider the expression &array[i]. This still contains the sub-expression array[i], but no dereferencing is performed! The meaning of array[i] has changed. It no longer means to perform a deference but instead acts as a kind of a specification, telling & what memory address we're looking for.  If you like, you could alternatively think of the & as "cancelling out" the dereference.

Because the two use-cases are similar in many ways, they share the syntax array[i], but the existence or absence of a & changes how that syntax is interpreted. Without &, it's a dereference and actually reads from the array. With &, it's not. The value array + i * sizeof(long) is still calculated, but it is not dereferenced.

The situation is very similar with mov and lea. With mov, a dereference occurs that does not happen with lea. This is despite the use of parentheses that occurs in both. For instance, movq (%r8), %r9 and leaq (%r8), %r9. With mov, these parentheses mean "dereference"; with lea, they don't. This is similar to how array[i] only means "dereference" when there is no &.

An example is in order.

Consider the code

movq (%rdi, %rsi, 8), %rbp

This loads the value at the memory location %rdi + %rsi * 8 into the register %rbp. That is: get the value in the register %rdi and the value in the register %rsi. Multiply the latter by 8, and then add it to the former. Find the value at this location and place it into the register %rbp.

This code corresponds to the C line x = array[i];, where array becomes %rdi and i becomes %rsi and x becomes %rbp. The 8 is the length of the data type contained in the array.

Now consider similar code that uses lea:

leaq (%rdi, %rsi, 8), %rbp

Just as the use of movq corresponded to dereferencing, the use of leaq here corresponds to not dereferencing. This line of assembly corresponds to the C line x = &array[i];. Recall that & changes the meaning of array[i] from dereferencing to simply specifying a location. Likewise, the use of leaq changes the meaning of (%rdi, %rsi, 8) from dereferencing to specifying a location.

The semantics of this line of code are as follows: get the value in the register %rdi and the value in the register %rsi. Multiply the latter by 8, and then add it to the former. Place this value into the register %rbp.  No load from memory is involved, just arithmetic operations [2].

Note that the only difference between my descriptions of leaq and movq is that movq does a dereference, and leaq doesn't. In fact, to write the leaq description, I basically copy+pasted the description of movq, and then removed "Find the value at this location".

To summarize: movq vs. leaq is tricky because they treat the use of parentheses, as in (%rsi) and (%rdi, %rsi, 8), differently. In movq (and all other instruction except lea), these parentheses denote a genuine dereference, whereas in leaq they do not and are purely convenient syntax.

[1] I've said that when array is an array of long, the expression array[i] loads the value from the address array + i * sizeof(long). This is true, but there's a subtlety that should be addressed. If I write the C code

long x = array[5];

this is not the same as typing

long x = *(array + 5 * sizeof(long));

It seems that it should be based on my previous statements, but it's not.

What's going on is that C pointer addition has a trick to it. Say I have a pointer p pointing to values of type T. The expression p + i does not mean "the position at p plus i bytes". Instead, the expression p + i actually means "the position at p plus i * sizeof(T) bytes".

The convenience of this is that to get "the next value" we just have to write p + 1 instead of p + 1 * sizeof(T).

This means that the C code long x = array[5]; is actually equivalent to

long x = *(array + 5)

because C will automatically multiply the 5 by sizeof(long).

So in the context of this StackOverflow question, how is this all relevant? It means that when I say "the address array + i * sizeof(long)", I do not mean for "array + i * sizeof(long)" to be interpreted as a C expression. I am doing the multiplication by sizeof(long) myself in order to make my answer more explicit, but understand that due to that, this expression should not be read as C. Just as normal math that uses C syntax.

[2] Side note: because all lea does is arithmetic operations, its arguments don't actually have to refer to valid addresses. For this reason, it's often used to perform pure arithmetic on values that may not be intended to be dereferenced. For instance, cc with -O2 optimization translates

long f(long x) {
  return x * 5;
}

into the following (irrelevant lines removed):

f:
  leaq (%rdi, %rdi, 4), %rax  # set %rax to %rdi + %rdi * 4
  ret


来源: stackexchange

问:
Finishing current activity from a fragment
I have a fragment in an activity that I am using as a navigation drawer.  It contains buttons that when clicked start new activities (startActivity from a fragment simply calls startActivity on the current activity).

For the life of me I can't seem to figure out how I would finish the current activity after starting a new one.

I am looking to achieve something like this in the fragment:

```<code>@Override
public void onClick(View view) {
    // TODO Auto-generated method stub
    if (view == mButtonShows) {
        Intent intent = new Intent(view.getContext(), MyNewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }
}
</code>```

But it seems Fragment.class does not implement finish() (like it implements startActivity(...)).

I would like the activity backstack cleared when they launch the 2nd activity. (so pressing back from the new activity would technically drop them back to the launcher)

答:
Try this. There shouldn't be any warning...</p>

```<code>            Activity thisActivity = getActivity();
            if (thisActivity != null) {
                startActivity(new Intent(thisActivity, yourActivity.class)); // if needed
                thisActivity.finish();
            }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a fragment in an activity that I am using as a navigation drawer.  It contains buttons that when clicked start new activities (startActivity from a fragment simply calls startActivity on the current activity).

For the life of me I can't seem to figure out how I would finish the current activity after starting a new one.

I am looking to achieve something like this in the fragment:

@Override
public void onClick(View view) {
    // TODO Auto-generated method stub
    if (view == mButtonShows) {
        Intent intent = new Intent(view.getContext(), MyNewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }
}

But it seems Fragment.class does not implement finish() (like it implements startActivity(...)).

I would like the activity backstack cleared when they launch the 2nd activity. (so pressing back from the new activity would technically drop them back to the launcher)

Body:
Try this. There shouldn't be any warning...

            Activity thisActivity = getActivity();
            if (thisActivity != null) {
                startActivity(new Intent(thisActivity, yourActivity.class)); // if needed
                thisActivity.finish();
            }

ContentLicense: CC BY-SA 4.0


问:
How can I run a service inside a docker container to get feed from a IDS uEye camera using gstreamer?
I have a docker container that uses a gstreamer plugin to capture the input of a camera. It runs fine with a Bastler camera but now I need to use an IDS uEye camera. To be able to use this camera I need to have the ueyeusbdrc service running. The IDS documentation says that to start it I can run sudo systemctl start ueyeusbdrc or sudo /etc/init.d/ueyeusbdrc start. The problem is that when the docker container runs, that service is not running and I get a Failed to initialize camera error, which is the same error I get if I run gst-launch-1.0 -v idsueyesrc ! videoconvert ! autovideosink and the ueyeusbdrc service is not running outside the container in my PC. So this tells me that the issue is that the ueyeusbdrc service is not running inside the container.

How can I run the ueyeusbdrc inside the docker container? I tried to run /etc/init.d/ueyeusbdrc start in the .sh script that launches the application (which is called using ENTRYPOINT ["<.sh file>"] in the Dockerfile), but it fails. Also if I try to use sudo, it tells me that the command doesn't exist. If I run systemctl it also tells me the command doesn't exist. BTW, I am running the docker with privileged: true (at least that's what is set in the docker-compose.yml file).

I am using Ubuntu 18.04.

Update:
I mapped /run/ueyed and /var/run/ueyed to the container and that changed the error from Failed to initialize camera to Failed to initialize video capture. It may be that I can run the daemon in the host and there is a way to hook it to the container. Any suggestions on how to do that?

答:
Finally got this working. I had to add a few options to the docker command (in my case to the docker-compose yml file). I based my solution on the settings found here: https://github.com/chalmers-revere/opendlv-device-camera-ueye

Adding these arguments to the docker command solved the issue: --ipc=host --pid=host -v /var/run:/var/run. With these options there is no need to run the service inside the container.

The other key part is to install the IDS software inside the docker container. This can be easily done by downloading, extracting and running the installer (the git repo mentioned above has an outdated version, but the most recent version can be found in the IDS web page).

Also, make sure the system service for the IDS uEye camera is running in the host (sudo systemctl start ueyeusbdrc).


问:
QTabWidget: close tab button not working
I have set ui->tabWidget->setTabsClosable(true); but QTabwidget only showing a cross on each tab that is not closing tab on click on this button. What else I have to do to make tabs closable? I tried to connect any slot (which would be proper for this work) of close to signal tabCloseRequested(int) but couldn't find any such slot in tabwidget. Please suggest the right way.

答:
For future stumblers upon this question looking for a PyQt5 solution, this can be condensed into a 1-liner:

```<code>tabs = QTabWidget()
tabs.tabCloseRequested.connect(lambda index: tabs.removeTab(index))
</code>```

The tabCloseRequested signal emits an integer equal to the index of the tab that emitted it, so you can just connect it to a lambda function that takes the index as its argument.

The only problem I could see with this is that connecting a lambda function to the slot prevents the object from getting garbage collected when the tab is deleted (see here).

EDIT (9/7/21): The lambda function  isn't actually necessary since QTabWidget.removeTab takes an integer index as its sole argument by default, so the following will suffice (and avoids the garbage-collection issue):

```<code>tabs.tabCloseRequested.connect(tabs.removeTab)
</code>```

Body:
For future stumblers upon this question looking for a PyQt5 solution, this can be condensed into a 1-liner:

tabs = QTabWidget()
tabs.tabCloseRequested.connect(lambda index: tabs.removeTab(index))

The tabCloseRequested signal emits an integer equal to the index of the tab that emitted it, so you can just connect it to a lambda function that takes the index as its argument.

The only problem I could see with this is that connecting a lambda function to the slot prevents the object from getting garbage collected when the tab is deleted (see here).

EDIT (9/7/21): The lambda function  isn't actually necessary since QTabWidget.removeTab takes an integer index as its sole argument by default, so the following will suffice (and avoids the garbage-collection issue):

tabs.tabCloseRequested.connect(tabs.removeTab)


问:
Add Shadow To ClipRRect
I want to add a shadow to a ClipRRect in Flutter. I want it to look like this:

But when I try building it I get something like this:

The shadow is going across the whole box instead of the ClipRRect area. Here is my code:

Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
            boxShadow: [
              BoxShadow(
                color: Color(0x54000000),
                spreadRadius: 10,
                blurRadius: 2,
              ),
            ],
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(250)),
            child: Container(
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                      end: Alignment.bottomCenter,
                      begin: Alignment.topCenter,
                      colors: [
                    Theme.of(context).primaryColor,
                    Color(0xff995DFF)
                  ])),
              height: 500,
              width: MediaQuery.of(context).size.width,
            ),
          ),
        )
      ],
    )
```

Somehow the shadow needs to be just on the ClipRRect. Thanks for any help

答:
This happens because the container that has shadown is a rect as default shape...

An option is put BorderRadius in decoration of container father like this:

```<code>        Column(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                //Here goes the same radius, u can put into a var or function
                borderRadius:
                    BorderRadius.only(bottomLeft: Radius.circular(250)),
                boxShadow: [
                  BoxShadow(
                    color: Color(0x54000000),
                    spreadRadius:4,
                    blurRadius: 20,
                  ),
                ],
              ),
              child: ClipRRect(
                borderRadius:
                    BorderRadius.only(bottomLeft: Radius.circular(250)),
                child: Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      end: Alignment.bottomCenter,
                      begin: Alignment.topCenter,
                      colors: [
                        Theme.of(context).primaryColor,
                        Color(0xff995DFF)
                      ],
                    ),
                  ),
                  height: 500,
                  width: MediaQuery.of(context).size.width,
                ),
              ),
            )
          ],
        ),
</code>```

Title: Add Shadow To ClipRRect

Body:
I want to add a shadow to a ClipRRect in Flutter. I want it to look like this:

But when I try building it I get something like this:

The shadow is going across the whole box instead of the ClipRRect area. Here is my code:

Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
            boxShadow: [
              BoxShadow(
                color: Color(0x54000000),
                spreadRadius: 10,
                blurRadius: 2,
              ),
            ],
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(250)),
            child: Container(
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                      end: Alignment.bottomCenter,
                      begin: Alignment.topCenter,
                      colors: [
                    Theme.of(context).primaryColor,
                    Color(0xff995DFF)
                  ])),
              height: 500,
              width: MediaQuery.of(context).size.width,
            ),
          ),
        )
      ],
    )

Somehow the shadow needs to be just on the ClipRRect. Thanks for any help

Body:
This happens because the container that has shadown is a rect as default shape...

An option is put BorderRadius in decoration of container father like this:

        Column(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                //Here goes the same radius, u can put into a var or function
                borderRadius:
                    BorderRadius.only(bottomLeft: Radius.circular(250)),
                boxShadow: [
                  BoxShadow(
                    color: Color(0x54000000),
                    spreadRadius:4,
                    blurRadius: 20,
                  ),
                ],
              ),
              child: ClipRRect(
                borderRadius:
                    BorderRadius.only(bottomLeft: Radius.circular(250)),
                child: Container(
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      end: Alignment.bottomCenter,
                      begin: Alignment.topCenter,
                      colors: [
                        Theme.of(context).primaryColor,
                        Color(0xff995DFF)
                      ],
                    ),
                  ),
                  height: 500,
                  width: MediaQuery.of(context).size.width,
                ),
              ),
            )
          ],
        ),


问:
Adding link color to CSS properties group
Is it possible to specify the hyperlink color within the main CSS properties statement like below? I have tried several variations and no luck. </p>

```<code>width: 100%;
color: #FFF;
background-color: #693F18;
a.link-color: #fff;
</code>```

答:
There are several different ways to style a hyperlink: a for the link itself, along with the following pseudo-classes:

a:link - a normal, unvisited link

a:visited - a link the user has visited

a:hover - a link when the user mouses over it

a:active - a link the moment it is clicked

To change the colour, you're looking for the color property.

This can be seen in the following:

a {
  color: cyan;
}

a:link {
  color: blue;
}

a:visited {
  color: red;
}

a:hover {
  color: green;
}

a:active {
  color: purple;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Link</code>```

Body:
Is it possible to specify the hyperlink color within the main CSS properties statement like below? I have tried several variations and no luck.

width: 100%;
color: #FFF;
background-color: #693F18;
a.link-color: #fff;

Body:
There are several different ways to style a hyperlink: a for the link itself, along with the following pseudo-classes:

a:link - a normal, unvisited link

a:visited - a link the user has visited

a:hover - a link when the user mouses over it

a:active - a link the moment it is clicked

To change the colour, you're looking for the color property.

This can be seen in the following:

a {
  color: cyan;
}

a:link {
  color: blue;
}

a:visited {
  color: red;
}

a:hover {
  color: green;
}

a:active {
  color: purple;
}

<a href="#">Link</a>


问:
How to get top 5 items for each group in grouped dataframe?
```<code>df = pd.DataFrame({'Weekday':list('MMMMMMMMMMTTTTTTTTTT'),
                  'Items': list("AAABBCDEFGBBBCCADEFG")
                  })

grouped = df.groupby(['Weekday','Items'],sort=True).agg({'Items': 'count'})
</code>```

Then, I get the result of grouped:

```<code>Weekday Items
M       A          3
        B          2
        C          1
        D          1
        E          1
        F          1
        G          1
T       A          1
        B          3
        C          2
        D          1
        E          1
        F          1
        G          1
</code>```

So how to output the top 5 items for each "weekdays" (5 for 'M' and 'T'), like:

```<code>Weekday Items
M       A          3
        B          2
        C          1
        D          1
        E          1

T
        B          3
        C          2
        A          1
        D          1
        E          1
</code>```

Anyone can help this?

答:
```<code>df = pd.DataFrame({'Weekday':list('MMMMMMMMMMTTTTTTTTTT'),
              'Item': list("AAABBCDEFGBBBCCADEFG")
              })

grouped = df.groupby(['Weekday','Item'],sort=True).agg(count=('Item', 'count'))

grouped.sort_values(['Weekday','count'],ascending=False).groupby('Weekday').head(5)

           count
Weekday Item
   T    B   3
        C   2
        A   1
        D   1
        E   1
    M   A   3
        B   2
        C   1
        D   1
        E   1
</code>```

Body:
df = pd.DataFrame({'Weekday':list('MMMMMMMMMMTTTTTTTTTT'),
                  'Items': list("AAABBCDEFGBBBCCADEFG")
                  })

grouped = df.groupby(['Weekday','Items'],sort=True).agg({'Items': 'count'})

Then, I get the result of grouped:

Weekday Items
M       A          3
        B          2
        C          1
        D          1
        E          1
        F          1
        G          1
T       A          1
        B          3
        C          2
        D          1
        E          1
        F          1
        G          1

So how to output the top 5 items for each "weekdays" (5 for 'M' and 'T'), like:

Weekday Items
M       A          3
        B          2
        C          1
        D          1
        E          1

T
        B          3
        C          2
        A          1
        D          1
        E          1

Anyone can help this?


问:
MomentJS - Grabbing the current time as a decimal value?
I'm trying to get the current time as a decimal value between 0 and 24

```<code>    const currentEpoch = moment().tz('America/Phoenix')
    const convertedEpoch = moment.unix(currentEpoch).format('hh:mm')
    const currentTimeAsNumeric = moment.duration(convertedEpoch).asHours();
</code>```

for example.. 4:30pm would be 16.5

I keep getting variable numbers from the code I've tried above.

答:
from the https://momentjs.com/ docs you could do something very lightweight like:

parseFloat(moment().format("H")) + parseFloat(moment().format("mm")/60)

Body:
I'm trying to get the current time as a decimal value between 0 and 24

    const currentEpoch = moment().tz('America/Phoenix')
    const convertedEpoch = moment.unix(currentEpoch).format('hh:mm')
    const currentTimeAsNumeric = moment.duration(convertedEpoch).asHours();

for example.. 4:30pm would be 16.5

I keep getting variable numbers from the code I've tried above.


问:
Detecting length of overlap between two strings
```<code>int overlap(const char *s1, const char *s2){
    int i = 0;
    while (s1[i] && s2[i] && s1[i] == s2[i])
        i++;
    return i;
}
</code>```

This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are:

```<code>abcdefg
1234efg
</code>```

it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?

答:
```<code>int overlap(const char *s1, const char *s2){
    int k;
    for(k = 0; s1[k] != s2[k]; k++)  // <--- add this loop
      if(0 == s1[k] || 0 == s2[k])
        return 0;
    int i = k;     // initialize to k + 1
    while (s1[i] && s1[i] == s2[i])  // check only s1 (or s2)
        i++;
    return i - k;  // return difference
}
</code>```

Body:
int overlap(const char *s1, const char *s2){
    int i = 0;
    while (s1[i] && s2[i] && s1[i] == s2[i])
        i++;
    return i;
}

This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are:

abcdefg
1234efg

it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?


问:
Keycloak with Spring Cloud Gateway
I have tried securing my Spring Cloud Gateway using Keycloak Spring Boot Adapter. It is showing me this error as soon as I add the keycloak-spring-boot-starter dependency :

```<code>**********************************************************

Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency.

**********************************************************
</code>```

This is the stack trace:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gatewayConfigurationService' defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]: Unsatisfied dependency expressed through method 'gatewayConfigurationService' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=webFluxConversionService)}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:539) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at com.example.gateway.GatewayApplication.main(GatewayApplication.java:13) [classes/:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=webFluxConversionService)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    ... 19 common frames omitted
</code>```

答:
Instead of keycloak-spring-boot-starter, you may use Spring Boot official OAuth2/OpenID Connect client in dependency org.springframework.boot:spring-boot-starter-oauth2-client which works well with Keycloak OIDC flows as shown on Tim te Beek's blog post.

You may also look at the spring-cloud samples on github, esp. sample-gateway-oauth2login. It's a Gradle project but you can easily adapt to Maven.

Title: Keycloak with Spring Cloud Gateway

Body:
I have tried securing my Spring Cloud Gateway using Keycloak Spring Boot Adapter. It is showing me this error as soon as I add the keycloak-spring-boot-starter dependency :

**********************************************************

Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency.

**********************************************************

This is the stack trace:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gatewayConfigurationService' defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]: Unsatisfied dependency expressed through method 'gatewayConfigurationService' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=webFluxConversionService)}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:539) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]
    at com.example.gateway.GatewayApplication.main(GatewayApplication.java:13) [classes/:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=webFluxConversionService)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789) ~[spring-beans-5.2.3.RELEASE.jar:5.2.3.RELEASE]
    ... 19 common frames omitted


问:
Deleting uploaded certificate from elastic load balancer
I've been testing and experimenting a bit to find out how exactly to upload SSL Certificates to AWS's Elastic Load Balancer (figuring out issues with different key and certificate encodings).

Therefore I have quite a few test certificates on there that I've generated with either the wrong information, missing certificate chains or just bogus data.

As far as I can see there is no way to delete these certificates, or even update/replace the ones that are missing certain information. AWS's instructions to "updating a certificate" (http://docs.amazonwebservices.com/ElasticLoadBalancing/latest/DeveloperGuide/US_UpdatingLoadBalancerSSL.html) actually just shows you how to change the load balancer listener to use a different certificate that is either already on there or that you can then upload as well! (that's exactly how I ended up with so many certificates on there in the first place).

Could someone please tell me that I'm wrong and there is a way to delete them? :D (and preferably also how to do that)

答:
As far as I can tell (at least with Boto3)

you can add a new certificate to the listener, but not as the default certificate (the isDefault attribute is rejected)

you cannot delete the existing "default" certificate while it is the default

you cannot modify which certificate is the default

an SSL listener may not have no certificates (you can't delete all the certificates and add a new default one).

Therefore, the only option left is either to delete the loadbalancer or delete the listener (what the hey!). Because the listener may be attached to a lot of routing information, this is a PITA. So, what I recommend is:

upload the certificate

retrieve the state of the listeners referencing the old SSL

make a note of their rules

delete those listeners

recreate them with just their CertificateArn changed (an pointing to your new certificate.

Something like this:

```<code>   import boto3

   def fixRule(rule):
            """Copy a rule so that it can be submitted as a new rule"""
            rule = rule.copy()
            if rule["IsDefault"]:
                # The default rule is set at create_listener
                return None

            def fix_condition(c):
                c = c.copy()
                del c["Values"]
                return c
            rule["Conditions"] = [fix_condition(c) for c in rule.get("Conditions",())]
            # del rule["Priority"]
            del rule["RuleArn"]
            del rule["IsDefault"]
            # rule["Priority"] = rule["Priority"]
            try:
                rule["Priority"] = int(rule["Priority"])
            except:
                del rule["Priority"]
            return rule

   acmClient = session.client('acm')
   response = acmClient.import_certificate(
                Certificate=certificate,
                PrivateKey=privatekey,
                CertificateChain=chain
            )
   current_ssl_arn = response[ 'CertificateArn']

   session.client('resourcegroupstaggingapi').tag_resources(
                ResourceARNList=[
                    current_ssl_arn
                ],
                Tags={ ... whaterver }
                }
            )

   # Replace each SSL listener with one that has a new certificate.
   lbClient = session.client('elbv2')
   listeners = lbClient.describe_listeners(LoadBalancerArn=self.lb_arn["Listeners"]

   # Make existing listeners use the certificate
   # Delete exisiting listeners with SSL certificates
   # Create a new one with the same parameters and rules as the old one.
   for l in listeners:
            oldListenerArn = l["ListenerArn"]

            # Only deal with SSL listeners
            if l.get("SslPolicy")==None: continue

            _listener_certs = l.get("Certificates",())
            _listener_cert_arns = set(c['CertificateArn'] for c in _listener_certs)

            # Great! already up-to-date
            if current_ssl_arn in _listener_cert_arns: continue

            # Backup the rules
            oldRules = lbClient.describe_rules(ListenerArn=oldListenerArn)['Rules']

            # Recreate the listener with the new certificate
            print("Replacing listener")
            _ = lbClient.delete_listener(ListenerArn = oldListenerArn)

            l = l.copy()
            del l["ListenerArn"]
            l["Certificates"] = [{"CertificateArn":current_ssl_arn}]
            newListener = lbClient.create_listener(**l)["Listeners"][0]
            newListenerArn = newListener["ListenerArn"]

            print("Replacing listener .. copying ({}) rules ".format(len(oldRules)))
            for rule in oldRules:
                rule = fixRule(rule)
                if rule is None: continue
                _ = lbClient.create_rule(
                    ListenerArn=newListenerArn,
                    **rule)
            print("Replacing listener .. OK")

</code>```

Its not ideal, since if anything goes wrong then there's downtime. Though I think this is the best with the tools Amazon provided.

Body:
As far as I can tell (at least with Boto3)

you can add a new certificate to the listener, but not as the default certificate (the isDefault attribute is rejected)

you cannot delete the existing "default" certificate while it is the default

you cannot modify which certificate is the default

an SSL listener may not have no certificates (you can't delete all the certificates and add a new default one).

Therefore, the only option left is either to delete the loadbalancer or delete the listener (what the hey!). Because the listener may be attached to a lot of routing information, this is a PITA. So, what I recommend is:

upload the certificate

retrieve the state of the listeners referencing the old SSL

make a note of their rules

delete those listeners

recreate them with just their CertificateArn changed (an pointing to your new certificate.

Something like this:

   import boto3

   def fixRule(rule):
            """Copy a rule so that it can be submitted as a new rule"""
            rule = rule.copy()
            if rule["IsDefault"]:
                # The default rule is set at create_listener
                return None

            def fix_condition(c):
                c = c.copy()
                del c["Values"]
                return c
            rule["Conditions"] = [fix_condition(c) for c in rule.get("Conditions",())]
            # del rule["Priority"]
            del rule["RuleArn"]
            del rule["IsDefault"]
            # rule["Priority"] = rule["Priority"]
            try:
                rule["Priority"] = int(rule["Priority"])
            except:
                del rule["Priority"]
            return rule

   acmClient = session.client('acm')
   response = acmClient.import_certificate(
                Certificate=certificate,
                PrivateKey=privatekey,
                CertificateChain=chain
            )
   current_ssl_arn = response[ 'CertificateArn']

   session.client('resourcegroupstaggingapi').tag_resources(
                ResourceARNList=[
                    current_ssl_arn
                ],
                Tags={ ... whaterver }
                }
            )

   # Replace each SSL listener with one that has a new certificate.
   lbClient = session.client('elbv2')
   listeners = lbClient.describe_listeners(LoadBalancerArn=self.lb_arn["Listeners"]

   # Make existing listeners use the certificate
   # Delete exisiting listeners with SSL certificates
   # Create a new one with the same parameters and rules as the old one.
   for l in listeners:
            oldListenerArn = l["ListenerArn"]

            # Only deal with SSL listeners
            if l.get("SslPolicy")==None: continue

            _listener_certs = l.get("Certificates",())
            _listener_cert_arns = set(c['CertificateArn'] for c in _listener_certs)

            # Great! already up-to-date
            if current_ssl_arn in _listener_cert_arns: continue

            # Backup the rules
            oldRules = lbClient.describe_rules(ListenerArn=oldListenerArn)['Rules']

            # Recreate the listener with the new certificate
            print("Replacing listener")
            _ = lbClient.delete_listener(ListenerArn = oldListenerArn)

            l = l.copy()
            del l["ListenerArn"]
            l["Certificates"] = [{"CertificateArn":current_ssl_arn}]
            newListener = lbClient.create_listener(**l)["Listeners"][0]
            newListenerArn = newListener["ListenerArn"]

            print("Replacing listener .. copying ({}) rules ".format(len(oldRules)))
            for rule in oldRules:
                rule = fixRule(rule)
                if rule is None: continue
                _ = lbClient.create_rule(
                    ListenerArn=newListenerArn,
                    **rule)
            print("Replacing listener .. OK")

Its not ideal, since if anything goes wrong then there's downtime. Though I think this is the best with the tools Amazon provided.


问:
Android Espresso: PerformException
I`m getting

android.support.test.espresso.PerformException: Error performing 'send
  keyCode: 4, metaState: 0 key event' on view 'Animations or transitions
  are enabled on the target device.

I read articles with same error but didnt find answer.

I have simple android app and I try to test simple thing:

Load RecyclerView

Click on RecyclerView`s item

Open Activity

Press button inside Activity

Press back

Repeat from part 1.

Code is extremely easy:

```<code>@Test
public void getOver500Products() {
    onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
    onView(withId(R.id.layout2)).perform(click());
    clickExactItem(2);
    for (int i = 0; i< 501; i++) {
        clickRandomItem();
        addedToCart();
        Espresso.pressBack();
    }
}

public void clickRandomItem() {
    try {
        int x = getRandomRecyclerPosition(R.id.list);
        clickExactItem(x);
    } catch (NoMatchingViewException e) {
    }
}

public void clickExactItem(int position) {
    onView(withId(R.id.list))
            .perform(RecyclerViewActions
                    .actionOnItemAtPosition(position, click()));
}

public boolean addedToCart() {
    try {
        onView(withId(R.id.product_add_in_cart)).perform(click());
    } catch (NoMatchingViewException e) {
        return false;
    }
    return true;
}
</code>```

It throws exception after 10-50 iterations (randomly) so basically code is right.

EspressoTestDev.java:88 line where it crashes is

```<code>Espresso.pressBack();
</code>```

Exactly after this line I`m getting exception.

Exception stacktrace:

```<code>android.support.test.espresso.PerformException: Error performing 'send keyCode: 4, metaState: 0 key event' on view 'Animations or transitions are enabled on the target device.

is a root view.'.
at android.support.test.espresso.PerformException$Builder.build(PerformException.java:83)
at android.support.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:80)
at android.support.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:56)
at android.support.test.espresso.ViewInteraction.runSynchronouslyOnUiThread(ViewInteraction.java:184)
at android.support.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:115)
at android.support.test.espresso.ViewInteraction.perform(ViewInteraction.java:87)
at android.support.test.espresso.Espresso.pressBack(Espresso.java:189)
at com.app.myapp.EspressoTestDev.getOver500Products(EspressoTestDev.java:88)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at android.support.test.internal.statement.UiThreadStatement.evaluate(UiThreadStatement.java:55)
at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:270)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1851)
Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints:
is displayed on the screen to the user
Target view: "PopupViewContainer{id=-1, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}"
at android.support.test.espresso.ViewInteraction$1.run(ViewInteraction.java:138)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5549)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
</code>```

Looks like it found problem with PopupViewContainer but I dont use it, dont click it and I have no idea how can it impact to Espresso.pressBack()

What I tried:

Adding getInstrumentation().waitForIdleSync(); before and after Espresso.pressBack()

Making delay as suggested here

The question is: how can I avoid this error or how can I ignore and continue iterations in my case?

答: I've run into the error Animations or transitions are enabled on the target device several times.  In the latest case, the real problem was that my UI code was throwing a NullPointerException.  Unfortunately Espresso was "swallowing" the NullPointerException and giving me the irrelevant error Animations or transitions are enabled on the target device.

Title: Android Espresso: PerformException

Body:
I`m getting

android.support.test.espresso.PerformException: Error performing 'send
  keyCode: 4, metaState: 0 key event' on view 'Animations or transitions
  are enabled on the target device.

I read articles with same error but didnt find answer.

I have simple android app and I try to test simple thing:

Load RecyclerView

Click on RecyclerView`s item

Open Activity

Press button inside Activity

Press back

Repeat from part 1.

Code is extremely easy:

@Test
public void getOver500Products() {
    onView(withId(R.id.drawer_layout)).perform(DrawerActions.open());
    onView(withId(R.id.layout2)).perform(click());
    clickExactItem(2);
    for (int i = 0; i< 501; i++) {
        clickRandomItem();
        addedToCart();
        Espresso.pressBack();
    }
}

public void clickRandomItem() {
    try {
        int x = getRandomRecyclerPosition(R.id.list);
        clickExactItem(x);
    } catch (NoMatchingViewException e) {
    }
}

public void clickExactItem(int position) {
    onView(withId(R.id.list))
            .perform(RecyclerViewActions
                    .actionOnItemAtPosition(position, click()));
}

public boolean addedToCart() {
    try {
        onView(withId(R.id.product_add_in_cart)).perform(click());
    } catch (NoMatchingViewException e) {
        return false;
    }
    return true;
}

It throws exception after 10-50 iterations (randomly) so basically code is right.

EspressoTestDev.java:88 line where it crashes is

Espresso.pressBack();

Exactly after this line I`m getting exception.

Exception stacktrace:

android.support.test.espresso.PerformException: Error performing 'send keyCode: 4, metaState: 0 key event' on view 'Animations or transitions are enabled on the target device.

is a root view.'.
at android.support.test.espresso.PerformException$Builder.build(PerformException.java:83)
at android.support.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:80)
at android.support.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:56)
at android.support.test.espresso.ViewInteraction.runSynchronouslyOnUiThread(ViewInteraction.java:184)
at android.support.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:115)
at android.support.test.espresso.ViewInteraction.perform(ViewInteraction.java:87)
at android.support.test.espresso.Espresso.pressBack(Espresso.java:189)
at com.app.myapp.EspressoTestDev.getOver500Products(EspressoTestDev.java:88)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at android.support.test.internal.statement.UiThreadStatement.evaluate(UiThreadStatement.java:55)
at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:270)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1851)
Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints:
is displayed on the screen to the user
Target view: "PopupViewContainer{id=-1, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}"
at android.support.test.espresso.ViewInteraction$1.run(ViewInteraction.java:138)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5549)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)

Looks like it found problem with PopupViewContainer but I dont use it, dont click it and I have no idea how can it impact to Espresso.pressBack()

What I tried:

Adding getInstrumentation().waitForIdleSync(); before and after Espresso.pressBack()

Making delay as suggested here

The question is: how can I avoid this error or how can I ignore and continue iterations in my case?


问:
Reactjs ERR_INVALID_ARG_TYPE
there!
I bought some template from themeforest and everything works fine with previews version, but with the new one I'm having error like

```<code>> TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type
> string. Received type undefined
>         at validateString (internal/validators.js:125:11)
>         at Object.join (path.js:427:7)
>         at noopServiceWorkerMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)
>         at trim_prefix (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:317:13)
>         at C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:284:7
>         at Function.process_params (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:335:12)
>         at next (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:275:10)
>         at launchEditorMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)
>         at trim_prefix (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:317:13)
>         at C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:284:7
>         at Function.process_params (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:335:12)
>         at next (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:275:10)
>         at handleWebpackInternalMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\evalSourceMapMiddleware.js:42:7)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)
</code>```

I believe that template is not supposed to have this error, but still I have it. What could be the problem?

答:
You can check this link https://github.com/ionic-team/ionic/issues/20503

To fix this issue simply upgrade to "react-scripts": "^3.4.0"

Overwrite the existing "react-scripts": "^3.x.x" with"react-scripts": "^3.4.0" in your package.json

Delete your node modules

Finally run npm install or yarn install into your command prompt.

i hope it will fix it.

Title: Reactjs ERR_INVALID_ARG_TYPE

Body:
there!
I bought some template from themeforest and everything works fine with previews version, but with the new one I'm having error like

> TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type
> string. Received type undefined
>         at validateString (internal/validators.js:125:11)
>         at Object.join (path.js:427:7)
>         at noopServiceWorkerMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)
>         at trim_prefix (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:317:13)
>         at C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:284:7
>         at Function.process_params (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:335:12)
>         at next (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:275:10)
>         at launchEditorMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)
>         at trim_prefix (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:317:13)
>         at C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:284:7
>         at Function.process_params (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:335:12)
>         at next (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:275:10)
>         at handleWebpackInternalMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\evalSourceMapMiddleware.js:42:7)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)

I believe that template is not supposed to have this error, but still I have it. What could be the problem?


问:
can we use order by clause with group by
Hi
   I am using following query --

```<code>select * from table_name order by status desc
</code>```

It shows the desired result with all records,but as n when i use following query -

```<code>select * from table_name group by category order by status desc
</code>```

It shows only 2 records of distinct category with sorted order.

Is it because i am using order by with group by.....

答:
Yes.

Often you'll want to use aggregate functions like COUNT() and SUM() with the GROUP BY clause.

For instance count the number of records with the first name Bob.

```<code>SELECT First_Name, COUNT(First_Name) FROM Users GROUP BY First_Name ORDER BY First_Name ASC;
</code>```

Body:
Hi
   I am using following query --

select * from table_name order by status desc

It shows the desired result with all records,but as n when i use following query -

select * from table_name group by category order by status desc

It shows only 2 records of distinct category with sorted order.

Is it because i am using order by with group by.....

Body:
Yes.

Often you'll want to use aggregate functions like COUNT() and SUM() with the GROUP BY clause.

For instance count the number of records with the first name Bob.

SELECT First_Name, COUNT(First_Name) FROM Users GROUP BY First_Name ORDER BY First_Name ASC;


答:
```<code> grouped = (df.groupby(['Weekday','Items'])
            .Items.agg(counter='count')
            .groupby(['Weekday'],
            as_index=False))

pd.concat([group.nlargest(5,'counter') for name,group in grouped])

              counter
Weekday Items
M       A       3
        B       2
        C       1
        D       1
        E       1
T       B       3
        C       2
        A       1
        D       1
        E       1
</code>```

groupby twice, first to get the counter variable. the second groupby allows an iteration through the groups to get the top 5, using nlargest. last step is to combine the dataframes in the list into one.

vb_rise's solution should be faster as it avoids the iteration process.

Title: How to get top 5 items for each group in grouped dataframe?

Body:
 grouped = (df.groupby(['Weekday','Items'])
            .Items.agg(counter='count')
            .groupby(['Weekday'],
            as_index=False))

pd.concat([group.nlargest(5,'counter') for name,group in grouped])

              counter
Weekday Items
M       A       3
        B       2
        C       1
        D       1
        E       1
T       B       3
        C       2
        A       1
        D       1
        E       1

groupby twice, first to get the counter variable. the second groupby allows an iteration through the groups to get the top 5, using nlargest. last step is to combine the dataframes in the list into one.

vb_rise's solution should be faster as it avoids the iteration process.


问:
In pandas, how to convert a numeric type to category type to use with seaborn hue
I am stuck on what seems like an easy problem trying to color the different groups on a scatterplot I am creating. I have the following example dataframe and graph:

```<code>test_df = pd.DataFrame({ 'A' : 1.,
                    'B' : np.array([1, 5, 9, 7, 3], dtype='int32'),
                    'C' : np.array([6, 7, 8, 9, 3], dtype='int32'),
                    'D' : np.array([2, 2, 3, 4, 4], dtype='int32'),
                    'E' : pd.Categorical(["test","train","test","train","train"]),
                    'F' : 'foo' })

# fix to category
# test_df['D'] = test_df["D"].astype('category')

# and test plot
f, ax = plt.subplots(figsize=(6,6))
ax = sns.scatterplot(x="B", y="C", hue="D", s=100,
                     data=test_df)
</code>```

which creates this graph:

However, instead of a continuous scale, I'd like a categorical scale for each of the 3 categories [2, 3, 4]. After I uncomment the line of code test_df['D'] = ..., to change this column to a category column-type for category-coloring in the seaborn plot, I receive the following error from the seaborn plot: TypeError: data type not understood

Does anybody know the correct way to convert this numeric column to a factor / categorical column to use for coloring?

Thanks!

答:
I encoutered the same error TypeError: data type not understood.
Workaround that works is to use option legend="full". Conversion to categorical type is not necessary in this approach:

```<code>ax = sns.scatterplot(x="B", y="C", hue="D", s=100, legend="full", data=test_df)
</code>```

Another solution is to use custom palette:

```<code>ax = sns.scatterplot(x="B", y="C", hue="D", s=100, palette=["b", "g", "r"], data=test_df)
</code>```

In this case number of colours must be equal to unique values in column "D".

Body:
I am stuck on what seems like an easy problem trying to color the different groups on a scatterplot I am creating. I have the following example dataframe and graph:

test_df = pd.DataFrame({ 'A' : 1.,
                    'B' : np.array([1, 5, 9, 7, 3], dtype='int32'),
                    'C' : np.array([6, 7, 8, 9, 3], dtype='int32'),
                    'D' : np.array([2, 2, 3, 4, 4], dtype='int32'),
                    'E' : pd.Categorical(["test","train","test","train","train"]),
                    'F' : 'foo' })

# fix to category
# test_df['D'] = test_df["D"].astype('category')

# and test plot
f, ax = plt.subplots(figsize=(6,6))
ax = sns.scatterplot(x="B", y="C", hue="D", s=100,
                     data=test_df)

which creates this graph:

However, instead of a continuous scale, I'd like a categorical scale for each of the 3 categories [2, 3, 4]. After I uncomment the line of code test_df['D'] = ..., to change this column to a category column-type for category-coloring in the seaborn plot, I receive the following error from the seaborn plot: TypeError: data type not understood

Does anybody know the correct way to convert this numeric column to a factor / categorical column to use for coloring?

Thanks!

Body:
I encoutered the same error TypeError: data type not understood.
Workaround that works is to use option legend="full". Conversion to categorical type is not necessary in this approach:

ax = sns.scatterplot(x="B", y="C", hue="D", s=100, legend="full", data=test_df)

Another solution is to use custom palette:

ax = sns.scatterplot(x="B", y="C", hue="D", s=100, palette=["b", "g", "r"], data=test_df)

In this case number of colours must be equal to unique values in column "D".


问:
Angular 8 @output EventEmitter not letting an Object to be emitted
How would I emit an Object instead of primitive data types?

I have a object const amount = { currenty: 'USD', total: '10.25' };
which I wanted to emmit to the parent component.

```<code>export class MyChildComponent implements OnInit {
     @Output() childEventEmitter: EventEmitter = new EventEmitter();
....
}
</code>```

in the emitter function

this.childEventEmitter.emit(amount); // not working

error: Argument of type { currenty: 'USD', total: '10.25' } not assignable to paraments of type string

答:
```<code>@Output() childEventEmitter: EventEmitter<{currenty: string, total: string}> = new EventEmitter<{currenty: string, total: string}>();
</code>```

Body:
How would I emit an Object instead of primitive data types?

I have a object const amount = { currenty: 'USD', total: '10.25' };
which I wanted to emmit to the parent component.

export class MyChildComponent implements OnInit {
     @Output() childEventEmitter: EventEmitter = new EventEmitter();
....
}

in the emitter function

this.childEventEmitter.emit(amount); // not working

error: Argument of type { currenty: 'USD', total: '10.25' } not assignable to paraments of type string


问:
What does (_) mean when calling a function?
I’ve seen the notation used elsewhere but, just as an example, I recently read about replacing

```<code>ChangeNotifierProvider(
  create: (BuildContext context) => MyCounter()
</code>```

with

```<code> ChangeNotifierProvider(
    create: (_) => MyCounter()
</code>```

What does the latter notation mean? Is the BuildContext parameter optional and the caller chosen to not supply it?

答:
In dart, underscore means private, when used into anonymous function, means something that are not necessary using in that context, but could be any name, it's just a common notation, likely that parameter is "private" and you aren't using it (but nothing stops you to use with _ name, like _.getHashCode())

The use depends on context, for example BuildContext context, sometimes, you will receive it, but not always you'll use it.

Body:
I’ve seen the notation used elsewhere but, just as an example, I recently read about replacing

ChangeNotifierProvider(
  create: (BuildContext context) => MyCounter()

with

 ChangeNotifierProvider(
    create: (_) => MyCounter()

What does the latter notation mean? Is the BuildContext parameter optional and the caller chosen to not supply it?


问:
A compiler's evaluation of the size of an array's declaration. When does it take place?
This is more for clarity or a better understanding of the internal workings of compilers: I'm beginning to study compiler design and compiler theory.

Typically When declaring the size of an array on the stack it has to be known at compile-time and this is understood, but this is not always the case.

What I would like to know is; when does this evaluation occur? Does it happen during the precompiler, tokenizer, syntax analysis, etc.? Also, does it depend on the particular compiler that is being used? Finally, is the point in time of this evaluation specified to be at any particular stage of a compiler within the language standards?

Pseudo Code snippet. C or C++

```<code>int main() {
    int x[5]; // When does the evaluation of the 5 for the array's size take place
              // during the compilation process?
              // Does it take place during pre-compiler or normal compilation time.
    return 0;
}
</code>```

答:
The C standard specifies eight phases of translation:

Physical source multibyte characters and trigraph sequences are mapped to characters of the source character set.

Each backslash followed by a new-line is deleted (splicing together two lines).

The source characters are grouped into preprocessing tokens, and each sequence of white-space characters is replaced by one space, except new-lines are kept.

Preprocessing directives and _Pragma operators are executed, and macro invocations are expanded.

Source characters in strings and character constants are converted to the execution character set.

Adjacent string literals are concatenated.

Each preprocessing token is converted into a grammar token, and white-space characters separated tokens are discarded. The resulting tokens are analyzed and translated (compiled).

All external references are resolved (the program is linked).

Resolution of constant array dimensions thus occurs in phase 7. However, the phases are largely conceptual. The phases explain how the C language is understood, not how a compiler must execute.

For compilers that produce object modules, the sizes of arrays with static storage duration are necessarily resolved before the object information is written, as the array size affects data layout, which must be completely described in the object module. Handling of the sizes of arrays with automatic storage duration could theoretically be left until the program is actually executing code that needs them, as this is necessarily the case for variable length arrays. However, it would be wasteful to do so, since constant array sizes are easily handled during compilation, and it is preferably for the necessary values (such as the amount of stack space to reserve when entering a function) to be calculated at compilation time rather than during execution. So we can expect that normal compilers resolve all constant array sizes during compilation (that is, before completing an object module for the translation unit) and conceptually after phase 6.

Additional identification of points within the translation process where array sizes are resolved is dependent on internal details of the compiler implementation (or of a C implementation generally).

Body:
This is more for clarity or a better understanding of the internal workings of compilers: I'm beginning to study compiler design and compiler theory.

Typically When declaring the size of an array on the stack it has to be known at compile-time and this is understood, but this is not always the case.

What I would like to know is; when does this evaluation occur? Does it happen during the precompiler, tokenizer, syntax analysis, etc.? Also, does it depend on the particular compiler that is being used? Finally, is the point in time of this evaluation specified to be at any particular stage of a compiler within the language standards?

Pseudo Code snippet. C or C++

int main() {
    int x[5]; // When does the evaluation of the 5 for the array's size take place
              // during the compilation process?
              // Does it take place during pre-compiler or normal compilation time.
    return 0;
}


问:
When I call "static void Example(int example)" and later on call "Example(Example);" The variable doesn't change
When I create a void method and assign private variables to it, it usually works fine. But for some reason when I use this script below the moveEnemy() wont work properly. Im trying to make it so when the enemies position is greater than the players, the enemies position will decrease.

If I directly reference a variable the script works but not when I use the private ones. EX: using posX += 1; makes the enemy move forwards. But using posX += speed doesnt do anything at all even though in the Main void im changing both of those variables to enemyPosX and enemySpeed. What is wrong with the code?

```<code>static void moveEnemy(double posX, double posY, char symbol, double speed, bool made, bool move)
        {
            if (made == false)
            {
                posX = generateNumber.Next(defaultLeftBorder + 1, defaultRightBorder - 1);
                posY = generateNumber.Next(defaultUpBorder + 1, defaultDownBorder - 1);
                made = true;
                move = true;
            }

            if (posX > playerPosX + 1)
            {
                if (move == true)
                {
                    posX -= speed;
                    move = false;
                }
            }
            if (posX < playerPosX + 1)
            {
                if (move == true)
                {
                    posX += speed;
                    move = false;
                }
            }
            if (posY > playerPosY)
            {
                if (move == true)
                {
                    posY -= speed;
                    move = false;
                }
            }
            if (posY < playerPosY)
            {
                if (move == true)
                {
                    posY += speed;
                    move = false;
                }
            }
            drawEnemy(posX, posY, symbol);
        }

        static void Main(string[] args)
        {
            start();

            while (true)
            {
                moveEnemy(enemyPosX, enemyPosY, enemyChar, enemySpeed, enemyMade, enemyMove);

                Thread.Sleep(60);
                Console.Clear();
                enemyMove = true;
            }
        }
</code>```

答:
When I call “static void Example(int example)” and later on call
  “Example(Example);” The variable doesn't change

Your title explains it.

Problem:

The below passes example by value. So whatever the lifecycle change in value of example within Example() method  is only limited within Example()'s scope. Anything outside of it will have the original value of example

static void Example(int example)

Solution:

Find it Here .

This will improve your understanding on the topic as well. You need to pass example buy reference. So that whatever changes you make to the value of example within Example(ref int example){ //Here } will change the actual value of example in memory.

Body:
When I create a void method and assign private variables to it, it usually works fine. But for some reason when I use this script below the moveEnemy() wont work properly. Im trying to make it so when the enemies position is greater than the players, the enemies position will decrease.

If I directly reference a variable the script works but not when I use the private ones. EX: using posX += 1; makes the enemy move forwards. But using posX += speed doesnt do anything at all even though in the Main void im changing both of those variables to enemyPosX and enemySpeed. What is wrong with the code?

static void moveEnemy(double posX, double posY, char symbol, double speed, bool made, bool move)
        {
            if (made == false)
            {
                posX = generateNumber.Next(defaultLeftBorder + 1, defaultRightBorder - 1);
                posY = generateNumber.Next(defaultUpBorder + 1, defaultDownBorder - 1);
                made = true;
                move = true;
            }

            if (posX > playerPosX + 1)
            {
                if (move == true)
                {
                    posX -= speed;
                    move = false;
                }
            }
            if (posX < playerPosX + 1)
            {
                if (move == true)
                {
                    posX += speed;
                    move = false;
                }
            }
            if (posY > playerPosY)
            {
                if (move == true)
                {
                    posY -= speed;
                    move = false;
                }
            }
            if (posY < playerPosY)
            {
                if (move == true)
                {
                    posY += speed;
                    move = false;
                }
            }
            drawEnemy(posX, posY, symbol);
        }

        static void Main(string[] args)
        {
            start();

            while (true)
            {
                moveEnemy(enemyPosX, enemyPosY, enemyChar, enemySpeed, enemyMade, enemyMove);

                Thread.Sleep(60);
                Console.Clear();
                enemyMove = true;
            }
        }


问:
How can I add a divisible function to this calculator program?
So below I have a calculator function. I have the addition, subtraction, and multiplication working just fine. The actual computation is not the issue here. (Note: the computation is in a different class all together). I simply need to figure out how to make the "/" symbol show up on the calculator gui when I launch it.</p>

```<code>import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

/* This is the GUI class that visualize the calculator
 *
 * */
public class Calculator extends Application {

    private MyStack stack = new MyStack();
    private double font_size = 30; //by default the font size on the screen is 30

    /*The keyboard key values*/
    private static final String[][] key_values = {
              { "0", "=", "c", "<" },
              { "1", "2", "3", "-" },
              { "4", "5", "6", "*" },
              { "7", "8", "9", "+" },
              { "/"}

          };
    private Button btn[][] = new Button[5][5]; //all the key buttons
    TextField calculator_screen;  //the calculator screen

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

      @Override public void start(Stage stage) {

         /*The outside layout*/
         final VBox layout = new VBox(30); //the size vertically

         /*The inside layout for keys or buttons*/
         TilePane keypad = new TilePane(); //even it is called keypad, it is a layout
         keypad.setVgap(7);
         keypad.setHgap(7); //set the gap between keys

        /*Create Calculator Screen */
        calculator_screen =  new TextField();
        calculator_screen.getStyleClass().add("screen1"); //set the style of the screen
        calculator_screen.setAlignment(Pos.CENTER_RIGHT); //make the screen in the center of the calculator
        calculator_screen.setEditable(false); //make sure the screen cannot be typed in manually
        calculator_screen.setPrefWidth(300); //set the width of the screen
        calculator_screen.setPrefHeight(30);
        calculator_screen.setFont(Font.font("Verdana", font_size));

        /*Create Calculator keyboard*/
        keypad.setPrefColumns(key_values[0].length); //set the preferred number of columns

        for (int i = 0; i < 4; i++) {
          for (int j = 0; j < 4; j++) {
            btn[i][j] = new Button(key_values[i][j]);
            final int a = i;
            final int b = j;

            /*Add button event*/
            btn[i][j].setOnAction(new EventHandler<ActionEvent>(){

                @Override
                public void handle(ActionEvent event) {

                    StackNode node = new StackNode(key_values[a][b]);

                    if(a == 0 && b == 2) //if the key is "c"
                    {
                        stack.clear();
                        calculator_screen.setFont(Font.font("Verdana", 30));
                        font_size = 30;
                    }
                    else if(a == 0 && b == 3) //if the key is "b"
                        stack.pop();
                    else if (a == 0 && b == 1) // if the key is "="
                    {
                        stack.computeExp();
                    }
                    else
                        stack.push(node); //otherwise push the key into the list

                    String math_exp = stack.getAllNodeValues();

                    if(math_exp.length() * font_size > 1.2 * calculator_screen.getPrefWidth())
                    {
                        font_size /= 1.2;
                        calculator_screen.setFont(Font.font("Verdana", font_size));

                    }

                    calculator_screen.setText(math_exp);

                }
            }
            );

            //Add special style for the "=" button
            if(a == 0 && b == 1)
                btn[i][j].getStyleClass().add("btnEqual");
            else if(a == 0 && b == 2)
                btn[i][j].getStyleClass().add("btnClear");
            else if(a == 0 && b == 3)
                btn[i][j].getStyleClass().add("btnBackspace");
            keypad.getChildren().add(btn[i][j]);

          }
        }

        /*Put the calculator screen and keypad into a VBox layout*/
        layout.setAlignment(Pos.CENTER);
        layout.getChildren().addAll(calculator_screen, keypad);
        layout.getStyleClass().add("vbox1");
        calculator_screen.prefWidthProperty().bind(keypad.widthProperty());

        /*Show the window*/
        stage.setTitle("Calculator");
        stage.initStyle(StageStyle.UTILITY);
        stage.setResizable(false);
        Scene scene = new Scene(layout);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());

        stage.setScene(scene);
        stage.show();

      }

}
</code>```

答:
I think your problem is only that you never go over the fifth column of your key_values array when creating your buttons in your for loop.

You should verify the length of each row and column while iterating to make sure you don

For example:

```<code>for (int i = 0; i < key_values.length; i++) {
      for (int j = 0; j < key_values[i].length; j++) {
        btn[i][j] = new Button(key_values[i][j]);
</code>```

Instead of :

```<code>for (int i = 0; i < 4; i++) {
      for (int j = 0; j < 4; j++) {
        btn[i][j] = new Button(key_values[i][j]);
</code>```

Body:
So below I have a calculator function. I have the addition, subtraction, and multiplication working just fine. The actual computation is not the issue here. (Note: the computation is in a different class all together). I simply need to figure out how to make the "/" symbol show up on the calculator gui when I launch it.

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

/* This is the GUI class that visualize the calculator
 *
 * */
public class Calculator extends Application {

    private MyStack stack = new MyStack();
    private double font_size = 30; //by default the font size on the screen is 30

    /*The keyboard key values*/
    private static final String[][] key_values = {
              { "0", "=", "c", "<" },
              { "1", "2", "3", "-" },
              { "4", "5", "6", "*" },
              { "7", "8", "9", "+" },
              { "/"}

          };
    private Button btn[][] = new Button[5][5]; //all the key buttons
    TextField calculator_screen;  //the calculator screen

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

      @Override public void start(Stage stage) {

         /*The outside layout*/
         final VBox layout = new VBox(30); //the size vertically

         /*The inside layout for keys or buttons*/
         TilePane keypad = new TilePane(); //even it is called keypad, it is a layout
         keypad.setVgap(7);
         keypad.setHgap(7); //set the gap between keys

        /*Create Calculator Screen */
        calculator_screen =  new TextField();
        calculator_screen.getStyleClass().add("screen1"); //set the style of the screen
        calculator_screen.setAlignment(Pos.CENTER_RIGHT); //make the screen in the center of the calculator
        calculator_screen.setEditable(false); //make sure the screen cannot be typed in manually
        calculator_screen.setPrefWidth(300); //set the width of the screen
        calculator_screen.setPrefHeight(30);
        calculator_screen.setFont(Font.font("Verdana", font_size));

        /*Create Calculator keyboard*/
        keypad.setPrefColumns(key_values[0].length); //set the preferred number of columns

        for (int i = 0; i < 4; i++) {
          for (int j = 0; j < 4; j++) {
            btn[i][j] = new Button(key_values[i][j]);
            final int a = i;
            final int b = j;

            /*Add button event*/
            btn[i][j].setOnAction(new EventHandler<ActionEvent>(){

                @Override
                public void handle(ActionEvent event) {

                    StackNode node = new StackNode(key_values[a][b]);

                    if(a == 0 && b == 2) //if the key is "c"
                    {
                        stack.clear();
                        calculator_screen.setFont(Font.font("Verdana", 30));
                        font_size = 30;
                    }
                    else if(a == 0 && b == 3) //if the key is "b"
                        stack.pop();
                    else if (a == 0 && b == 1) // if the key is "="
                    {
                        stack.computeExp();
                    }
                    else
                        stack.push(node); //otherwise push the key into the list

                    String math_exp = stack.getAllNodeValues();

                    if(math_exp.length() * font_size > 1.2 * calculator_screen.getPrefWidth())
                    {
                        font_size /= 1.2;
                        calculator_screen.setFont(Font.font("Verdana", font_size));

                    }

                    calculator_screen.setText(math_exp);

                }
            }
            );

            //Add special style for the "=" button
            if(a == 0 && b == 1)
                btn[i][j].getStyleClass().add("btnEqual");
            else if(a == 0 && b == 2)
                btn[i][j].getStyleClass().add("btnClear");
            else if(a == 0 && b == 3)
                btn[i][j].getStyleClass().add("btnBackspace");
            keypad.getChildren().add(btn[i][j]);

          }
        }

        /*Put the calculator screen and keypad into a VBox layout*/
        layout.setAlignment(Pos.CENTER);
        layout.getChildren().addAll(calculator_screen, keypad);
        layout.getStyleClass().add("vbox1");
        calculator_screen.prefWidthProperty().bind(keypad.widthProperty());

        /*Show the window*/
        stage.setTitle("Calculator");
        stage.initStyle(StageStyle.UTILITY);
        stage.setResizable(false);
        Scene scene = new Scene(layout);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());

        stage.setScene(scene);
        stage.show();

      }

}

Body:
I think your problem is only that you never go over the fifth column of your key_values array when creating your buttons in your for loop.

You should verify the length of each row and column while iterating to make sure you don

For example:

for (int i = 0; i < key_values.length; i++) {
      for (int j = 0; j < key_values[i].length; j++) {
        btn[i][j] = new Button(key_values[i][j]);

Instead of :

for (int i = 0; i < 4; i++) {
      for (int j = 0; j < 4; j++) {
        btn[i][j] = new Button(key_values[i][j]);