问:
Need help to optimize texture drawing on LibGDX, SpriteBatch
I'm converting my game Hold & Drag from Swift (SpriteKit) to Android using LibGDX, I created my 'SpriteKit' api a little clone of the official on Xcode.

I'm looking for optimizing the render of textures especially because I got FPS drop (45-60 /60 fps)
When I don't draw textures I got 60 (the maximum).

I hope you will help me as efficiently as possible!

```<code>@Override
public void draw() {
    if (texture == null)
        return;

    Gdx.gl.glEnable(GL20.GL_BLEND);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);

    spriteBatch.setTransformMatrix(getTransformMatrix());
    spriteBatch.begin();
    Color color = spriteBatch.getColor();
    color.a = getAlpha();
    spriteBatch.setColor(color);
    spriteBatch.draw(texture, -size.width / 2, -size.height / 2, size.width, size.height);
    spriteBatch.end();

    Gdx.gl.glDisable(GL20.GL_BLEND);
}
</code>```

```<code>public List<SKNode> getParents() {
    List<SKNode> parents = new ArrayList<>();
    if (parent != null) {
        parents.add(parent);
        parents.addAll(parent.getParents());
    }
    return parents;
}

public Matrix4 getTransformMatrix() {
    List<SKNode> nodes = getParents();
    Collections.reverse(nodes);
    nodes.add(this);

    Matrix4 transformMatrix = new Matrix4();
    transformMatrix.idt();
    for (SKNode node : nodes) {
        transformMatrix.translate(node.position.x + node.origin.x, node.position.y + node.origin.y, 0);
        transformMatrix.rotate(0, 0, 1, node.zRotation);
        transformMatrix.scale(node.xScale, node.yScale, 0);
        transformMatrix.translate(-node.origin.x, -node.origin.y, 0);
    }

    return transformMatrix;
}
</code>```

答:
It is slow to do things that cause the sprite batch to "flush", which means it has to issue a number of OpenGL commands and transfer vertex data, etc. A flush occurs when you call spriteBatch.end() but also occurs if you:

Draw something with a different texture instance than the last thing drawn

Change the projection or transform matrices

Enable/disable blending

So you want to organize so you are not triggering a flush on every object you draw. What is typically done is to begin the batch, and then each sprite is drawn at its particular location with one of the spriteBatch.draw() methods that includes all the parameters you want. Like this:

```<code>batch.setProjectionMatrix(camera.combined);
batch.begin();
for (GameObject obj : myGameObjects)
    obj.draw();
batch.end();

//And in your game object / sprite class
public void draw() {
    if (texture == null)
        return;
    spriteBatch.setColor(1f, 1f, 1f, getAlpha());
    spriteBatch.draw(texture, -size.width / 2, -size.height / 2, size.width, size.height);
}
</code>```

Note that the above assumes you are referring to the same sprite batch instance in every object.

Now, to make it behave more like SpriteKit (I'm assuming since I haven't used it), your objects each need a transform. But you don't want to be calling setTransformMatrix or you will trigger a flush. Instead you can use the Affine2 class instead of Matrix4. It functions just as well for holding transform data for a 2D object. Then you can use spriteBatch.draw(textureRegion, width, height, affine2Transform) to draw it without triggering a flush.

To avoid triggering flushes from using different texture instances, you should use a TextureAtlas and texture regions. You can read up on that in the LibGDX documentation on their wiki.

As an aside, when using SpriteBatch, you do not need to make OpenGL calls to enable and disable blending. That is handled internally by SpriteBatch. Call spriteBatch.enableBlending() instead.

Body:
I'm converting my game Hold & Drag from Swift (SpriteKit) to Android using LibGDX, I created my 'SpriteKit' api a little clone of the official on Xcode.

I'm looking for optimizing the render of textures especially because I got FPS drop (45-60 /60 fps)
When I don't draw textures I got 60 (the maximum).

I hope you will help me as efficiently as possible!

@Override
public void draw() {
    if (texture == null)
        return;

    Gdx.gl.glEnable(GL20.GL_BLEND);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);

    spriteBatch.setTransformMatrix(getTransformMatrix());
    spriteBatch.begin();
    Color color = spriteBatch.getColor();
    color.a = getAlpha();
    spriteBatch.setColor(color);
    spriteBatch.draw(texture, -size.width / 2, -size.height / 2, size.width, size.height);
    spriteBatch.end();

    Gdx.gl.glDisable(GL20.GL_BLEND);
}

public List<SKNode> getParents() {
    List<SKNode> parents = new ArrayList<>();
    if (parent != null) {
        parents.add(parent);
        parents.addAll(parent.getParents());
    }
    return parents;
}

public Matrix4 getTransformMatrix() {
    List<SKNode> nodes = getParents();
    Collections.reverse(nodes);
    nodes.add(this);

    Matrix4 transformMatrix = new Matrix4();
    transformMatrix.idt();
    for (SKNode node : nodes) {
        transformMatrix.translate(node.position.x + node.origin.x, node.position.y + node.origin.y, 0);
        transformMatrix.rotate(0, 0, 1, node.zRotation);
        transformMatrix.scale(node.xScale, node.yScale, 0);
        transformMatrix.translate(-node.origin.x, -node.origin.y, 0);
    }

    return transformMatrix;
}

Body:
It is slow to do things that cause the sprite batch to "flush", which means it has to issue a number of OpenGL commands and transfer vertex data, etc. A flush occurs when you call spriteBatch.end() but also occurs if you:

Draw something with a different texture instance than the last thing drawn

Change the projection or transform matrices

Enable/disable blending

So you want to organize so you are not triggering a flush on every object you draw. What is typically done is to begin the batch, and then each sprite is drawn at its particular location with one of the spriteBatch.draw() methods that includes all the parameters you want. Like this:

batch.setProjectionMatrix(camera.combined);
batch.begin();
for (GameObject obj : myGameObjects)
    obj.draw();
batch.end();

//And in your game object / sprite class
public void draw() {
    if (texture == null)
        return;
    spriteBatch.setColor(1f, 1f, 1f, getAlpha());
    spriteBatch.draw(texture, -size.width / 2, -size.height / 2, size.width, size.height);
}

Note that the above assumes you are referring to the same sprite batch instance in every object.

Now, to make it behave more like SpriteKit (I'm assuming since I haven't used it), your objects each need a transform. But you don't want to be calling setTransformMatrix or you will trigger a flush. Instead you can use the Affine2 class instead of Matrix4. It functions just as well for holding transform data for a 2D object. Then you can use spriteBatch.draw(textureRegion, width, height, affine2Transform) to draw it without triggering a flush.

To avoid triggering flushes from using different texture instances, you should use a TextureAtlas and texture regions. You can read up on that in the LibGDX documentation on their wiki.

As an aside, when using SpriteBatch, you do not need to make OpenGL calls to enable and disable blending. That is handled internally by SpriteBatch. Call spriteBatch.enableBlending() instead.


来源: stackexchange

问:
Data augmentation in training only with tensorflow
I want to do some random augmentation , only at train time.

I've combined the augmentation as part of the graph - which I think is kind of mistake since the same graph is used for testing also - and I don't want the test images to be augmented.

```<code>x = tf.placeholder(tf.float32, shape=[None, _IMAGE_SIZE * _IMAGE_SIZE * _IMAGE_CHANNELS], name='Input')
y = tf.placeholder(tf.float32, shape=[None, _NUM_CLASSES], name='Output')

#reshape the input so we can apply conv2d########
x_image = tf.reshape(x, [-1,32,32,3])

x_image = tf.map_fn(lambda frame: tf.random_crop(frame, [_IMAGE_SIZE, _IMAGE_SIZE, _IMAGE_CHANNELS]), x_image)
x_image = tf.map_fn(lambda frame: tf.image.random_flip_left_right(frame), x_image)
x_image = tf.map_fn(lambda frame: tf.image.random_brightness(frame, max_delta=63), x_image)
x_image = tf.map_fn(lambda frame: tf.image.random_contrast(frame, lower=0.2, upper=1.8), x_image)
x_image = tf.map_fn(lambda frame: tf.image.per_image_standardization(frame), x_image)
</code>```

I want the above augmentations to be applied only at test time - how can it be done ?

答:
The solution for this is quit simple

```<code>def pre_process_image(image, training):
if training:
    Do things
else:
    Do some other things
return image

def pre_process(images, training):
    images = tf.map_fn(lambda image: pre_process_image(image, training), images)
    return images
</code>```

Then call pre_process inside the model as I wanted

```<code>if is_training == True:
    with tf.variable_scope('augment', reuse=False):
        with tf.device('/cpu:0'):
            x_image = tf.reshape(x, [-1, _IMAGE_SIZE, _IMAGE_SIZE, _IMAGE_CHANNELS], name='images')
            x_image = pre_process(x_image, is_training)
else:

    with tf.variable_scope('augment', reuse=True):
        with tf.device('/cpu:0'):
            x_image = tf.reshape(x, [-1, _IMAGE_SIZE, _IMAGE_SIZE, _IMAGE_CHANNELS], name='images')
            x_image = pre_process(x_image, is_training)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to do some random augmentation , only at train time.

I've combined the augmentation as part of the graph - which I think is kind of mistake since the same graph is used for testing also - and I don't want the test images to be augmented.

x = tf.placeholder(tf.float32, shape=[None, _IMAGE_SIZE * _IMAGE_SIZE * _IMAGE_CHANNELS], name='Input')
y = tf.placeholder(tf.float32, shape=[None, _NUM_CLASSES], name='Output')

#reshape the input so we can apply conv2d########
x_image = tf.reshape(x, [-1,32,32,3])

x_image = tf.map_fn(lambda frame: tf.random_crop(frame, [_IMAGE_SIZE, _IMAGE_SIZE, _IMAGE_CHANNELS]), x_image)
x_image = tf.map_fn(lambda frame: tf.image.random_flip_left_right(frame), x_image)
x_image = tf.map_fn(lambda frame: tf.image.random_brightness(frame, max_delta=63), x_image)
x_image = tf.map_fn(lambda frame: tf.image.random_contrast(frame, lower=0.2, upper=1.8), x_image)
x_image = tf.map_fn(lambda frame: tf.image.per_image_standardization(frame), x_image)

I want the above augmentations to be applied only at test time - how can it be done ?

Body:
The solution for this is quit simple

def pre_process_image(image, training):
if training:
    Do things
else:
    Do some other things
return image

def pre_process(images, training):
    images = tf.map_fn(lambda image: pre_process_image(image, training), images)
    return images

Then call pre_process inside the model as I wanted

if is_training == True:
    with tf.variable_scope('augment', reuse=False):
        with tf.device('/cpu:0'):
            x_image = tf.reshape(x, [-1, _IMAGE_SIZE, _IMAGE_SIZE, _IMAGE_CHANNELS], name='images')
            x_image = pre_process(x_image, is_training)
else:

    with tf.variable_scope('augment', reuse=True):
        with tf.device('/cpu:0'):
            x_image = tf.reshape(x, [-1, _IMAGE_SIZE, _IMAGE_SIZE, _IMAGE_CHANNELS], name='images')
            x_image = pre_process(x_image, is_training)


问:
group a column by date with different formats
I have a dataset where one column has a date and time  values. Every date has multiple entries. The first row for every date has a date value inthe form 29MAY2018_00:00:00.000000 while the rest of the row for the same date has time values i.e. 20:00 - 21:00. The problem is that I want to sum the values in another column for each day.

The sample data has the following format

```<code>Date                       A
29MAY2018_00:00:00.000000
20:00 - 21:00              0.009
21:00 - 22:00              0.003
22:00 - 23:00              0.0003
23:00 - 00:00              0
30MAY2018_00:00:00.000000
00:00 - 01:00              -0.0016
01:00 - 02:00              -0.0012
02:00 - 03:00              -0.0002
03:00 - 04:00              -0.0023
04:00 - 05:00              0
05:00 - 06:00              -0.0005
20:00 - 21:00              -0.0042
21:00 - 22:00              -0.0035
22:00 - 23:00              -0.0026
23:00 - 00:00              -0.001
</code>```

I have created a new column

```<code>data$C[data$A ==0 ] <- 0
data$C[data$A < 0 ] <- -1
data$C[data$A > 0 ] <- 1
</code>```

I need to sum the column `C' for every date.
The output should be

```<code>A                    B
29-MAY-2019          4
30-MAY-2019         -9
31-MAY-2019          3
</code>```

答:
An option would be to create a grouping column based on the occurrence of full datetime format in the 'Date', summarise the first 'Date', convert it to Date format (with anydate from anytime) and get the sum of sign of 'A'

```<code>library(tidyverse)
library(anytime)
data %>%
    group_by(grp = cumsum(str_detect(Date, "[A-Z]"))) %>%
    summarise(Date = anydate(first(Date)),
               B = sum(sign(A), na.rm = TRUE))
</code>```

Body:
I have a dataset where one column has a date and time  values. Every date has multiple entries. The first row for every date has a date value inthe form 29MAY2018_00:00:00.000000 while the rest of the row for the same date has time values i.e. 20:00 - 21:00. The problem is that I want to sum the values in another column for each day.

The sample data has the following format

Date                       A
29MAY2018_00:00:00.000000
20:00 - 21:00              0.009
21:00 - 22:00              0.003
22:00 - 23:00              0.0003
23:00 - 00:00              0
30MAY2018_00:00:00.000000
00:00 - 01:00              -0.0016
01:00 - 02:00              -0.0012
02:00 - 03:00              -0.0002
03:00 - 04:00              -0.0023
04:00 - 05:00              0
05:00 - 06:00              -0.0005
20:00 - 21:00              -0.0042
21:00 - 22:00              -0.0035
22:00 - 23:00              -0.0026
23:00 - 00:00              -0.001

I have created a new column

data$C[data$A ==0 ] <- 0
data$C[data$A < 0 ] <- -1
data$C[data$A > 0 ] <- 1

I need to sum the column `C' for every date.
The output should be

A                    B
29-MAY-2019          4
30-MAY-2019         -9
31-MAY-2019          3

Body:
An option would be to create a grouping column based on the occurrence of full datetime format in the 'Date', summarise the first 'Date', convert it to Date format (with anydate from anytime) and get the sum of sign of 'A'

library(tidyverse)
library(anytime)
data %>%
    group_by(grp = cumsum(str_detect(Date, "[A-Z]"))) %>%
    summarise(Date = anydate(first(Date)),
               B = sum(sign(A), na.rm = TRUE))


问:
Adding `__getattr__` method to an existing object instance
I would like this to work:

import types

def new_getattr(self, *args, **kwargs):
    return 2

class A:
    def __init__(self):
        pass

a = A()
a.__getattr__ = types.MethodType(new_getattr, a)
print(a.anything)
```

Right now, it throws AttributeError: A instance has no attribute 'anything'.

I tried different solutions proposed here and they work, but not for __getattr__.

If I do print(a.__getattr__('anything')), it actually prints 2; the problem is that my __getattr__ method is not called automatically when I do a.anything.

As a side note, in my actual implementation, I cannot modify the definition of the class A, nor can I type its name and do something like A.__getattr__ = ... (which would work) because I need this to be generic and independent of the class name.

Edit: I ended up doing it like this:

a.__class__.__getattr__ = new_getattr.

答:
You can not - __dunder__ names are resolved on the type, not per-instance. Custom __getattr__ will need to be defined directly on A.

See Special method lookup section of the datamodel documentation, specifically:

For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.

Note: if you only have a reference to an instance, not the class, it is still possible to monkeypatch the type by assigning a method onto the object returned by type(a).  Be warned that this will affect all existing instances, not just the a instance.

Body:
I would like this to work:

import types

def new_getattr(self, *args, **kwargs):
    return 2

class A:
    def __init__(self):
        pass

a = A()
a.__getattr__ = types.MethodType(new_getattr, a)
print(a.anything)

Right now, it throws AttributeError: A instance has no attribute 'anything'.

I tried different solutions proposed here and they work, but not for __getattr__.

If I do print(a.__getattr__('anything')), it actually prints 2; the problem is that my __getattr__ method is not called automatically when I do a.anything.

As a side note, in my actual implementation, I cannot modify the definition of the class A, nor can I type its name and do something like A.__getattr__ = ... (which would work) because I need this to be generic and independent of the class name.

Edit: I ended up doing it like this:

a.__class__.__getattr__ = new_getattr.


问:
GitHub: invalid username or password
I have a project hosted on GitHub. I fail when trying to push my modifications on the master. I always get the following error message

```<code>Password for 'https://git@github.com':
remote: Invalid username or password.
fatal: Authentication failed for 'https://git@github.com/eurydyce/MDANSE.git/'
</code>```

However, setting my ssh key to github seems ok. Indeed, when I do a ssh -T git@github.com I get

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

Which seems to indicate that everything is OK from that side (eurydyce being my github username). I strictly followed the instructions given on github and the recommendations of many stack discussion but no way. Would you have any idea of what I may have done wrong?

答: I just disable the Two-factor authentication and try again. It works for me.</p>

ContentLicense: CC BY-SA 3.0

Title: GitHub: invalid username or password

Body:
I have a project hosted on GitHub. I fail when trying to push my modifications on the master. I always get the following error message

Password for 'https://git@github.com':
remote: Invalid username or password.
fatal: Authentication failed for 'https://git@github.com/eurydyce/MDANSE.git/'

However, setting my ssh key to github seems ok. Indeed, when I do a ssh -T git@github.com I get

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

Which seems to indicate that everything is OK from that side (eurydyce being my github username). I strictly followed the instructions given on github and the recommendations of many stack discussion but no way. Would you have any idea of what I may have done wrong?


问:
How do I get resource file values in Visual Basic?
I'm new to Visual Basic, and I'm having issues accessing the resource file for my project.

```<code>Dim rm As Resources.ResourceManager = New Resources.ResourceManager("MyProjectName.My.Resources.Resources", [Assembly].GetExecutingAssembly())
Dim myValue = rm.GetString(lookUpKey) 'boom Object reference not set to an instance of an object.
</code>```

I think the issue is with the string "MyProjectName.My.Resources.Resources".

Would I be better off moving the strings into their own resource file?

答:
Refer to the MSDN article Retrieving Resources with the ResourceManager Class for naming convetions:

```<code>Dim myManager As New _
   System.Resources.ResourceManager("ResourceNamespace.myResources", _
   myAssembly)
</code>```

Body:
I'm new to Visual Basic, and I'm having issues accessing the resource file for my project.

Dim rm As Resources.ResourceManager = New Resources.ResourceManager("MyProjectName.My.Resources.Resources", [Assembly].GetExecutingAssembly())
Dim myValue = rm.GetString(lookUpKey) 'boom Object reference not set to an instance of an object.

I think the issue is with the string "MyProjectName.My.Resources.Resources".

Would I be better off moving the strings into their own resource file?

Body:
Refer to the MSDN article Retrieving Resources with the ResourceManager Class for naming convetions:

Dim myManager As New _
   System.Resources.ResourceManager("ResourceNamespace.myResources", _
   myAssembly)


问:
CMake GTest fatal error (missing stdlib.h) when cross compiling

Set-up

I have the following files.

empty.cc:

```<code>#include <cstdlib>
</code>```

CMakeLists.txt:

```<code>set(CMAKE_MINIMUM_VERSION 3.8)

cmake_minimum_required(VERSION ${CMAKE_MINIMUM_VERSION})

find_package(GTest REQUIRED)

set(gtest_test gtest-test)
add_executable(${gtest_test} empty.cc)
#target_link_libraries(${gtest_test} ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES}) # Line A
target_link_libraries(${gtest_test} GTest::GTest GTest::Main) # Line B
</code>```

toolchain.cmake:

```<code>set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_VERSION 4.14.0)
set(CMAKE_SYSTEM_PROCESSOR arm)

set(CMAKE_C_COMPILER /opt/zynq/xtl/bin/arm-linux-musleabihf-gcc)
set(CMAKE_CXX_COMPILER /opt/zynq/xtl/bin/arm-linux-musleabihf-g++)

set(CMAKE_SYSROOT /opt/zynq/xtl/arm-linux-musleabihf)

set(CMAKE_FIND_ROOT_PATH /opt/zynq/xtl/arm-linux-musleabihf)

set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE NEVER)

set(CMAKE_INSTALL_PREFIX /opt/zynq/xtl/arm-linux-musleabihf)
</code>```

Problem

I build it using:

```<code>cmake -DCMAKE_TOOLCHAIN_FILE=../toolchain.cmake .. && make VERBOSE=1 -j
</code>```

When I link against GTest using Line A, i.e., target_link_libraries(${gtest_test} ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES}), then everything is OK. But when I use Line B, i.e., target_link_libraries(${gtest_test} GTest::GTest GTest::Main), then I've got the following error:

```<code>/opt/zynq/xtl/bin/arm-linux-musleabihf-g++ --sysroot=/opt/zynq/xtl/arm-linux-musleabihf   -isystem /opt/zynq/xtl/arm-linux-musleabihf/include   -o CMakeFiles/gtest-test.dir/empty.cc.o -c /home/xxx/git/cmake/cmake-with-gtest/empty.cc
In file included from /home/xxx/git/cmake/cmake-with-gtest/empty.cc:1:
/opt/zynq/xtl/arm-linux-musleabihf/include/c++/8.3.0/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
 #include_next <stdlib.h>
               ^~~~~~~~~~
compilation terminated.
CMakeFiles/gtest-test.dir/build.make:62: recipe for target
'CMakeFiles/gtest-test.dir/empty.cc.o' failed
make[2]: *** [CMakeFiles/gtest-test.dir/empty.cc.o] Error 1
</code>```

g++ version

```<code>...$ /opt/zynq/xtl/bin/arm-linux-musleabihf-g++ --version
arm-linux-musleabihf-g++ (GCC) 8.3.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

Normal build, i.e., not cross compiling, works fine using either

```<code>target_link_libraries(${gtest_test} ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES}) # Line A
</code>```

or

```<code>target_link_libraries(${gtest_test} GTest::GTest GTest::Main) # Line B
</code>```

Question

Why is it that using one way of linking results in a missing header and the other works just fine?

答:
It is known that using -isystem for standard compiler include directories breaks #include_next directive which is widely used for standard C++ header files. See e.g. this question: -isystem on a system include directory causes errors.

CMake has a mechanism for filtering out standard compiler include directories, which uses variable CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES as a list of include directories which are needed to be filtered out. Unfortunately, this list is not autodetected with a compiler (see that closed bugreport: https://gitlab.kitware.com/cmake/cmake/issues/16291). Instead, directory /usr/include (relative to sysroot) is just added to that list.

Because in your toolchain compiler include directory is not a /usr/include but /include one, you need to add this directory to the exception list explicitely:

```<code># in toolchain.cmake
list(APPEND CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES ${CMAKE_SYSROOT}/include)
# Setting the exclude directory for C compiler is optional:
# C standard headers rarely use `#include_next` directive
list(APPEND CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES ${CMAKE_SYSROOT}/include)
</code>```

Difference between

```<code>target_link_libraries(${gtest_test} ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES}) # Line A
</code>```

and

```<code>target_link_libraries(${gtest_test} GTest::GTest GTest::Main) # Line B
</code>```

is that the Line B uses targets names for link with, and include directories assosiated with that targets are automatically added to the your executable. That is why you got -isystem.

The second way  (Line B) is treated as "modern" one and is suggested to be used in newly written code. But both methods should work.

Body:
Set-up

I have the following files.

empty.cc:

#include <cstdlib>

CMakeLists.txt:

set(CMAKE_MINIMUM_VERSION 3.8)

cmake_minimum_required(VERSION ${CMAKE_MINIMUM_VERSION})

find_package(GTest REQUIRED)

set(gtest_test gtest-test)
add_executable(${gtest_test} empty.cc)
#target_link_libraries(${gtest_test} ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES}) # Line A
target_link_libraries(${gtest_test} GTest::GTest GTest::Main) # Line B

toolchain.cmake:

set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_VERSION 4.14.0)
set(CMAKE_SYSTEM_PROCESSOR arm)

set(CMAKE_C_COMPILER /opt/zynq/xtl/bin/arm-linux-musleabihf-gcc)
set(CMAKE_CXX_COMPILER /opt/zynq/xtl/bin/arm-linux-musleabihf-g++)

set(CMAKE_SYSROOT /opt/zynq/xtl/arm-linux-musleabihf)

set(CMAKE_FIND_ROOT_PATH /opt/zynq/xtl/arm-linux-musleabihf)

set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE NEVER)

set(CMAKE_INSTALL_PREFIX /opt/zynq/xtl/arm-linux-musleabihf)

Problem

I build it using:

cmake -DCMAKE_TOOLCHAIN_FILE=../toolchain.cmake .. && make VERBOSE=1 -j

When I link against GTest using Line A, i.e., target_link_libraries(${gtest_test} ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES}), then everything is OK. But when I use Line B, i.e., target_link_libraries(${gtest_test} GTest::GTest GTest::Main), then I've got the following error:

/opt/zynq/xtl/bin/arm-linux-musleabihf-g++ --sysroot=/opt/zynq/xtl/arm-linux-musleabihf   -isystem /opt/zynq/xtl/arm-linux-musleabihf/include   -o CMakeFiles/gtest-test.dir/empty.cc.o -c /home/xxx/git/cmake/cmake-with-gtest/empty.cc
In file included from /home/xxx/git/cmake/cmake-with-gtest/empty.cc:1:
/opt/zynq/xtl/arm-linux-musleabihf/include/c++/8.3.0/cstdlib:75:15: fatal error: stdlib.h: No such file or directory
 #include_next <stdlib.h>
               ^~~~~~~~~~
compilation terminated.
CMakeFiles/gtest-test.dir/build.make:62: recipe for target
'CMakeFiles/gtest-test.dir/empty.cc.o' failed
make[2]: *** [CMakeFiles/gtest-test.dir/empty.cc.o] Error 1

g++ version

...$ /opt/zynq/xtl/bin/arm-linux-musleabihf-g++ --version
arm-linux-musleabihf-g++ (GCC) 8.3.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Normal build, i.e., not cross compiling, works fine using either

target_link_libraries(${gtest_test} ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES}) # Line A

or

target_link_libraries(${gtest_test} GTest::GTest GTest::Main) # Line B

Question

Why is it that using one way of linking results in a missing header and the other works just fine?

Body:
It is known that using -isystem for standard compiler include directories breaks #include_next directive which is widely used for standard C++ header files. See e.g. this question: -isystem on a system include directory causes errors.

CMake has a mechanism for filtering out standard compiler include directories, which uses variable CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES as a list of include directories which are needed to be filtered out. Unfortunately, this list is not autodetected with a compiler (see that closed bugreport: https://gitlab.kitware.com/cmake/cmake/issues/16291). Instead, directory /usr/include (relative to sysroot) is just added to that list.

Because in your toolchain compiler include directory is not a /usr/include but /include one, you need to add this directory to the exception list explicitely:

# in toolchain.cmake
list(APPEND CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES ${CMAKE_SYSROOT}/include)
# Setting the exclude directory for C compiler is optional:
# C standard headers rarely use `#include_next` directive
list(APPEND CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES ${CMAKE_SYSROOT}/include)

Difference between

target_link_libraries(${gtest_test} ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES}) # Line A

and

target_link_libraries(${gtest_test} GTest::GTest GTest::Main) # Line B

is that the Line B uses targets names for link with, and include directories assosiated with that targets are automatically added to the your executable. That is why you got -isystem.

The second way  (Line B) is treated as "modern" one and is suggested to be used in newly written code. But both methods should work.


问:
for numbers outside range, short type casting gives overflow, but long type casting gives compile error?
```<code>/*Casting to short via (short)# gives overflow, but casting to long via (long)# gives compile error.  Am I missing something fundamental? (I'm a new student, still learning where educational resources are)
*/

//I'm working in Intellij IDEA.

short y = (short)198_203_304;

long t = (long)1_923_123_456_789_000;
// won't compile as number is outside long range

long u = 1_923_123_456_789_000L;
// use of #L casts to long, but I understand risk of data loss is
// present.

System.out.println("y = " + y);
System.out.println("u = " + u);

//... yields...

y = 20473
// Result of overflow, since 198_203_304 is out of range, I believe.
u = 1923123456789000
</code>```

<p>/*So my question is why wouldn't the use of long u = (long)#### result in overflow instead of compile error, as the situation with short did?
*/</p>

答:
```<code>short y = (short)198_203_304;
</code>```

198_203_304 is literal type int. You're in range for that. No compiler error!

```<code>long t = (long)1_923_123_456_789_000;
</code>```

1_923_123_456_789_000 is literal type int. You're out of range for that - compiler error!

```<code>long u = 1_923_123_456_789_000L;
</code>```

"1_923_123_456_789_000L" is literal type long. You're in range for that - no compiler error!

See here and the section "Integer Literals".

Body:
/*Casting to short via (short)# gives overflow, but casting to long via (long)# gives compile error.  Am I missing something fundamental? (I'm a new student, still learning where educational resources are)
*/

//I'm working in Intellij IDEA.

short y = (short)198_203_304;

long t = (long)1_923_123_456_789_000;
// won't compile as number is outside long range

long u = 1_923_123_456_789_000L;
// use of #L casts to long, but I understand risk of data loss is
// present.

System.out.println("y = " + y);
System.out.println("u = " + u);

//... yields...

y = 20473
// Result of overflow, since 198_203_304 is out of range, I believe.
u = 1923123456789000

/*So my question is why wouldn't the use of long u = (long)#### result in overflow instead of compile error, as the situation with short did?
*/

Body:
short y = (short)198_203_304;

198_203_304 is literal type int. You're in range for that. No compiler error!

long t = (long)1_923_123_456_789_000;

1_923_123_456_789_000 is literal type int. You're out of range for that - compiler error!

long u = 1_923_123_456_789_000L;

"1_923_123_456_789_000L" is literal type long. You're in range for that - no compiler error!

See here and the section "Integer Literals".


问:
How could this buffer be overrun?
I apologize in advance for the useless title of this question, but nothing seemed to fit better.

The idea here is to replicate argv in another variable, essentially making a copy of it. So the basic idea of what the function does is, use malloc() to request some space for a copy and then iterate through argv making copies of each element.

This is the code I'm working with, the development environment is right now Visual Studio 2019 (even if it's not strictly a C compiler...):

```<code>// Returns a copy of an array of strings (intended for argv, but should work with any of them):
wchar_t** copyArgv(size_t argc, wchar_t* argv[]) {
    // Allocate space for the array of arguments:
    wchar_t** argsCopy = malloc(((argc + 1) * sizeof(wchar_t*)));
    if (!argsCopy)
        return NULL;
    // Copy each one of them:
    for (size_t i = 0; i < argc; i++) {
        argsCopy[i] = _wcsdup(argv[i]);
        if (!argsCopy[i]) {
            // Should also free any previous copied string I left that part out in the paste.
            free(argsCopy);
            return NULL;
        }
    }
    argsCopy[argc] = NULL;
    return argsCopy;
}
</code>```

I've been trying different ways to make a copy of argv but each and everyone of them lets VS to believe there can be a buffer overrun when I make a copy of an argument (line:argsCopy[i] = _wcsdup(argv[i]);) or reading invalid data in the next line, meaning reading out of the bounds of the reserved space.

All of this has lead me to believe the problem lies in the (now) only malloc() call to reserve space for the array of arguments.

Yet I'm banging my head against the wall trying to figure out what the problem is, I mean, I think I'm asking for enough space.

I've tried other compilers as well, latest stable versions of Clang and GCC don't seem to show any such warning. So I decided to ask you, seasoned programmers, if you can spot the problem, or it's some sort of compiler bug (unlikely I bet).

For reference these are the exact warnings VS2019 is throwing (in a 64-bit compilation):

In the assignment:

Buffer overrun while writing to 'argsCopy':  the writable size is '((argc+1))*sizeof(wchar_t *)' bytes, but '16' bytes might be written.

Next line, the test for NULL:

Reading invalid data from 'argsCopy':  the readable size is '((argc+1))*sizeof(wchar_t *)' bytes, but '16' bytes may be read.

答:
1) One way to replicate argv is explained below but.,
2) I am unable to understand why you want to make a replica of argv? what use-case/user-problems does it solve?

as I mentioned in (1), here is one of the ways, which is essentially about copying all the contents that argv has into your buffer. It goes something like this (PS: there could be compilation erros as I"m typing in my phone while being in a taxi, so don't have access to a hi quality C compiler to cross check)

```<code>int numArgc = argc
char** argvCopy;

for (i=0;i<argc,i++)
{

 argvCopy[i] = malloc(sizeof(char)*strlen(argv[i]));
 strcpy(argvCopy[i], argv[i]);

}

//please do not forget to Free this malloc'ed memory (a very common C programming error) //when you don't need it anymore
</code>```

please do tell the problem that you want to solve

Title: How could this buffer be overrun?

Body:
I apologize in advance for the useless title of this question, but nothing seemed to fit better.

The idea here is to replicate argv in another variable, essentially making a copy of it. So the basic idea of what the function does is, use malloc() to request some space for a copy and then iterate through argv making copies of each element.

This is the code I'm working with, the development environment is right now Visual Studio 2019 (even if it's not strictly a C compiler...):

// Returns a copy of an array of strings (intended for argv, but should work with any of them):
wchar_t** copyArgv(size_t argc, wchar_t* argv[]) {
    // Allocate space for the array of arguments:
    wchar_t** argsCopy = malloc(((argc + 1) * sizeof(wchar_t*)));
    if (!argsCopy)
        return NULL;
    // Copy each one of them:
    for (size_t i = 0; i < argc; i++) {
        argsCopy[i] = _wcsdup(argv[i]);
        if (!argsCopy[i]) {
            // Should also free any previous copied string I left that part out in the paste.
            free(argsCopy);
            return NULL;
        }
    }
    argsCopy[argc] = NULL;
    return argsCopy;
}

I've been trying different ways to make a copy of argv but each and everyone of them lets VS to believe there can be a buffer overrun when I make a copy of an argument (line:argsCopy[i] = _wcsdup(argv[i]);) or reading invalid data in the next line, meaning reading out of the bounds of the reserved space.

All of this has lead me to believe the problem lies in the (now) only malloc() call to reserve space for the array of arguments.

Yet I'm banging my head against the wall trying to figure out what the problem is, I mean, I think I'm asking for enough space.

I've tried other compilers as well, latest stable versions of Clang and GCC don't seem to show any such warning. So I decided to ask you, seasoned programmers, if you can spot the problem, or it's some sort of compiler bug (unlikely I bet).

For reference these are the exact warnings VS2019 is throwing (in a 64-bit compilation):

In the assignment:

Buffer overrun while writing to 'argsCopy':  the writable size is '((argc+1))*sizeof(wchar_t *)' bytes, but '16' bytes might be written.

Next line, the test for NULL:

Reading invalid data from 'argsCopy':  the readable size is '((argc+1))*sizeof(wchar_t *)' bytes, but '16' bytes may be read.

Body:
1) One way to replicate argv is explained below but.,
2) I am unable to understand why you want to make a replica of argv? what use-case/user-problems does it solve?

as I mentioned in (1), here is one of the ways, which is essentially about copying all the contents that argv has into your buffer. It goes something like this (PS: there could be compilation erros as I"m typing in my phone while being in a taxi, so don't have access to a hi quality C compiler to cross check)

int numArgc = argc
char** argvCopy;

for (i=0;i<argc,i++)
{

 argvCopy[i] = malloc(sizeof(char)*strlen(argv[i]));
 strcpy(argvCopy[i], argv[i]);

}

//please do not forget to Free this malloc'ed memory (a very common C programming error) //when you don't need it anymore

please do tell the problem that you want to solve


问:
windows batch to split string on first occurrence of a delimiter
I have a parameter string read from a properties file. One of the properties is as below:

```<code>"CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080"
</code>```

I need to split this string on the first occurrence of "=" and set a parameter with the value:

```<code>-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
</code>```

I am trying to split the string first on the = token and then remove the fist sub-string token from the original string.
In the below code %%G will be set to "CUSTOM_JAVA_OPTIONS" and I am trying to remove this from the original string "TESTSTR"

```<code>@echo off

set "TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com
-Dhttp.proxyPort=8080"

SETLOCAL ENABLEDELAYEDEXPANSION

FOR /F "tokens=1,2 delims==" %%G IN ("%TESTSTR%") DO (

  echo Name=%%G
  echo Value=%%H
  set removestr=%%G

  echo TESTSTR=!TESTSTR!
  echo removestr=!removestr!

  set "str=!TESTSTR:%removestr%=!"
  echo str=!str!
  )
pause
</code>```

The above does not seem to work, it produces:

```<code>Name=CUSTOM_JAVA_OPTIONS
Value=-Dhttp.proxyHost
TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
removestr=CUSTOM_JAVA_OPTIONS
str=TESTSTR:=
</code>```

Expected result needs to be:

```<code> str=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
</code>```

答:
Your code fails entirely because %removestr% is expanded when the command is initially parsed, and your entire loop (code block) is parsed all at once. So %removestr% expands to the value that existed before your loop was entered. In your case, the variable is undefined. So !TESTSTR:%removestr%=! becomes !TESTSTR:=!, which finally becomes TESTSTR:=.

You get closer if you use %%G directly, instead of assigning an environment variable.

set str=!TESTSTR:%%G=! yields =-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080

You can then use set str=!str:~1!" to remove the leading =.

set str=!TESTSTR:%%G==! will not work because the search strings stops at the first occurrence of =, so the result is ==-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080

The RGuggisberg answer is the most convenient method to get your desired result. (You may want both %%G and %%H).

However, it technically does not break at the first =. It actually breaks at the first string of contiguous = because FOR /F does not parse empty tokens.

So for /f "tokens=1* delims==" %%G in ("A==B==C") yields A for %%G (correct), and B==C (incorrect) for %%H. The correct value should be =B==C.

Body:
I have a parameter string read from a properties file. One of the properties is as below:

"CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080"

I need to split this string on the first occurrence of "=" and set a parameter with the value:

-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080

I am trying to split the string first on the = token and then remove the fist sub-string token from the original string.
In the below code %%G will be set to "CUSTOM_JAVA_OPTIONS" and I am trying to remove this from the original string "TESTSTR"

@echo off

set "TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com
-Dhttp.proxyPort=8080"

SETLOCAL ENABLEDELAYEDEXPANSION

FOR /F "tokens=1,2 delims==" %%G IN ("%TESTSTR%") DO (

  echo Name=%%G
  echo Value=%%H
  set removestr=%%G

  echo TESTSTR=!TESTSTR!
  echo removestr=!removestr!

  set "str=!TESTSTR:%removestr%=!"
  echo str=!str!
  )
pause

The above does not seem to work, it produces:

Name=CUSTOM_JAVA_OPTIONS
Value=-Dhttp.proxyHost
TESTSTR=CUSTOM_JAVA_OPTIONS=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080
removestr=CUSTOM_JAVA_OPTIONS
str=TESTSTR:=

Expected result needs to be:

 str=-Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080


问:
chrome and firefox browser fails to launch windows folder from link
I have a link that directs to a windows folder by its directory link. It works for internet explorer, but it doesn't work for chrome or firefox. How do i fix this?

my link goes something like this

```<code><a href="\\directory\folder1\folder2">Click Here</a>
</code>```

It works in internet explorer but it doesnt work for chrome? and it doesn't work in firefox either?

答:
try

```<code><a href="file:///c:/directory/folder1/folder2" target="_new" >Click here</a>
</code>```

also is this only being used by you because the chances of us both having the same folder structure is slim to none.

Body:
I have a link that directs to a windows folder by its directory link. It works for internet explorer, but it doesn't work for chrome or firefox. How do i fix this?

my link goes something like this

Click Here

It works in internet explorer but it doesnt work for chrome? and it doesn't work in firefox either?

Body:
try

<a href="file:///c:/directory/folder1/folder2" target="_new" >Click here</a>

also is this only being used by you because the chances of us both having the same folder structure is slim to none.


问:
Error executing API while fetching folder list
I am creating logicapp to retrieve attachment from Email and copy it to SFTP folder. While Setting up connection to SFTP folder, when I try to select a folder then I get error as in the screenshot

logic app error

Another user in my company can connect to the SFTP folder using filezilla. However, I am getting an error even with FileZilla. We have confirmed that whitelist of IPs is not enabled and ports are no blocked anywhere.

Any idea how to trouble-shoot this issue? Thanks in advance

harry

答: When you create the api-connection for the SFTP server, have you tried with 'Disable SSH Host Key Validation' turned on? If not try it. You can update the api-connection from the Azure portal. </p>


问:
How to sort a list nested inside another list?
I have lists nested inside an outer list. I want to sort the elements in inner lists without changing the position of the elements(lists in this case) in outer list. How to do it?

I am getting space separated user input which I later convert to nested lists where each inner list contain the digits of the number separated from each other. All I want is to get the inner lists in sorted form

```<code>num = list(map(str, input().split()))
n_list = []
for i in range(len(num)):
    num_in_num = [int(j) for j in num[i]]
    n_list.append(num_in_num)
print(n_list)
</code>```

for this given input:

```<code>5654 3456 7215 7612 5463
</code>```

I get the list as:

```<code>[[5, 6, 5, 4], [3, 4, 5, 6], [7, 2, 1, 5], [7, 6, 1, 2], [5, 4, 6, 3]]
</code>```

I want the output to be like:

```<code>[[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]
</code>```

How to get this output?

答:
You can use map for this:

```<code>n_list = list(map(sorted, n_list))
</code>```

or directly:

```<code>n_list = list(map(lambda n:sorted(map(int,n)), input().split())
</code>```

Body:
I have lists nested inside an outer list. I want to sort the elements in inner lists without changing the position of the elements(lists in this case) in outer list. How to do it?

I am getting space separated user input which I later convert to nested lists where each inner list contain the digits of the number separated from each other. All I want is to get the inner lists in sorted form

num = list(map(str, input().split()))
n_list = []
for i in range(len(num)):
    num_in_num = [int(j) for j in num[i]]
    n_list.append(num_in_num)
print(n_list)

for this given input:

5654 3456 7215 7612 5463

I get the list as:

[[5, 6, 5, 4], [3, 4, 5, 6], [7, 2, 1, 5], [7, 6, 1, 2], [5, 4, 6, 3]]

I want the output to be like:

[[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]

How to get this output?

Body:
You can use map for this:

n_list = list(map(sorted, n_list))

or directly:

n_list = list(map(lambda n:sorted(map(int,n)), input().split())


问:
Using atan2 to find angle between two vectors
I understand that:

atan2(vector.y, vector.x) = the angle between the vector and the X axis.

But I wanted to know how to get the angle between two vectors using atan2. So I came across this solution:

```<code>atan2(vector1.y - vector2.y, vector1.x - vector2.x)
</code>```

My question is very simple:

Will the two following formulas produce the same number?

atan2(vector1.y - vector2.y, vector1.x - vector2.x)

atan2(vector2.y - vector1.y, vector2.x - vector1.x)

If not: How do I know what vector comes first in the subtractions?

答:
Here a little program in Python that uses the angle between vectors to determine if a point is inside or outside a certain polygon</p>

```<code>import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from shapely.geometry import Point, Polygon
from pprint import pprint

# Plot variables
x_min, x_max = -6, 12
y_min, y_max = -3, 8
tick_interval = 1
FIG_SIZE = (10, 10)
DELTA_ERROR = 0.00001
IN_BOX_COLOR = 'yellow'
OUT_BOX_COLOR = 'black'

def angle_between(v1, v2):
    """ Returns the angle in radians between vectors 'v1' and 'v2'
        The sign of the angle is dependent on the order of v1 and v2
        so acos(norm(dot(v1, v2))) does not work and atan2 has to be used, see:
        https://stackoverflow.com/questions/21483999/using-atan2-to-find-angle-between-two-vectors
    """
    arg1 = np.cross(v1, v2)
    arg2 = np.dot(v1, v2)
    angle = np.arctan2(arg1, arg2)
    return angle

def point_inside(point, border):
    """ Returns True if point is inside border polygon and False if not
        Arguments:
        :point: x, y in shapely.geometry.Point type
        :border: [x1 y1, x2 y2, ... , xn yn] in shapely.geomettry.Polygon type
    """
    assert len(border.exterior.coords) > 2,\
        'number of points in the polygon must be > 2'

    point = np.array(point)
    side1 = np.array(border.exterior.coords[0]) - point
    sum_angles = 0
    for border_point in border.exterior.coords[1:]:
        side2 = np.array(border_point) - point
        angle = angle_between(side1, side2)
        sum_angles += angle
        side1 = side2

    # if wn is 1 then the point is inside
    wn = sum_angles / 2 / np.pi
    if abs(wn - 1) < DELTA_ERROR:
        return True
    else:
        return False

class MainMap():

    @classmethod
    def settings(cls, fig_size):
        # set the plot outline, including axes going through the origin
        cls.fig, cls.ax = plt.subplots(figsize=fig_size)
        cls.ax.set_xlim(-x_min, x_max)
        cls.ax.set_ylim(-y_min, y_max)
        cls.ax.set_aspect(1)
        tick_range_x = np.arange(round(x_min + (10*(x_max - x_min) % tick_interval)/10, 1),
            x_max + 0.1, step=tick_interval)
        tick_range_y = np.arange(round(y_min + (10*(y_max - y_min) % tick_interval)/10, 1),
            y_max + 0.1, step=tick_interval)
        cls.ax.set_xticks(tick_range_x)
        cls.ax.set_yticks(tick_range_y)
        cls.ax.tick_params(axis='both', which='major', labelsize=6)
        cls.ax.spines['left'].set_position('zero')
        cls.ax.spines['right'].set_color('none')
        cls.ax.spines['bottom'].set_position('zero')
        cls.ax.spines['top'].set_color('none')

    @classmethod
    def get_ax(cls):
        return cls.ax

    @staticmethod
    def plot():
        plt.tight_layout()
        plt.show()

class PlotPointandRectangle(MainMap):

    def __init__(self, start_point, rectangle_polygon, tolerance=0):

        self.current_object = None
        self.currently_dragging = False
        self.fig.canvas.mpl_connect('key_press_event', self.on_key)
        self.plot_types = ['o', 'o-']
        self.plot_type = 1
        self.rectangle = rectangle_polygon

        # define a point that can be moved around
        self.point = patches.Circle((start_point.x, start_point.y), 0.10,
            alpha=1)
        if point_inside(start_point, self.rectangle):
            _color = IN_BOX_COLOR
        else:
            _color = OUT_BOX_COLOR
        self.point.set_color(_color)
        self.ax.add_patch(self.point)
        self.point.set_picker(tolerance)
        cv_point = self.point.figure.canvas
        cv_point.mpl_connect('button_release_event', self.on_release)
        cv_point.mpl_connect('pick_event', self.on_pick)
        cv_point.mpl_connect('motion_notify_event', self.on_motion)

        self.plot_rectangle()

    def plot_rectangle(self):
        x = [point[0] for point in self.rectangle.exterior.coords]
        y = [point[1] for point in self.rectangle.exterior.coords]
        # y = self.rectangle.y
        self.rectangle_plot, = self.ax.plot(x, y,
            self.plot_types[self.plot_type], color='r', lw=0.4, markersize=2)

    def on_release(self, event):
        self.current_object = None
        self.currently_dragging = False

    def on_pick(self, event):
        self.currently_dragging = True
        self.current_object = event.artist

    def on_motion(self, event):
        if not self.currently_dragging:
            return
        if self.current_object == None:
            return

        point = Point(event.xdata, event.ydata)
        self.current_object.center = point.x, point.y
        if point_inside(point, self.rectangle):
            _color = IN_BOX_COLOR
        else:
            _color = OUT_BOX_COLOR
        self.current_object.set_color(_color)

        self.point.figure.canvas.draw()

    def remove_rectangle_from_plot(self):
        try:
            self.rectangle_plot.remove()
        except ValueError:
            pass

    def on_key(self, event):
        # with 'space' toggle between just points or points connected with
        # lines
        if event.key == ' ':
            self.plot_type = (self.plot_type + 1) % 2
            self.remove_rectangle_from_plot()
            self.plot_rectangle()
            self.point.figure.canvas.draw()

def main(start_point, rectangle):

    MainMap.settings(FIG_SIZE)
    plt_me = PlotPointandRectangle(start_point, rectangle)  #pylint: disable=unused-variable
    MainMap.plot()

if __name__ == "__main__":
    try:
        start_point = Point([float(val) for val in sys.argv[1].split()])
    except IndexError:
        start_point= Point(0, 0)

    border_points = [(-2, -2),
                     (1, 1),
                     (3, -1),
                     (3, 3.5),
                     (4, 1),
                     (5, 1),
                     (4, 3.5),
                     (5, 6),
                     (3, 4),
                     (3, 5),
                     (-0.5, 1),
                     (-3, 1),
                     (-1, -0.5),
                    ]

    border_points_polygon = Polygon(border_points)
    main(start_point, border_points_polygon)
</code>```

Body:
I understand that:

atan2(vector.y, vector.x) = the angle between the vector and the X axis.

But I wanted to know how to get the angle between two vectors using atan2. So I came across this solution:

atan2(vector1.y - vector2.y, vector1.x - vector2.x)

My question is very simple:

Will the two following formulas produce the same number?

atan2(vector1.y - vector2.y, vector1.x - vector2.x)

atan2(vector2.y - vector1.y, vector2.x - vector1.x)

If not: How do I know what vector comes first in the subtractions?

Body:
Here a little program in Python that uses the angle between vectors to determine if a point is inside or outside a certain polygon

import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from shapely.geometry import Point, Polygon
from pprint import pprint

# Plot variables
x_min, x_max = -6, 12
y_min, y_max = -3, 8
tick_interval = 1
FIG_SIZE = (10, 10)
DELTA_ERROR = 0.00001
IN_BOX_COLOR = 'yellow'
OUT_BOX_COLOR = 'black'

def angle_between(v1, v2):
    """ Returns the angle in radians between vectors 'v1' and 'v2'
        The sign of the angle is dependent on the order of v1 and v2
        so acos(norm(dot(v1, v2))) does not work and atan2 has to be used, see:
        https://stackoverflow.com/questions/21483999/using-atan2-to-find-angle-between-two-vectors
    """
    arg1 = np.cross(v1, v2)
    arg2 = np.dot(v1, v2)
    angle = np.arctan2(arg1, arg2)
    return angle

def point_inside(point, border):
    """ Returns True if point is inside border polygon and False if not
        Arguments:
        :point: x, y in shapely.geometry.Point type
        :border: [x1 y1, x2 y2, ... , xn yn] in shapely.geomettry.Polygon type
    """
    assert len(border.exterior.coords) > 2,\
        'number of points in the polygon must be > 2'

    point = np.array(point)
    side1 = np.array(border.exterior.coords[0]) - point
    sum_angles = 0
    for border_point in border.exterior.coords[1:]:
        side2 = np.array(border_point) - point
        angle = angle_between(side1, side2)
        sum_angles += angle
        side1 = side2

    # if wn is 1 then the point is inside
    wn = sum_angles / 2 / np.pi
    if abs(wn - 1) < DELTA_ERROR:
        return True
    else:
        return False

class MainMap():

    @classmethod
    def settings(cls, fig_size):
        # set the plot outline, including axes going through the origin
        cls.fig, cls.ax = plt.subplots(figsize=fig_size)
        cls.ax.set_xlim(-x_min, x_max)
        cls.ax.set_ylim(-y_min, y_max)
        cls.ax.set_aspect(1)
        tick_range_x = np.arange(round(x_min + (10*(x_max - x_min) % tick_interval)/10, 1),
            x_max + 0.1, step=tick_interval)
        tick_range_y = np.arange(round(y_min + (10*(y_max - y_min) % tick_interval)/10, 1),
            y_max + 0.1, step=tick_interval)
        cls.ax.set_xticks(tick_range_x)
        cls.ax.set_yticks(tick_range_y)
        cls.ax.tick_params(axis='both', which='major', labelsize=6)
        cls.ax.spines['left'].set_position('zero')
        cls.ax.spines['right'].set_color('none')
        cls.ax.spines['bottom'].set_position('zero')
        cls.ax.spines['top'].set_color('none')

    @classmethod
    def get_ax(cls):
        return cls.ax

    @staticmethod
    def plot():
        plt.tight_layout()
        plt.show()

class PlotPointandRectangle(MainMap):

    def __init__(self, start_point, rectangle_polygon, tolerance=0):

        self.current_object = None
        self.currently_dragging = False
        self.fig.canvas.mpl_connect('key_press_event', self.on_key)
        self.plot_types = ['o', 'o-']
        self.plot_type = 1
        self.rectangle = rectangle_polygon

        # define a point that can be moved around
        self.point = patches.Circle((start_point.x, start_point.y), 0.10,
            alpha=1)
        if point_inside(start_point, self.rectangle):
            _color = IN_BOX_COLOR
        else:
            _color = OUT_BOX_COLOR
        self.point.set_color(_color)
        self.ax.add_patch(self.point)
        self.point.set_picker(tolerance)
        cv_point = self.point.figure.canvas
        cv_point.mpl_connect('button_release_event', self.on_release)
        cv_point.mpl_connect('pick_event', self.on_pick)
        cv_point.mpl_connect('motion_notify_event', self.on_motion)

        self.plot_rectangle()

    def plot_rectangle(self):
        x = [point[0] for point in self.rectangle.exterior.coords]
        y = [point[1] for point in self.rectangle.exterior.coords]
        # y = self.rectangle.y
        self.rectangle_plot, = self.ax.plot(x, y,
            self.plot_types[self.plot_type], color='r', lw=0.4, markersize=2)

    def on_release(self, event):
        self.current_object = None
        self.currently_dragging = False

    def on_pick(self, event):
        self.currently_dragging = True
        self.current_object = event.artist

    def on_motion(self, event):
        if not self.currently_dragging:
            return
        if self.current_object == None:
            return

        point = Point(event.xdata, event.ydata)
        self.current_object.center = point.x, point.y
        if point_inside(point, self.rectangle):
            _color = IN_BOX_COLOR
        else:
            _color = OUT_BOX_COLOR
        self.current_object.set_color(_color)

        self.point.figure.canvas.draw()

    def remove_rectangle_from_plot(self):
        try:
            self.rectangle_plot.remove()
        except ValueError:
            pass

    def on_key(self, event):
        # with 'space' toggle between just points or points connected with
        # lines
        if event.key == ' ':
            self.plot_type = (self.plot_type + 1) % 2
            self.remove_rectangle_from_plot()
            self.plot_rectangle()
            self.point.figure.canvas.draw()

def main(start_point, rectangle):

    MainMap.settings(FIG_SIZE)
    plt_me = PlotPointandRectangle(start_point, rectangle)  #pylint: disable=unused-variable
    MainMap.plot()

if __name__ == "__main__":
    try:
        start_point = Point([float(val) for val in sys.argv[1].split()])
    except IndexError:
        start_point= Point(0, 0)

    border_points = [(-2, -2),
                     (1, 1),
                     (3, -1),
                     (3, 3.5),
                     (4, 1),
                     (5, 1),
                     (4, 3.5),
                     (5, 6),
                     (3, 4),
                     (3, 5),
                     (-0.5, 1),
                     (-3, 1),
                     (-1, -0.5),
                    ]

    border_points_polygon = Polygon(border_points)
    main(start_point, border_points_polygon)


问:
Type punning and malloc'ed memory
I originally asked this question: Type Punning with Unions and Heap

And not wanting the question to keep evolving to the point that anyone reading in the future had no idea what the original question was, I have a spin off question.

After reading this site:
https://kristerw.blogspot.com/2016/05/type-based-aliasing-in-c.html

Near the bottom it talks about malloc'd memory. Is it safe to say that casting from one pointer type to another pointer type is safe when memory is on the heap?

Example:

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

struct test1
{
    int a;
    char b;
};

struct test2
{
    int c;
    char d;
};

void printer(const struct test2* value);

int main()
{
    struct test1* aQuickTest = malloc(sizeof(struct test1));
    aQuickTest->a = 42;
    aQuickTest->b = 'a';
    printer((struct test2*)aQuickTest); //safe because memory was malloc'd???
    return 0;
}

void printer(const struct test2* value)
{
    printf("Int: %i Char: %c",value->c, value->d);
}
</code>```

And guessing it might not be safe. What would be the proper way to do this with memcpy? I will attempt to write an example with a function of what might hopefully work?

```<code>struct test2* converter(struct test1* original);

int main()
{
    struct test1* aQuickTest = malloc(sizeof(struct test1));
    aQuickTest->a = 42;
    aQuickTest->b = 'a';
    struct test2* newStruct = converter(aQuickTest);
    printer(newStruct);
    return 0;
}

struct test2* converter(struct test1* original)
{
    struct test2* temp;
    memcpy(&temp, &original, sizeof(struct test2));
    return temp;
}
</code>```

答:
```<code>void *pnt = malloc(sizeof(struct test1));
</code>```

What type has the memory behind pnt pointer? No type. It is uninitialized (it's value is "indeterminate"). There is just "memory".

Then you do:

```<code>struct test1* aQuickTest = malloc(sizeof(struct test1));
</code>```

You only cast the pointer. Nothing happens here. No assembly is generated. Reading uninitialized memory is undefined behavior tho, so you can't read from aQuickTest->a (yet). But you can assign:

```<code>aQuickTest->a = 1;
</code>```

This writes to an object struct test1 in the memory. This is assignment. You can now read aQuickTest->a, ie. print it.

But the following

```<code>printf("%d", ((struct test2*)aQuickTest)->a);
</code>```

is undefined behavior (although it will/should work). You access the underlying object (ie. struct test1) using a not matching pointer type struct test2*. This is called "strict alias violation". Dereferencing an object (ie. doing -> or *) using a handle of not compatible type results in undefined behavior. It does not matter that struct test1 and struct test2 "look the same". They are different type. The rule is in C11 standard 6.5p7.

In the first code snipped undefined behavior happens on inside printf("Int: %i Char: %c",value->c. The access value-> accesses the underlying memory using incompatible handle.

In the second code snipped the variable temp is only a pointer. Also original is a pointer. Doing memcpy(&temp, &original, sizeof(struct test2)); is invalid, because &temp writes into the temp pointer and &original writes into the original pointer. No to the memory behind pointers. As you write out of bounds into&temppointer and read of bounds from&originalpointer (because most probablysizeof(temp) < sizeof(struct test2)andsizeof(original) < sizeof(struct test2)`), undefined behavior happens.

Anyway even if it were:

```<code>    struct test1* original = &(some valid struct test1 object).
    struct test2 temp;
    memcpy(&temp, original, sizeof(struct test2));
    printf("%d", temp.a); // undefined behavior
</code>```

accessing the memory behind temp variable is still invalid. As the original didn't had struct test2 object, it is still invalid. memcpy doesn't change the type of the object in memory.

Title: Type punning and malloc'ed memory

Body:
I originally asked this question: Type Punning with Unions and Heap

And not wanting the question to keep evolving to the point that anyone reading in the future had no idea what the original question was, I have a spin off question.

After reading this site:
https://kristerw.blogspot.com/2016/05/type-based-aliasing-in-c.html

Near the bottom it talks about malloc'd memory. Is it safe to say that casting from one pointer type to another pointer type is safe when memory is on the heap?

Example:

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

struct test1
{
    int a;
    char b;
};

struct test2
{
    int c;
    char d;
};

void printer(const struct test2* value);

int main()
{
    struct test1* aQuickTest = malloc(sizeof(struct test1));
    aQuickTest->a = 42;
    aQuickTest->b = 'a';
    printer((struct test2*)aQuickTest); //safe because memory was malloc'd???
    return 0;
}

void printer(const struct test2* value)
{
    printf("Int: %i Char: %c",value->c, value->d);
}

And guessing it might not be safe. What would be the proper way to do this with memcpy? I will attempt to write an example with a function of what might hopefully work?

struct test2* converter(struct test1* original);

int main()
{
    struct test1* aQuickTest = malloc(sizeof(struct test1));
    aQuickTest->a = 42;
    aQuickTest->b = 'a';
    struct test2* newStruct = converter(aQuickTest);
    printer(newStruct);
    return 0;
}

struct test2* converter(struct test1* original)
{
    struct test2* temp;
    memcpy(&temp, &original, sizeof(struct test2));
    return temp;
}

Body:
void *pnt = malloc(sizeof(struct test1));

What type has the memory behind pnt pointer? No type. It is uninitialized (it's value is "indeterminate"). There is just "memory".

Then you do:

struct test1* aQuickTest = malloc(sizeof(struct test1));

You only cast the pointer. Nothing happens here. No assembly is generated. Reading uninitialized memory is undefined behavior tho, so you can't read from aQuickTest->a (yet). But you can assign:

aQuickTest->a = 1;

This writes to an object struct test1 in the memory. This is assignment. You can now read aQuickTest->a, ie. print it.

But the following

printf("%d", ((struct test2*)aQuickTest)->a);

is undefined behavior (although it will/should work). You access the underlying object (ie. struct test1) using a not matching pointer type struct test2*. This is called "strict alias violation". Dereferencing an object (ie. doing -> or *) using a handle of not compatible type results in undefined behavior. It does not matter that struct test1 and struct test2 "look the same". They are different type. The rule is in C11 standard 6.5p7.

In the first code snipped undefined behavior happens on inside printf("Int: %i Char: %c",value->c. The access value-> accesses the underlying memory using incompatible handle.

In the second code snipped the variable temp is only a pointer. Also original is a pointer. Doing memcpy(&temp, &original, sizeof(struct test2)); is invalid, because &temp writes into the temp pointer and &original writes into the original pointer. No to the memory behind pointers. As you write out of bounds into&temppointer and read of bounds from&originalpointer (because most probablysizeof(temp) < sizeof(struct test2)andsizeof(original) < sizeof(struct test2)`), undefined behavior happens.

Anyway even if it were:

    struct test1* original = &(some valid struct test1 object).
    struct test2 temp;
    memcpy(&temp, original, sizeof(struct test2));
    printf("%d", temp.a); // undefined behavior

accessing the memory behind temp variable is still invalid. As the original didn't had struct test2 object, it is still invalid. memcpy doesn't change the type of the object in memory.


问:
Compare date stored as an integer with a datetime
I have a column having datatype integer which is in the format yyyymm (e.g. 201905). I want to check if this column is in between start and end date i.e.:

```<code>case
  when [cov_yyyymm] between [start_dt] and [end_dt] then 'Period1'
  else 'OtherPeriod'
end
</code>```

note: start and end dates are datetime

I have tried converting the Int to datetime/date. similarly vice versa from date to int and still could not get it to work.

I expect to use a CASE statement to compare if the Integer is in between 2 dates.

答:
You can convert it to datetime like so:

```<code>SELECT CAST(CAST(201905 AS VARCHAR(6)) + '01' AS DATETIME)
</code>```

And compare with datetime columns like so:

```<code>WHERE CAST(CAST(201905 AS VARCHAR(6)) + '01' AS DATETIME) BETWEEN start_dt AND end_dt
</code>```

Body:
I have a column having datatype integer which is in the format yyyymm (e.g. 201905). I want to check if this column is in between start and end date i.e.:

case
  when [cov_yyyymm] between [start_dt] and [end_dt] then 'Period1'
  else 'OtherPeriod'
end

note: start and end dates are datetime

I have tried converting the Int to datetime/date. similarly vice versa from date to int and still could not get it to work.

I expect to use a CASE statement to compare if the Integer is in between 2 dates.

Body:
You can convert it to datetime like so:

SELECT CAST(CAST(201905 AS VARCHAR(6)) + '01' AS DATETIME)

And compare with datetime columns like so:

WHERE CAST(CAST(201905 AS VARCHAR(6)) + '01' AS DATETIME) BETWEEN start_dt AND end_dt


问:
How can I return the nth regex match in a string?
Working in PL/SQL.

I've got the following string

```<code>('Jade Court','Sarah M.', 4, '08/17/2017')
</code>```

I need to write a regex that can parse each item in between the ' characters.  So for example, I need Jade Court, Sarah M., 08/17/2017 etc.

So far, I have come up with the following regex:

```<code>(?<=')[^']+(?=')
</code>```

As you can see from the demo below, this works so far by finding each of the necessary items at the same time.

https://regex101.com/r/CV8evw/1

However, I need to be able to parse them out individually.  Is there a way to add a quantifier to my regex so that I can specify which match I want?

I tried (?<=')[^']+(?='){1} which I was hoping would return Jade Court, but unfortunately that did not work.  Is this possible?

答:
you can try this regex :

```<code>/\w{2,}\/?\s?\w*(\/\d{4})?/g
</code>```

just visual test using javascript

const x = "('Jade Court','Sarah M.', 4, '08/17/2017')"

const regex = /\w{2,}\/?\s?\w*(\/\d{4})?/g

console.log(x.match(regex))```

Body:
Working in PL/SQL.

I've got the following string

('Jade Court','Sarah M.', 4, '08/17/2017')

I need to write a regex that can parse each item in between the ' characters.  So for example, I need Jade Court, Sarah M., 08/17/2017 etc.

So far, I have come up with the following regex:

(?<=')[^']+(?=')

As you can see from the demo below, this works so far by finding each of the necessary items at the same time.

https://regex101.com/r/CV8evw/1

However, I need to be able to parse them out individually.  Is there a way to add a quantifier to my regex so that I can specify which match I want?

I tried (?<=')[^']+(?='){1} which I was hoping would return Jade Court, but unfortunately that did not work.  Is this possible?

Body:
you can try this regex :

/\w{2,}\/?\s?\w*(\/\d{4})?/g

just visual test using javascript

const x = "('Jade Court','Sarah M.', 4, '08/17/2017')"

const regex = /\w{2,}\/?\s?\w*(\/\d{4})?/g

console.log(x.match(regex))


问:
Hibernate and Spring Boot MalformedParameterizedTypeException: null while initializing bean (org.apache.commons.dbcp2.BasicDataSource)
I have Spring 1.5.21.RELEASE spring boot project and I am not able to initialize the Spring Boot Datasoruce org.apache.commons.dbcp2.BasicDataSource.  When application start-up I get the following exception.  I have tried and try to debug but I am not able to figure which incompatibility causing this issue.  I am using Java 8.

```<code> Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Dbcp2.class]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
        ... 211 common frames omitted
    Caused by: java.lang.reflect.MalformedParameterizedTypeException: null
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.validateConstructorArguments(ParameterizedTypeImpl.java:58)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.<init>(ParameterizedTypeImpl.java:51)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.make(ParameterizedTypeImpl.java:92)
        at sun.reflect.generics.factory.CoreReflectionFactory.makeParameterizedType(CoreReflectionFactory.java:105)
        at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:140)
        at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
        at sun.reflect.generics.repository.ConstructorRepository.getParameterTypes(ConstructorRepository.java:94)
        at java.lang.reflect.Executable.getGenericParameterTypes(Executable.java:283)
        at java.lang.reflect.Method.getGenericParameterTypes(Method.java:283)
        at java.lang.reflect.Executable.getAllGenericParameterTypes(Executable.java:302)
        at java.lang.reflect.Executable.getAnnotatedParameterTypes(Executable.java:693)
        at java.lang.reflect.Parameter.getAnnotatedType(Parameter.java:237)
        at org.hibernate.validator.internal.metadata.provider.TypeAnnotationAwareMetaDataProvider.findTypeAnnotationConstraintsForExecutableParameter(TypeAnnotationAwareMetaDataProvider.java:85)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getParameterMetaData(AnnotationMetaDataProvider.java:498)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.findExecutableMetaData(AnnotationMetaDataProvider.java:347)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getMetaData(AnnotationMetaDataProvider.java:332)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getMethodMetaData(AnnotationMetaDataProvider.java:318)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.retrieveBeanConfiguration(AnnotationMetaDataProvider.java:138)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getBeanConfiguration(AnnotationMetaDataProvider.java:125)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getBeanConfigurationForHierarchy(AnnotationMetaDataProvider.java:108)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.createBeanMetaData(BeanMetaDataManager.java:203)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.getOrCreateBeanMetaData(BeanMetaDataManager.java:231)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.getBeanMetaData(BeanMetaDataManager.java:178)
        at org.hibernate.validator.internal.engine.ValidatorImpl.getConstraintsForClass(ValidatorImpl.java:327)
        at org.springframework.validation.beanvalidation.SpringValidatorAdapter.getConstraintsForClass(SpringValidatorAdapter.java:304)
        at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor$ValidatedLocalValidatorFactoryBean.supports(ConfigurationPropertiesBindingPostProcessor.java:429)
        at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.determineValidator(ConfigurationPropertiesBindingPostProcessor.java:355)
        at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(ConfigurationPropertiesBindingPostProcessor.java:316)
        at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(ConfigurationPropertiesBindingPostProcessor.java:297)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:407)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1622)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
</code>```

Here is spring lib list :

```<code>camel-spring-2.17.7.jar
camel-spring-boot-2.17.7.jar
camel-spring-boot-starter-2.17.7.jar
camel-spring-redis-2.17.7.jar
shiro-spring-1.2.3.jar
spring-aop-4.3.24.RELEASE.jar
spring-aspects-4.3.24.RELEASE.jar
spring-beans-4.3.24.RELEASE.jar
spring-boot-1.5.21.RELEASE.jar
spring-boot-autoconfigure-1.5.21.RELEASE.jar
spring-boot-starter-1.5.21.RELEASE.jar
spring-boot-starter-aop-1.5.21.RELEASE.jar
spring-boot-starter-data-jpa-1.5.21.RELEASE.jar
spring-boot-starter-jdbc-1.5.21.RELEASE.jar
spring-boot-starter-logging-1.5.21.RELEASE.jar
spring-boot-starter-tomcat-1.5.21.RELEASE.jar
spring-boot-starter-web-1.5.21.RELEASE.jar
spring-context-4.3.24.RELEASE.jar
spring-context-support-4.3.24.RELEASE.jar
spring-core-4.3.24.RELEASE.jar
spring-data-commons-1.13.22.RELEASE.jar
spring-data-jpa-1.11.22.RELEASE.jar
spring-data-keyvalue-1.2.22.RELEASE.jar
spring-data-redis-1.8.22.RELEASE.jar
spring-expression-4.3.24.RELEASE.jar
spring-jdbc-4.3.24.RELEASE.jar
spring-orm-4.3.24.RELEASE.jar
spring-oxm-4.3.24.RELEASE.jar
spring-security-config-4.2.12.RELEASE.jar
spring-security-core-4.2.12.RELEASE.jar
spring-security-web-4.2.12.RELEASE.jar
spring-test-4.3.24.RELEASE.jar
spring-tx-4.3.24.RELEASE.jar
spring-web-4.3.24.RELEASE.jar
spring-webmvc-4.3.24.RELEASE.jar
</code>```

Here is hiberate Lib:

```<code>hibernate-commons-annotations-5.0.4.Final.jar
hibernate-core-5.3.10.Final.jar
hibernate-entitymanager-5.3.10.Final.jar
hibernate-types-52-1.0.0.jar
hibernate-validator-5.3.6.Final.jar
</code>```

答:
I had to use a newer version of commons-pool2 from 2.5.4 to 2.6.2.</p>

```<code><!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.6.2</version>
</dependency>
</code>```

Body:
I have Spring 1.5.21.RELEASE spring boot project and I am not able to initialize the Spring Boot Datasoruce org.apache.commons.dbcp2.BasicDataSource.  When application start-up I get the following exception.  I have tried and try to debug but I am not able to figure which incompatibility causing this issue.  I am using Java 8.

 Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Dbcp2.class]: Initialization of bean failed; nested exception is java.lang.reflect.MalformedParameterizedTypeException
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
        ... 211 common frames omitted
    Caused by: java.lang.reflect.MalformedParameterizedTypeException: null
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.validateConstructorArguments(ParameterizedTypeImpl.java:58)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.<init>(ParameterizedTypeImpl.java:51)
        at sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl.make(ParameterizedTypeImpl.java:92)
        at sun.reflect.generics.factory.CoreReflectionFactory.makeParameterizedType(CoreReflectionFactory.java:105)
        at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:140)
        at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
        at sun.reflect.generics.repository.ConstructorRepository.getParameterTypes(ConstructorRepository.java:94)
        at java.lang.reflect.Executable.getGenericParameterTypes(Executable.java:283)
        at java.lang.reflect.Method.getGenericParameterTypes(Method.java:283)
        at java.lang.reflect.Executable.getAllGenericParameterTypes(Executable.java:302)
        at java.lang.reflect.Executable.getAnnotatedParameterTypes(Executable.java:693)
        at java.lang.reflect.Parameter.getAnnotatedType(Parameter.java:237)
        at org.hibernate.validator.internal.metadata.provider.TypeAnnotationAwareMetaDataProvider.findTypeAnnotationConstraintsForExecutableParameter(TypeAnnotationAwareMetaDataProvider.java:85)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getParameterMetaData(AnnotationMetaDataProvider.java:498)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.findExecutableMetaData(AnnotationMetaDataProvider.java:347)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getMetaData(AnnotationMetaDataProvider.java:332)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getMethodMetaData(AnnotationMetaDataProvider.java:318)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.retrieveBeanConfiguration(AnnotationMetaDataProvider.java:138)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getBeanConfiguration(AnnotationMetaDataProvider.java:125)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getBeanConfigurationForHierarchy(AnnotationMetaDataProvider.java:108)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.createBeanMetaData(BeanMetaDataManager.java:203)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.getOrCreateBeanMetaData(BeanMetaDataManager.java:231)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.getBeanMetaData(BeanMetaDataManager.java:178)
        at org.hibernate.validator.internal.engine.ValidatorImpl.getConstraintsForClass(ValidatorImpl.java:327)
        at org.springframework.validation.beanvalidation.SpringValidatorAdapter.getConstraintsForClass(SpringValidatorAdapter.java:304)
        at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor$ValidatedLocalValidatorFactoryBean.supports(ConfigurationPropertiesBindingPostProcessor.java:429)
        at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.determineValidator(ConfigurationPropertiesBindingPostProcessor.java:355)
        at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(ConfigurationPropertiesBindingPostProcessor.java:316)
        at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(ConfigurationPropertiesBindingPostProcessor.java:297)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:407)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1622)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)

Here is spring lib list :

camel-spring-2.17.7.jar
camel-spring-boot-2.17.7.jar
camel-spring-boot-starter-2.17.7.jar
camel-spring-redis-2.17.7.jar
shiro-spring-1.2.3.jar
spring-aop-4.3.24.RELEASE.jar
spring-aspects-4.3.24.RELEASE.jar
spring-beans-4.3.24.RELEASE.jar
spring-boot-1.5.21.RELEASE.jar
spring-boot-autoconfigure-1.5.21.RELEASE.jar
spring-boot-starter-1.5.21.RELEASE.jar
spring-boot-starter-aop-1.5.21.RELEASE.jar
spring-boot-starter-data-jpa-1.5.21.RELEASE.jar
spring-boot-starter-jdbc-1.5.21.RELEASE.jar
spring-boot-starter-logging-1.5.21.RELEASE.jar
spring-boot-starter-tomcat-1.5.21.RELEASE.jar
spring-boot-starter-web-1.5.21.RELEASE.jar
spring-context-4.3.24.RELEASE.jar
spring-context-support-4.3.24.RELEASE.jar
spring-core-4.3.24.RELEASE.jar
spring-data-commons-1.13.22.RELEASE.jar
spring-data-jpa-1.11.22.RELEASE.jar
spring-data-keyvalue-1.2.22.RELEASE.jar
spring-data-redis-1.8.22.RELEASE.jar
spring-expression-4.3.24.RELEASE.jar
spring-jdbc-4.3.24.RELEASE.jar
spring-orm-4.3.24.RELEASE.jar
spring-oxm-4.3.24.RELEASE.jar
spring-security-config-4.2.12.RELEASE.jar
spring-security-core-4.2.12.RELEASE.jar
spring-security-web-4.2.12.RELEASE.jar
spring-test-4.3.24.RELEASE.jar
spring-tx-4.3.24.RELEASE.jar
spring-web-4.3.24.RELEASE.jar
spring-webmvc-4.3.24.RELEASE.jar

Here is hiberate Lib:

hibernate-commons-annotations-5.0.4.Final.jar
hibernate-core-5.3.10.Final.jar
hibernate-entitymanager-5.3.10.Final.jar
hibernate-types-52-1.0.0.jar
hibernate-validator-5.3.6.Final.jar

Body:
I had to use a newer version of commons-pool2 from 2.5.4 to 2.6.2.

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.6.2</version>
</dependency>


问:
How do I use external python packages in this configuration
I can not figure out how to import and/or use a python package. I really need some help getting off the ground with this. I want to accomplish getting 1 smoke test working. I'm now working in Windows 10 1809 os.

I've set up Eclipse to use Robotframework and RED robot. I have a project created with a folder, suite, and working test case (which does not include any Python). I've tried importing our "GoDirect" package, but when running the test shows that library has warning about no keywords. So, I'm assuming I have to create an external python.py file, and I tried to get one working but could not figure out how to set that up in the Eclipse Environment and use it.

My goal is to get a test case working that connects to a sensor, and reads information from it. I currently have no results other than a working skeleton test case. I'm new to Eclipse, but have "some" experience working with RobotFramework in the SikuliX IDE for a different application (using Mac Mojave).

This is my working Test case:

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

Suite Setup
Log    I am inside Test Suite Setup

Suite Teardown
Log    I am inside Test suite Teardown

Test Setup
Log    I am inside Test Setup

Test Teardown
Log    I am insied Test Teardown

Default Tags        sanity

*** Test Cases ***

gdx_smoke_test

    [Tags]    smoke
    Log    Hello World...

*** Variables ***

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

Below is a "pip list" of what I have installed on my Windows 10 1809 os:

Package                         Version

enum-compat                     0.0.2

godirect                        1.0.3

hidapi                          0.7.99.post21
pexpect                         4.7.0

pip                             19.1.1

ptyprocess                      0.6.0

pyserial                        3.4

robotframework                  3.1.1

robotframework-selenium2library 3.0.0

robotframework-seleniumlibrary  3.3.1

selenium                        3.141.0

setuptools                      41.0.1

urllib3                         1.25.3

vernierpygatt                   3.2.0

wheel                           0.33.4

Below is the website we use for students and teachers to download and use our "godirect" python implementations

https://www.vernier.com/engineering/python/

05/30/2019 : I'm working on an external python file that creates a class object with a few "def" functions in it. I'm thinking I can put that .py someplace in the Eclipse project folder and import it (as a library) into RobotFramework. In theory I should be able to call Keywords into that .py class object. Example of the possible .py:

05/31/2019 : OK guys. I solved it on my own. I mislead myself a lot on our website. There was a few things I ended up doing to solve it. I'll explain below for anyone that's interested.

1) Copied gdx.py to site folder: It turns out I can't just do "pip install godirect[usb,ble]" alone. This only installs the site package in a folder that the Robotframework and RED.xml will use. I needed to also download one of their files that had a "gdx.py" file in it. That file has keywords in it such as "open_usb(self)" and many other ones. So I copied that "gdx.py" file to the site folder.

2) Add gdx.py to RED.xml : Double clicked the RED.xml which opens the RED project Referenced Libraries window. and added the gdx.py Library.

3) Added the "Library gdx" in the Settings of Robot Framework

4) Added keyword "open  usb": In my gdx_smoke_test I added this keyword to it

5) Ran the test suite and it passed!

The passing smoke test for using a custom Python file is below (shows changes I made to the original above)

```<code>*** Settings ***
Library  gdx
Suite Setup
Log    I am inside Test Suite Setup

Suite Teardown
Log    I am inside Test suite Teardown

Test Setup
Log    I am inside Test Setup

Test Teardown
Log    I am insied Test Teardown

Default Tags        sanity

*** Test Cases ***

gdx_smoke_test

    [Tags]    smoke
    Log    Hello World...
    open . usb

*** Variables ***

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

答: OK, solved it myself. I made changes to the original post showing what I did to solve it. </p>

Body:
I can not figure out how to import and/or use a python package. I really need some help getting off the ground with this. I want to accomplish getting 1 smoke test working. I'm now working in Windows 10 1809 os.

I've set up Eclipse to use Robotframework and RED robot. I have a project created with a folder, suite, and working test case (which does not include any Python). I've tried importing our "GoDirect" package, but when running the test shows that library has warning about no keywords. So, I'm assuming I have to create an external python.py file, and I tried to get one working but could not figure out how to set that up in the Eclipse Environment and use it.

My goal is to get a test case working that connects to a sensor, and reads information from it. I currently have no results other than a working skeleton test case. I'm new to Eclipse, but have "some" experience working with RobotFramework in the SikuliX IDE for a different application (using Mac Mojave).

This is my working Test case:

*** Settings ***

Suite Setup
Log    I am inside Test Suite Setup

Suite Teardown
Log    I am inside Test suite Teardown

Test Setup
Log    I am inside Test Setup

Test Teardown
Log    I am insied Test Teardown

Default Tags        sanity

*** Test Cases ***

gdx_smoke_test

    [Tags]    smoke
    Log    Hello World...

*** Variables ***

*** Keywords ***

Below is a "pip list" of what I have installed on my Windows 10 1809 os:

Package                         Version

enum-compat                     0.0.2

godirect                        1.0.3

hidapi                          0.7.99.post21
pexpect                         4.7.0

pip                             19.1.1

ptyprocess                      0.6.0

pyserial                        3.4

robotframework                  3.1.1

robotframework-selenium2library 3.0.0

robotframework-seleniumlibrary  3.3.1

selenium                        3.141.0

setuptools                      41.0.1

urllib3                         1.25.3

vernierpygatt                   3.2.0

wheel                           0.33.4

Below is the website we use for students and teachers to download and use our "godirect" python implementations

https://www.vernier.com/engineering/python/

05/30/2019 : I'm working on an external python file that creates a class object with a few "def" functions in it. I'm thinking I can put that .py someplace in the Eclipse project folder and import it (as a library) into RobotFramework. In theory I should be able to call Keywords into that .py class object. Example of the possible .py:

05/31/2019 : OK guys. I solved it on my own. I mislead myself a lot on our website. There was a few things I ended up doing to solve it. I'll explain below for anyone that's interested.

1) Copied gdx.py to site folder: It turns out I can't just do "pip install godirect[usb,ble]" alone. This only installs the site package in a folder that the Robotframework and RED.xml will use. I needed to also download one of their files that had a "gdx.py" file in it. That file has keywords in it such as "open_usb(self)" and many other ones. So I copied that "gdx.py" file to the site folder.

2) Add gdx.py to RED.xml : Double clicked the RED.xml which opens the RED project Referenced Libraries window. and added the gdx.py Library.

3) Added the "Library gdx" in the Settings of Robot Framework

4) Added keyword "open  usb": In my gdx_smoke_test I added this keyword to it

5) Ran the test suite and it passed!

The passing smoke test for using a custom Python file is below (shows changes I made to the original above)

*** Settings ***
Library  gdx
Suite Setup
Log    I am inside Test Suite Setup

Suite Teardown
Log    I am inside Test suite Teardown

Test Setup
Log    I am inside Test Setup

Test Teardown
Log    I am insied Test Teardown

Default Tags        sanity

*** Test Cases ***

gdx_smoke_test

    [Tags]    smoke
    Log    Hello World...
    open . usb

*** Variables ***

*** Keywords ***


答:
Try a list comprehension where you map your strings to integers and then sort them using sorted

```<code>num = ['5654', '3456', '7215', '7612', '5463']
answer = [sorted(map(int, i)) for i in num]
# [[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]
</code>```

Title: How to sort a list nested inside another list?

Body:
Try a list comprehension where you map your strings to integers and then sort them using sorted

num = ['5654', '3456', '7215', '7612', '5463']
answer = [sorted(map(int, i)) for i in num]
# [[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]