问:
Setting an environment variable for maven-driven integration tests
Is is possible to set an environment variable from within a Citrus Framework integration test? I am asking because my services use log4j to log console output and the configuration file (log4j2-spring.xml) uses environment variables to set log file names, etc. It would be convenient to be able to do this.</p>

答:
It turns out this was not so much a question of how to do this in the Citrus Framework, but rather with setting up the environment variables for maven integration tests.

I was able to set the environment variables I needed for the integration test(s) run via maven by adding the following to the spring-boot-maven-plugin configuration:

```<code>  <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
      ...
      <environmentVariables>
        <env-var-name>env var value</env-var-name>
        ...
      </environmentVariables>
    </configuration>
    ...
  </plugin>
</code>```

Once the appropriate variables are set, test console output is logged where directed by configuration in log4j2-test.xml, located in src/test/resources.

See issue Citrus Framework logging - how to enable/use.

Body:
It turns out this was not so much a question of how to do this in the Citrus Framework, but rather with setting up the environment variables for maven integration tests.

I was able to set the environment variables I needed for the integration test(s) run via maven by adding the following to the spring-boot-maven-plugin configuration:

  <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
      ...
      <environmentVariables>
        <env-var-name>env var value</env-var-name>
        ...
      </environmentVariables>
    </configuration>
    ...
  </plugin>

Once the appropriate variables are set, test console output is logged where directed by configuration in log4j2-test.xml, located in src/test/resources.

See issue Citrus Framework logging - how to enable/use.


来源: stackexchange

问:
Type for intersection of all return types with list of functions
Say I have an array of functions like so:

```<code>const foo: Array< () => object > = [
    () => ({ one: 'fish' }),
    () => ({ two: 'fish' }),
    () => ({ red: 'fish' }),
    () => ({ blue: 'fish' })
]
</code>```

Is it possible to write a type that will intersection the return types of all these functions?

```<code>{
  one: string,
  two: string,
  red: string,
  blue: string,
}
</code>```

Basically, the type for what would result if you reduced all these functions into a single result.

答:
Interesting problem. This can be done using a combination of mapped types and conditional types; we need to:

Get rid of the type annotation Array<() => object> so that the array's actual contents can be used to construct a type,

Get the function types from the array type,

Get the return types of those function types,

That gives a union like {one: string} | {two: string} | {red: string} | {blue: string} so we need to be able to get the property names (keyof doesn't work on a union like this),

Get the value type associated with a given property name in the union,

And finally, construct the result as a mapping from those property names to those value types.

Here's an implementation:

const foo = [
    () => ({ one: 'fish' }),
    () => ({ two: 'fish' }),
    () => ({ red: 'fish' }),
    () => ({ blue: 'fish' })
];

type ComponentType = A extends (infer U)[] ? U : never

type ReturnsUnion = ReturnType<ComponentType<typeof foo>>
// {one: string} | {two: string} | {red: string} | {blue: string}

type KeyOfUnion<T> = T extends infer U ? keyof U : never
// KeyOfUnion<ReturnsUnion> = 'one' | 'two' | 'red' | 'blue'

type ValueInUnion<T, K extends PropertyKey> = T extends { [k in K]: infer V } ? V : never

type Result = { [K in KeyOfUnion<ReturnsUnion>]: ValueInUnion<ReturnsUnion, K> }
// { one: string, two: string, red: string, blue: string }
```

Playground Link

ContentLicense: CC BY-SA 4.0

Body:
Say I have an array of functions like so:

const foo: Array< () => object > = [
    () => ({ one: 'fish' }),
    () => ({ two: 'fish' }),
    () => ({ red: 'fish' }),
    () => ({ blue: 'fish' })
]

Is it possible to write a type that will intersection the return types of all these functions?

{
  one: string,
  two: string,
  red: string,
  blue: string,
}

Basically, the type for what would result if you reduced all these functions into a single result.

Body:
Interesting problem. This can be done using a combination of mapped types and conditional types; we need to:

Get rid of the type annotation Array<() => object> so that the array's actual contents can be used to construct a type,

Get the function types from the array type,

Get the return types of those function types,

That gives a union like {one: string} | {two: string} | {red: string} | {blue: string} so we need to be able to get the property names (keyof doesn't work on a union like this),

Get the value type associated with a given property name in the union,

And finally, construct the result as a mapping from those property names to those value types.

Here's an implementation:

const foo = [
    () => ({ one: 'fish' }),
    () => ({ two: 'fish' }),
    () => ({ red: 'fish' }),
    () => ({ blue: 'fish' })
];

type ComponentType<A extends any[]> = A extends (infer U)[] ? U : never

type ReturnsUnion = ReturnType<ComponentType<typeof foo>>
// {one: string} | {two: string} | {red: string} | {blue: string}

type KeyOfUnion<T> = T extends infer U ? keyof U : never
// KeyOfUnion<ReturnsUnion> = 'one' | 'two' | 'red' | 'blue'

type ValueInUnion<T, K extends PropertyKey> = T extends { [k in K]: infer V } ? V : never

type Result = { [K in KeyOfUnion<ReturnsUnion>]: ValueInUnion<ReturnsUnion, K> }
// { one: string, two: string, red: string, blue: string }

<a href="http://www.typescriptlang.org/play/#code/MYewdgzgLgBAZiEMC8MDaBYAUDXMAUAlCgHwEDeM4ApgFwwDkcAlhABYMwC+hANNngLFkZfJSgB3EPSasO3PgLxFSFGACdqAExkt2nHvxzLhoygCMANgFc6jPfJ7YAugG5s2KAE8ADtRgAwiAAtj40YFAAKr7UADwAgjDUAB5Q1GBaEDAAhmBeaM5kqIkpaRlZ+MxgcNTqMACqhAUwAPwNMPRg1AButR5Y3n4wAErUUNbqkPVgzOAoI2MTYNF+sUGh4VExsYPUIHDwiCQk2AD0pzDkNPTQ6lUA5lwwAD6XktIwtw9Pr+SaOp8oHcwI8XpcrLYbkDvv1djAANLULwAeTg01mYFikSKMEiSVS6UyMCqNTq9VaMAA1kj9u1Oj0+lhzgikaj0eBYqNxpMIOywDiGDROK8GO9hYx-uKGBDqAxYTEYAA1bI2agASTAfKxvAR+LKRIACuoQH51N5EV4cXjSoSspQ0JTiWAEc56CTakruBTFR0YF1eup5UNRhBrJZYKh7fCnSyUWiZhyuUteQn+a6lSrbBqtUmeXydfCyFwzhdKNdAcD7jr3lDKzr-rWHjqZY2QdxsEA" rel="noreferrer">Playground Link


问:
MSAL (Java) Rest API Authentication ( Authorization : Bearer Token )
I'd like to secure a Java Rest API against Azure AD B2C.

I understand that the caller is calling the service using the Authorization header with a value like: Bearer xxx-token

Is that an ID or Access Token ?

What are the steps the service should take to ensure this is a valid token? Java code using MSAL4J would be greatly appreciated.

答:
MSAL4J is for acquiring tokens so clients can access protected resources, not for validating tokens in your API.

Your API should be receiving an access token in the authorization header. This article explains what claims might be included in the access token and how to validate them.

Microsoft does not provide a Java library for this validation at the moment, but there are many third-party open source libraries that provide this functionality. For example, you can use jjwt


问:
Odd Java ternary behavior when assigning value. What is Java doing behind the scenes for this to happen?
A few days ago, I ran into a fascinating scenario that I couldn't find any documentation on how or why Java lets the following happen. (This snippet is just a simplified form of the bug.)

```<code>    @Test
    public void test() {
      boolean bool = false;
      Integer intVal = Integer.valueOf(5);
      Long longVal = null;
      Long result = bool ? intVal : longVal;

      System.out.println(" > " + result);
   }
</code>```

in the snippet above:

if the bool = true, then you get the value '5';

but if bool = false, then you get a null pointer exception when trying to evaluate the ternary operation. NOT the print statement.

To fix this I just change 'result' to

```<code>Long result = bool ? Long.valueOf(intVal) : longVal;
</code>```

Doing this, will give the expected behavior I needed:

if the bool = true, then you get the value '5';

but if bool = false, then you get 'null'

now the fun part is that if you split this into a normal if/else statement, then java does NOT let you compile

```<code>longVal = intVal;
</code>```

but it doesnt catch that via the ternary operator. So what's Java doing to make it null point in the original snippet?

(java 11)

答:
When you do this:

```<code>Long result = bool ? intVal : longVal
</code>```

This expression is returning a long and, when bool is false it tries to unboxe null to a Long value to fit the result variable and throws a NPE.

When you do this:

```<code>Long result = bool ? Long.valueOf(intVal) : longVal
</code>```

This expression is already returning Long then there is no need for unboxing and the null value is successfully assigned to the result variable.

Reference:

As discussed in the comments section, to better understand why does this happen, check the following sections of the JLS:

Section 5.6.2: Binary Numeric Promotion

Section 15.25: Conditional Operator ? :

Body:
A few days ago, I ran into a fascinating scenario that I couldn't find any documentation on how or why Java lets the following happen. (This snippet is just a simplified form of the bug.)

    @Test
    public void test() {
      boolean bool = false;
      Integer intVal = Integer.valueOf(5);
      Long longVal = null;
      Long result = bool ? intVal : longVal;

      System.out.println(" > " + result);
   }

in the snippet above:

if the bool = true, then you get the value '5';

but if bool = false, then you get a null pointer exception when trying to evaluate the ternary operation. NOT the print statement.

To fix this I just change 'result' to

Long result = bool ? Long.valueOf(intVal) : longVal;

Doing this, will give the expected behavior I needed:

if the bool = true, then you get the value '5';

but if bool = false, then you get 'null'

now the fun part is that if you split this into a normal if/else statement, then java does NOT let you compile

longVal = intVal;

but it doesnt catch that via the ternary operator. So what's Java doing to make it null point in the original snippet?

(java 11)

Body:
When you do this:

Long result = bool ? intVal : longVal

This expression is returning a long and, when bool is false it tries to unboxe null to a Long value to fit the result variable and throws a NPE.

When you do this:

Long result = bool ? Long.valueOf(intVal) : longVal

This expression is already returning Long then there is no need for unboxing and the null value is successfully assigned to the result variable.

Reference:

As discussed in the comments section, to better understand why does this happen, check the following sections of the JLS:

Section 5.6.2: Binary Numeric Promotion

Section 15.25: Conditional Operator ? :


问:
How to handle returned object from function to avoid memory leaks?
Suppose I have a function

```<code>- (NSString *)fullNameCopy {
    return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
}
</code>```

Can somebody tell me how to call this function, how to assign its value to a new object, and how then to release it, avoiding memory leaks, and bad access.

Would it be like

```<code>NSSting *abc = [object fullNameCopy];
</code>```

// Use it and release

```<code>[abc release];
</code>```

or I should alloc abc string too ?

Update:

The point here, Can I return non-autorelease objects from a function and then release them in the calling function. As per Obj-C function naming conventions, a function name containing alloc or copy should return object assuming that calling function has the ownership.

As in above case, my function "fullNameCopy" return a non-autoreleased abject, and I want to release them in the calling function.

答: return [[[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName]autorelease];</p>

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have a function

- (NSString *)fullNameCopy {
    return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
}

Can somebody tell me how to call this function, how to assign its value to a new object, and how then to release it, avoiding memory leaks, and bad access.

Would it be like

NSSting *abc = [object fullNameCopy];

// Use it and release

[abc release];

or I should alloc abc string too ?

Update:

The point here, Can I return non-autorelease objects from a function and then release them in the calling function. As per Obj-C function naming conventions, a function name containing alloc or copy should return object assuming that calling function has the ownership.

As in above case, my function "fullNameCopy" return a non-autoreleased abject, and I want to release them in the calling function.


问:
Is there a way to print a pointer with %x argument
I have tried to make a program with the parameter %d in a pointer but it does not work, I changed  to %p, but that is for the address, I want to print the value.
This is the error

```
gcc null_Pointer.c -o null_Pointer
null_Pointer.c: In function ‘main’:
null_Pointer.c:7:35: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
    7 |    printf("The value of ptr is : %x\n", ptr  );
      |                                  ~^     ~~~
      |                                   |     |
      |                                   |     int *
      |                                   unsigned int
      |                                  %ls
```

this  is the  code

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

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );

   return 0;
}
</code>```

答:
The proper format specifier for printing a pointer value is %p.  You also need to cast the pointer to void * because printf doesn't know the exact type of the parameters it receives.

```<code>printf("The value of ptr is : %p\n", (void *)ptr);
</code>```

Regarding your comment:

I changed to %p, but that is for the address

That's correct, and the address in question is the value of ptr.

Body:
I have tried to make a program with the parameter %d in a pointer but it does not work, I changed  to %p, but that is for the address, I want to print the value.
This is the error

gcc null_Pointer.c -o null_Pointer
null_Pointer.c: In function ‘main’:
null_Pointer.c:7:35: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
    7 |    printf("The value of ptr is : %x\n", ptr  );
      |                                  ~^     ~~~
      |                                   |     |
      |                                   |     int *
      |                                   unsigned int
      |                                  %ls

this  is the  code

#include <stdio.h>

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );

   return 0;
}

Body:
The proper format specifier for printing a pointer value is %p.  You also need to cast the pointer to void * because printf doesn't know the exact type of the parameters it receives.

printf("The value of ptr is : %p\n", (void *)ptr);

Regarding your comment:

I changed to %p, but that is for the address

That's correct, and the address in question is the value of ptr.


问:
Firebase custom action url breaks verification
I hadn't tried to verify any account and changed action URL at firebase authentication for email verification and now when user clicks the action link it doesn't verify the user and there's not a reset button for the action link. i have tried typing its placeholder value but didn't work. anyone know how can i fix this? or do i have to do any additional step to actually verify a user.</p>

```<code>firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
        .then(cred => {
          ref.set({
            username: this.username,
            avatar: this.signAvatar,
            user_id: cred.user.uid,
            villaComments: [],
            ratedVillas: []
          })
        }).then(() => {
          firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
          user.sendEmailVerification();
           } })
</code>```

答: I made a typo. when I write the old value it worked.</p>

Body:
I hadn't tried to verify any account and changed action URL at firebase authentication for email verification and now when user clicks the action link it doesn't verify the user and there's not a reset button for the action link. i have tried typing its placeholder value but didn't work. anyone know how can i fix this? or do i have to do any additional step to actually verify a user.

firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
        .then(cred => {
          ref.set({
            username: this.username,
            avatar: this.signAvatar,
            user_id: cred.user.uid,
            villaComments: [],
            ratedVillas: []
          })
        }).then(() => {
          firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
          user.sendEmailVerification();
           } })


问:
CORS issue when calling a localhost API hosted on one port from another port
I have a localhost Rest API POST query hosted using Docker at port 8501: http://localhost:8501/v1/models/model:predict. I have an HTML file which runs with a JavaScript script and it is hosted at http://127.0.0.1:8887/ using WebServer for Chrome. I am able to call global Rest API POST queries from my HTML-JS files and my local Rest API works fine from POSTMAN. But I am unable to call my API from my HTML-JS files.

Below is my JS file:

```<code>function foo() {
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    myHeaders.append("Access-Control-Allow-Origin", "*");
    myHeaders.append("Access-Control-Allow-Methods", "POST");

    var raw = JSON.stringify({"instances":[[0]]});

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: raw,
        redirect: 'follow'
    };

    fetch("http://localhost:8501/v1/models/model:predict", requestOptions)
        .then(response => console.log(response.text()))
        .then(result => console.log(result))
        .catch(error => console.log('error', error));

}
</code>```

I get the below error:

Access to fetch at
  'http://localhost:8501/v1/models/model:predict' from origin
  'http://127.0.0.1:8887' has been blocked by CORS policy: Response to
  preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. If an opaque response serves your needs, set the request's
  mode to 'no-cors' to fetch the resource with CORS disabled.

Can anyone please help me?

答: Your server is missing header Access-Control-Allow-Origin in response, as it is responsible what to allow or not. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Body:
I have a localhost Rest API POST query hosted using Docker at port 8501: http://localhost:8501/v1/models/model:predict. I have an HTML file which runs with a JavaScript script and it is hosted at http://127.0.0.1:8887/ using WebServer for Chrome. I am able to call global Rest API POST queries from my HTML-JS files and my local Rest API works fine from POSTMAN. But I am unable to call my API from my HTML-JS files.

Below is my JS file:

function foo() {
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    myHeaders.append("Access-Control-Allow-Origin", "*");
    myHeaders.append("Access-Control-Allow-Methods", "POST");

    var raw = JSON.stringify({"instances":[[0]]});

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: raw,
        redirect: 'follow'
    };

    fetch("http://localhost:8501/v1/models/model:predict", requestOptions)
        .then(response => console.log(response.text()))
        .then(result => console.log(result))
        .catch(error => console.log('error', error));

}

I get the below error:

Access to fetch at
  'http://localhost:8501/v1/models/model:predict' from origin
  'http://127.0.0.1:8887' has been blocked by CORS policy: Response to
  preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. If an opaque response serves your needs, set the request's
  mode to 'no-cors' to fetch the resource with CORS disabled.

Can anyone please help me?


问:
Function is Repeating Ten Times Instead of Once - Pygame Zero
I have written a simple racing game in Pygame Zero. This comes from the MagPi "Retro Gaming with Raspberry Pi" Book. I am a beginner programmer so I might be asking an obvious question. I want to make levels. For every 100 score, level + 1. Win at 10 levels.

areas of interest might be my draw() function:

```<code>    global gameStatus, level
    screen.fill((128, 128, 128))
    if gameStatus == 0:
        car.draw()
        b = 0
        while b < len(trackLeft):
            trackLeft[b].draw()
            trackRight[b].draw()
            b += 1
        screen.draw.text("Score: " + str(score), (50, 30), color="black")
        if score % 100 == 0:
            check_levels()
        screen.draw.text("Level: " + str(level), (50, 50), color="black")
    if gameStatus == 1:
        screen.blit('rflag', (318, 268))
    if gameStatus == 2:
        screen.blit('cflag', (318, 268))
</code>```

and my level_up() function:

```<code>    global level
    if level <= 10:
        level += 1
    if level == 10:
        gameStatus == 2
</code>```

score is counted for every one piece of track made there is one higher score.

My problem: When I get to 100 score, level is added by 10, not by one. I don't know what seems to happen. Might it be that for every score there are a few FPS/ticks, and that as level is updated every tick, it appears that when the score hangs on 100 for about 10 ticks, the level gets update every tick?

As my program is quite short, I'll just go ahead and post all the code:

```<code>import time
from random import randint
import pygame
import pgzrun

WIDTH = 700
HEIGHT = 800

car = Actor("racecar")
car.pos = 250, 700
SPEED = 4
trackLeft = []
trackRight = []
trackCount = 0
trackPosition = 250
trackWidth = 120
trackDirection = False
gameStatus = 0
score = 0
level = 1

def draw():
    global gameStatus, level
    screen.fill((128, 128, 128))
    if gameStatus == 0:
        car.draw()
        b = 0
        while b < len(trackLeft):
            trackLeft[b].draw()
            trackRight[b].draw()
            b += 1
        screen.draw.text("Score: " + str(score), (50, 30), color="black")
        if score % 100 == 0:
            check_levels()
        screen.draw.text("Level: " + str(level), (50, 50), color="black")
    if gameStatus == 1:
        screen.blit('rflag', (318, 268))
    if gameStatus == 2:
        screen.blit('cflag', (318, 268))

def update():
    global gameStatus, trackCount
    if gameStatus == 0:
        if keyboard.left: car.x -= 2
        if keyboard.right: car.x += 2
        update_track()

def make_track():
    global trackCount, trackLeft, trackRight, trackPosition, trackWidth, score
    trackLeft.append(Actor("barrier", pos=(trackPosition - trackWidth, 0)))
    trackRight.append(Actor("barrier", pos=(trackPosition + trackWidth, 0)))
    trackCount += 1
    score += 1

def update_track():
    global trackCount, trackPosition, trackDirection, trackWidth, gameStatus
    b = 0
    while b < len(trackLeft):
        if car.colliderect(trackLeft[b]) or car.colliderect(trackRight[b]):
            gameStatus = 1
        trackLeft[b].y += SPEED
        trackRight[b].y += SPEED
        b += 1
    if trackLeft[len(trackLeft) - 1].y > 32:
        if trackDirection == False: trackPosition += 16
        if trackDirection == True: trackPosition -= 16
        if randint(0, 4) == 1: trackDirection = not trackDirection
        if trackPosition > 700 - trackWidth: trackDirection = True
        if trackPosition < trackWidth: trackDirection = False
        make_track()

def check_levels():
    global level
    if level <= 10:
        level += 1
    if level == 10:
        gameStatus = 2

make_track()

pgzrun.go()
</code>```

答:
You have to do the level check when the score is updated. Note, draw is executed more often then the score is updated, so if score % 100 == 0: is fulfilled multiple times and the level is incremented more than once:

def draw():
    global gameStatus, level
    screen.fill((128, 128, 128))
    if gameStatus == 0:
        # [...]

        screen.draw.text("Score: " + str(score), (50, 30), color="black")

        # DELETE <--------------------------
        #if score % 100 == 0:
        #    check_levels()

        screen.draw.text("Level: " + str(level), (50, 50), color="black")
```

<pre class="lang-py prettyprint-override"><code>def make_track():
    #[...]
    trackCount += 1
    score += 1

    # ADD <-----------------------------
    if score % 100 == 0:
        check_levels()
</code>```

Furthermore your game lags after a while, because the lists trackLeft and trackRight are continuously growing. Remove the barriers from the list which are out of the window at the bottom:

def make_track():
    global trackCount, trackLeft, trackRight, trackPosition, trackWidth, score
    trackLeft.append(Actor("barrier", pos=(trackPosition - trackWidth, 0)))
    trackRight.append(Actor("barrier", pos=(trackPosition + trackWidth, 0)))

    # remove barriers which are out of screen
    if trackLeft[0].y >= HEIGHT:
        del trackLeft[0]
    if trackRight[0].y >= HEIGHT:
        del trackRight[0]

    trackCount += 1
    score += 1
    if score % 100 == 0:
        check_levels()
```

Body:
I have written a simple racing game in Pygame Zero. This comes from the MagPi "Retro Gaming with Raspberry Pi" Book. I am a beginner programmer so I might be asking an obvious question. I want to make levels. For every 100 score, level + 1. Win at 10 levels.

areas of interest might be my draw() function:

    global gameStatus, level
    screen.fill((128, 128, 128))
    if gameStatus == 0:
        car.draw()
        b = 0
        while b < len(trackLeft):
            trackLeft[b].draw()
            trackRight[b].draw()
            b += 1
        screen.draw.text("Score: " + str(score), (50, 30), color="black")
        if score % 100 == 0:
            check_levels()
        screen.draw.text("Level: " + str(level), (50, 50), color="black")
    if gameStatus == 1:
        screen.blit('rflag', (318, 268))
    if gameStatus == 2:
        screen.blit('cflag', (318, 268))

and my level_up() function:

    global level
    if level <= 10:
        level += 1
    if level == 10:
        gameStatus == 2

score is counted for every one piece of track made there is one higher score.

My problem: When I get to 100 score, level is added by 10, not by one. I don't know what seems to happen. Might it be that for every score there are a few FPS/ticks, and that as level is updated every tick, it appears that when the score hangs on 100 for about 10 ticks, the level gets update every tick?

As my program is quite short, I'll just go ahead and post all the code:

import time
from random import randint
import pygame
import pgzrun

WIDTH = 700
HEIGHT = 800

car = Actor("racecar")
car.pos = 250, 700
SPEED = 4
trackLeft = []
trackRight = []
trackCount = 0
trackPosition = 250
trackWidth = 120
trackDirection = False
gameStatus = 0
score = 0
level = 1

def draw():
    global gameStatus, level
    screen.fill((128, 128, 128))
    if gameStatus == 0:
        car.draw()
        b = 0
        while b < len(trackLeft):
            trackLeft[b].draw()
            trackRight[b].draw()
            b += 1
        screen.draw.text("Score: " + str(score), (50, 30), color="black")
        if score % 100 == 0:
            check_levels()
        screen.draw.text("Level: " + str(level), (50, 50), color="black")
    if gameStatus == 1:
        screen.blit('rflag', (318, 268))
    if gameStatus == 2:
        screen.blit('cflag', (318, 268))

def update():
    global gameStatus, trackCount
    if gameStatus == 0:
        if keyboard.left: car.x -= 2
        if keyboard.right: car.x += 2
        update_track()

def make_track():
    global trackCount, trackLeft, trackRight, trackPosition, trackWidth, score
    trackLeft.append(Actor("barrier", pos=(trackPosition - trackWidth, 0)))
    trackRight.append(Actor("barrier", pos=(trackPosition + trackWidth, 0)))
    trackCount += 1
    score += 1

def update_track():
    global trackCount, trackPosition, trackDirection, trackWidth, gameStatus
    b = 0
    while b < len(trackLeft):
        if car.colliderect(trackLeft[b]) or car.colliderect(trackRight[b]):
            gameStatus = 1
        trackLeft[b].y += SPEED
        trackRight[b].y += SPEED
        b += 1
    if trackLeft[len(trackLeft) - 1].y > 32:
        if trackDirection == False: trackPosition += 16
        if trackDirection == True: trackPosition -= 16
        if randint(0, 4) == 1: trackDirection = not trackDirection
        if trackPosition > 700 - trackWidth: trackDirection = True
        if trackPosition < trackWidth: trackDirection = False
        make_track()

def check_levels():
    global level
    if level <= 10:
        level += 1
    if level == 10:
        gameStatus = 2

make_track()

pgzrun.go()

Body:
You have to do the level check when the score is updated. Note, draw is executed more often then the score is updated, so if score % 100 == 0: is fulfilled multiple times and the level is incremented more than once:

def draw():
    global gameStatus, level
    screen.fill((128, 128, 128))
    if gameStatus == 0:
        # [...]

        screen.draw.text("Score: " + str(score), (50, 30), color="black")

        # DELETE <--------------------------
        #if score % 100 == 0:
        #    check_levels()

        screen.draw.text("Level: " + str(level), (50, 50), color="black")

def make_track():
    #[...]
    trackCount += 1
    score += 1

    # ADD <-----------------------------
    if score % 100 == 0:
        check_levels()

Furthermore your game lags after a while, because the lists trackLeft and trackRight are continuously growing. Remove the barriers from the list which are out of the window at the bottom:

def make_track():
    global trackCount, trackLeft, trackRight, trackPosition, trackWidth, score
    trackLeft.append(Actor("barrier", pos=(trackPosition - trackWidth, 0)))
    trackRight.append(Actor("barrier", pos=(trackPosition + trackWidth, 0)))

    # remove barriers which are out of screen
    if trackLeft[0].y >= HEIGHT:
        del trackLeft[0]
    if trackRight[0].y >= HEIGHT:
        del trackRight[0]

    trackCount += 1
    score += 1
    if score % 100 == 0:
        check_levels()


问:
Unity C#: type error referencing float from another script
I'm new to Unity, and although I've looked this up a million times, I can't get my script to stop erroring. I am trying to reference a public float (attached to a different object) in a new script - which is simple, I know. I have tried various methods, but this is what I have so far. I keep getting the error that the float (currentHealth) cannot  be implicitly converted to 'Health', which I understand but cannot seem to fix.  What am I doing wrong?

```<code>public class sugarGenerator : MonoBehaviour
{
    public GameObject sugar;
    public GameObject Insulin;
    public Transform generationPoint;
    public float distanceBetween;

    Health PlayerHealth;

    // Update is called once per frame
    public void Awake ()
    {
        GameObject.FindWithTag("Main_Girl_0");
        PlayerHealth = GetComponent<Health>().currentHealth;
    }
}
</code>```

答:
Based on my comment:

PlayerHealth is not a float, it is Health. You cannot assign a float (the type of currentHealth) to a Health.

I'm not familiar with Unity, but perhaps you meant to do:

```<code>PlayerHealth = GetComponent<Health>();
</code>```

Body:
I'm new to Unity, and although I've looked this up a million times, I can't get my script to stop erroring. I am trying to reference a public float (attached to a different object) in a new script - which is simple, I know. I have tried various methods, but this is what I have so far. I keep getting the error that the float (currentHealth) cannot  be implicitly converted to 'Health', which I understand but cannot seem to fix.  What am I doing wrong?

public class sugarGenerator : MonoBehaviour
{
    public GameObject sugar;
    public GameObject Insulin;
    public Transform generationPoint;
    public float distanceBetween;

    Health PlayerHealth;

    // Update is called once per frame
    public void Awake ()
    {
        GameObject.FindWithTag("Main_Girl_0");
        PlayerHealth = GetComponent<Health>().currentHealth;
    }
}

Body:
Based on my comment:

PlayerHealth is not a float, it is Health. You cannot assign a float (the type of currentHealth) to a Health.

I'm not familiar with Unity, but perhaps you meant to do:

PlayerHealth = GetComponent<Health>();


问:
LOST all Pod modules
HELP! I restart the project, suddenly my project got an error because of not having modules. I did pod install and pod update, but the project can not read the pod? Something's happen with the pod files?

答:
Verify is your Pod file looks like the below

```<code>use_frameworks!

target 'YOUR_PROJECT' do
  pod 'Firebase'
  pod 'Firebase/Auth'
  pod 'Firebase/Core'
  pod 'Firebase/Database'
end
</code>```

Try to do pod install, pod update if required. Clean the Workspace and restart the Xcode if the issue still persists.

Title: LOST all Pod modules

Body:
Verify is your Pod file looks like the below

use_frameworks!

target 'YOUR_PROJECT' do
  pod 'Firebase'
  pod 'Firebase/Auth'
  pod 'Firebase/Core'
  pod 'Firebase/Database'
end

Try to do pod install, pod update if required. Clean the Workspace and restart the Xcode if the issue still persists.


问:
When invoking AutoCAD through interop, how to to find current installed AutoCAD program ID
I am using interop and within a console application launching CAD as per the following example. How can I find the programID of AutoCAD which is installed on my local machine.

For example in the below article it uses

```<code>const string progID = "AutoCAD.Application.17.1";
</code>```

https://through-the-interface.typepad.com/through_the_interface/2007/12/launching-autoc.html

答:
Try just using "AutoCAD.Application" with no specific reference. Works for me.

Your issue is going to be the reference to the proper version of AutoCAD though. I get around this by using late binding.

Pretty good information on Late Binding

Not really sure that this is kept up to date -->
AutoCAD Version List

Body:
I am using interop and within a console application launching CAD as per the following example. How can I find the programID of AutoCAD which is installed on my local machine.

For example in the below article it uses

const string progID = "AutoCAD.Application.17.1";

https://through-the-interface.typepad.com/through_the_interface/2007/12/launching-autoc.html


问:
Reactive Filtering Based on User Login - Shinyauthr
I have a QA Shiny Dashboard app that has a master dataset that must filter the rows used in subsequent tables / maps according to user login details.

For example: if the user logs in with a particular username (location@email.com) then the reactive function selects rows that contain this username and passes these to the shiny app for rendering.

Example of basic premise:

```<code>username <- "location@email.com"

new_dataset <- filter(dataset, column %like% username

output$table <- renderTable ({
  new_dataset
)}
</code>```

I am using the shiny author package to create this but I am having difficulty passing the user login details created by the in-built Shinyauthr functions to a reactive function. Code below:

```<code>users <- data.frame(user= c("user1", "user2", "user3"),
                         password = c("pass1", "pass2", "pass3"),
                         stringsAsFactors = FALSE)

ui <- dashboardPage(

  dashboardHeader(
    title = "QA App",

    tags$li(class = "dropdown", style = "padding: 8px;", shinyauthr::logoutUI("logout"))
  ),

  dashboardSidebar(
    collapsed = TRUE, sidebarMenuOutput("sidebar")
  ),

  dashboardBody(

    shinyjs::useShinyjs(),

    # shinyauthr login ui module here
    shinyauthr::loginUI("login"),

    tabItems(
      tabItem("tab", uiOutput("tab1_ui"))
    )
  )
)

server <- function(input, output) {

credentials <- callModule(shinyauthr::login, "login",
                          data = users,
                          user_col = user,
                          pwd_col = password,
                          sodium_hashed = FALSE,
                          log_out = reactive(logout_init()))

# logout status managed by shinyauthr module and stored here
logout_init <- callModule(shinyauthr::logout, "logout", reactive(credentials()$user_auth))

output$sidebar <- renderMenu({
  req(credentials()$user_auth)
  sidebarMenu(

    menuItem("Tab", tabName = "tab", icon = icon("arrows-alt-v"))

  )
})

output$tab1_ui <- renderUI({

  req(credentials()$user_auth)
  fluidPage(

    mainPanel(
             tableOutput("table"),
      )
     )
  })
}

shinyApp(ui = ui, server = server)
</code>```

I wish to create a reactive function that will render this new_dataset and pass it to the table output within the UI. The question is how to access user login credentials as characters strings to use in filtering?

答:
As often happens in these cases, a lot of wrangling finally led to an answer but I will post my solution here in case anyone runs into a similar issue.

R2Evans was correct in that it can be called with credentials()$info. The issue was trying to use eventReactive, rather than simply reactive.

Reactive user details are collected via:

```<code>credentials <- callModule(shinyauthr::login, "login",
                          data = user_base,
                          user_col = user,
                          pwd_col = password,
                          sodium_hashed = FALSE,
                          log_out = reactive(logout_init()))

user_info <- reactive({credentials()$info})

filteredData <- reactive({
  filter(table, column %like% as.character(user_info()$user))
})

output$table <- renderTable(filteredData())
</code>```

Body:
I have a QA Shiny Dashboard app that has a master dataset that must filter the rows used in subsequent tables / maps according to user login details.

For example: if the user logs in with a particular username (location@email.com) then the reactive function selects rows that contain this username and passes these to the shiny app for rendering.

Example of basic premise:

username <- "location@email.com"

new_dataset <- filter(dataset, column %like% username

output$table <- renderTable ({
  new_dataset
)}

I am using the shiny author package to create this but I am having difficulty passing the user login details created by the in-built Shinyauthr functions to a reactive function. Code below:

users <- data.frame(user= c("user1", "user2", "user3"),
                         password = c("pass1", "pass2", "pass3"),
                         stringsAsFactors = FALSE)

ui <- dashboardPage(

  dashboardHeader(
    title = "QA App",

    tags$li(class = "dropdown", style = "padding: 8px;", shinyauthr::logoutUI("logout"))
  ),

  dashboardSidebar(
    collapsed = TRUE, sidebarMenuOutput("sidebar")
  ),

  dashboardBody(

    shinyjs::useShinyjs(),

    # shinyauthr login ui module here
    shinyauthr::loginUI("login"),

    tabItems(
      tabItem("tab", uiOutput("tab1_ui"))
    )
  )
)

server <- function(input, output) {

credentials <- callModule(shinyauthr::login, "login",
                          data = users,
                          user_col = user,
                          pwd_col = password,
                          sodium_hashed = FALSE,
                          log_out = reactive(logout_init()))

# logout status managed by shinyauthr module and stored here
logout_init <- callModule(shinyauthr::logout, "logout", reactive(credentials()$user_auth))

output$sidebar <- renderMenu({
  req(credentials()$user_auth)
  sidebarMenu(

    menuItem("Tab", tabName = "tab", icon = icon("arrows-alt-v"))

  )
})

output$tab1_ui <- renderUI({

  req(credentials()$user_auth)
  fluidPage(

    mainPanel(
             tableOutput("table"),
      )
     )
  })
}

shinyApp(ui = ui, server = server)

I wish to create a reactive function that will render this new_dataset and pass it to the table output within the UI. The question is how to access user login credentials as characters strings to use in filtering?

Body:
As often happens in these cases, a lot of wrangling finally led to an answer but I will post my solution here in case anyone runs into a similar issue.

R2Evans was correct in that it can be called with credentials()$info. The issue was trying to use eventReactive, rather than simply reactive.

Reactive user details are collected via:

credentials <- callModule(shinyauthr::login, "login",
                          data = user_base,
                          user_col = user,
                          pwd_col = password,
                          sodium_hashed = FALSE,
                          log_out = reactive(logout_init()))

user_info <- reactive({credentials()$info})

filteredData <- reactive({
  filter(table, column %like% as.character(user_info()$user))
})

output$table <- renderTable(filteredData())


问:
How to draw eye gaze data from eye tracker by PyQt while a video is playing
I am working bulid a eye gaze visualization tool just like this by PyQt5, and I also checked this post.
here is the code by modifing the above links.
turn out it's worked, but the video always get stuck sometime (the audio is normal, the the frames stuck, both video content and ellipse,just like this video),anyone can help?

```<code>import os
import time

from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia, QtMultimediaWidgets
import tobii_research as tr
import numpy as np

class Widget(QtWidgets.QWidget):

    def __init__(self, parent=None):

        super(Widget, self).__init__(parent)

        #first window,just have a single button for play the video
        self.resize(256, 256)
        self.btn_play = QtWidgets.QPushButton(self)
        self.btn_play.setGeometry(QtCore.QRect(100, 100, 28, 28))
        self.btn_play.setObjectName("btn_open")
        self.btn_play.setText("Play")
        self.btn_play.clicked.connect(self.Play_video)#click to play video
        #

        self._scene = QtWidgets.QGraphicsScene(self)
        self._gv = QtWidgets.QGraphicsView(self._scene)
        #construct a videoitem for showing the video
        self._videoitem = QtMultimediaWidgets.QGraphicsVideoItem()
        #add it into the scene
        self._scene.addItem(self._videoitem)

        # assign _ellipse_item is the gaze data, and embed it into videoitem,so it can show above the video.
        self._ellipse_item = QtWidgets.QGraphicsEllipseItem(QtCore.QRectF(0, 0, 40, 40), self._videoitem)
        self._ellipse_item.setBrush(QtGui.QBrush(QtCore.Qt.black))
        self._ellipse_item.setPen(QtGui.QPen(QtCore.Qt.red))
        #self._scene.addItem(self._ellipse_item)
        self._gv.fitInView(self._videoitem)

        self._player = QtMultimedia.QMediaPlayer(self, QtMultimedia.QMediaPlayer.VideoSurface)
        self._player.setVideoOutput(self._videoitem)
        file = os.path.join(os.path.dirname(__file__), "video.mp4")#video.mp4 is under the same dirctory
        self._player.setMedia(QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(file)))
        print(f"self._videoitem::{self._videoitem.size()}")

        #get eye tracker
        self.eyetrackers = tr.find_all_eyetrackers()
        self.my_eyetracker = self.eyetrackers[0]

    def gaze_data_callback(self, gaze_data_):

        #for now, I don't know the coordinate system,just randomly assign the gaze data to test the functionality
        self._ellipse_item.setPos(float(np.random.choice(range(0, 300))), float(np.random.choice(range(0, 240))))
        print("time.time()::{}".format(time.time()))

    def Play_video(self):
        self.my_eyetracker.subscribe_to(tr.EYETRACKER_GAZE_DATA, self.gaze_data_callback, as_dictionary=True)
        #size = QtCore.QSizeF(1920.0, 1080.0)#I hope it can fullscreen the video
        #self._videoitem.setSize(size)
        #self._gv.showFullScreen()
        self._gv.resize(720,720)
        self._gv.show()
        self._player.play()

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
</code>```

cmd printout information here

答:
According to the warning message:

```<code>QObject::startTimer: Timers can only be used with threads started with QThread
</code>```

it can be deduced that the callback associated with "my_eyetracker" is executed in a secondary thread, so the position of the item from a different thread to the main thread would be updated, which could generate the problem described by the OP.

The solution is to send the callback information to the guide through signals.

import os
import time

from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia, QtMultimediaWidgets
import tobii_research as tr
import numpy as np

class EyeTracker(QtCore.QObject):
    positionChanged = QtCore.pyqtSignal(float, float)

    def __init__(self, tracker, parent=None):
        super(EyeTracker, self).__init__(parent)
        self._tracker = tracker

    @property
    def tracker(self):
        return self._tracker

    def start(self):
        self.tracker.subscribe_to(
            tr.EYETRACKER_GAZE_DATA, self._callback, as_dictionary=True
        )

    def _callback(self, gaze_data_):
        self.positionChanged.emit(
            float(np.random.choice(range(0, 300))),
            float(np.random.choice(range(0, 240))),
        )
        print("time.time()::{}".format(time.time()))

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):

        super(Widget, self).__init__(parent)

        # first window,just have a single button for play the video
        self.resize(256, 256)
        self.btn_play = QtWidgets.QPushButton(self)
        self.btn_play.setGeometry(QtCore.QRect(100, 100, 28, 28))
        self.btn_play.setObjectName("btn_open")
        self.btn_play.setText("Play")
        self.btn_play.clicked.connect(self.Play_video)  # click to play video
        #

        self._scene = QtWidgets.QGraphicsScene(self)
        self._gv = QtWidgets.QGraphicsView(self._scene)
        # construct a videoitem for showing the video
        self._videoitem = QtMultimediaWidgets.QGraphicsVideoItem()
        # add it into the scene
        self._scene.addItem(self._videoitem)

        # assign _ellipse_item is the gaze data, and embed it into videoitem,so it can show above the video.
        self._ellipse_item = QtWidgets.QGraphicsEllipseItem(
            QtCore.QRectF(0, 0, 40, 40), self._videoitem
        )
        self._ellipse_item.setBrush(QtGui.QBrush(QtCore.Qt.black))
        self._ellipse_item.setPen(QtGui.QPen(QtCore.Qt.red))
        # self._scene.addItem(self._ellipse_item)
        self._gv.fitInView(self._videoitem)

        self._player = QtMultimedia.QMediaPlayer(
            self, QtMultimedia.QMediaPlayer.VideoSurface
        )
        self._player.setVideoOutput(self._videoitem)
        file = os.path.join(
            os.path.dirname(__file__), "video.mp4"
        )  # video.mp4 is under the same dirctory
        self._player.setMedia(
            QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(file))
        )
        print(f"self._videoitem::{self._videoitem.size()}")

        # get eye tracker
        eyetrackers = tr.find_all_eyetrackers()
        self.tracker = EyeTracker(eyetrackers[0])
        self.tracker.positionChanged.connect(self._ellipse_item.setPos)

    def Play_video(self):
        self.tracker.start()
        # size = QtCore.QSizeF(1920.0, 1080.0)#I hope it can fullscreen the video
        # self._videoitem.setSize(size)
        # self._gv.showFullScreen()
        self._gv.resize(720, 720)
        self._gv.show()
        self._player.play()

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
```

Body:
I am working bulid a eye gaze visualization tool just like this by PyQt5, and I also checked this post.
here is the code by modifing the above links.
turn out it's worked, but the video always get stuck sometime (the audio is normal, the the frames stuck, both video content and ellipse,just like this video),anyone can help?

import os
import time

from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia, QtMultimediaWidgets
import tobii_research as tr
import numpy as np

class Widget(QtWidgets.QWidget):

    def __init__(self, parent=None):

        super(Widget, self).__init__(parent)

        #first window,just have a single button for play the video
        self.resize(256, 256)
        self.btn_play = QtWidgets.QPushButton(self)
        self.btn_play.setGeometry(QtCore.QRect(100, 100, 28, 28))
        self.btn_play.setObjectName("btn_open")
        self.btn_play.setText("Play")
        self.btn_play.clicked.connect(self.Play_video)#click to play video
        #

        self._scene = QtWidgets.QGraphicsScene(self)
        self._gv = QtWidgets.QGraphicsView(self._scene)
        #construct a videoitem for showing the video
        self._videoitem = QtMultimediaWidgets.QGraphicsVideoItem()
        #add it into the scene
        self._scene.addItem(self._videoitem)

        # assign _ellipse_item is the gaze data, and embed it into videoitem,so it can show above the video.
        self._ellipse_item = QtWidgets.QGraphicsEllipseItem(QtCore.QRectF(0, 0, 40, 40), self._videoitem)
        self._ellipse_item.setBrush(QtGui.QBrush(QtCore.Qt.black))
        self._ellipse_item.setPen(QtGui.QPen(QtCore.Qt.red))
        #self._scene.addItem(self._ellipse_item)
        self._gv.fitInView(self._videoitem)

        self._player = QtMultimedia.QMediaPlayer(self, QtMultimedia.QMediaPlayer.VideoSurface)
        self._player.setVideoOutput(self._videoitem)
        file = os.path.join(os.path.dirname(__file__), "video.mp4")#video.mp4 is under the same dirctory
        self._player.setMedia(QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(file)))
        print(f"self._videoitem::{self._videoitem.size()}")

        #get eye tracker
        self.eyetrackers = tr.find_all_eyetrackers()
        self.my_eyetracker = self.eyetrackers[0]

    def gaze_data_callback(self, gaze_data_):

        #for now, I don't know the coordinate system,just randomly assign the gaze data to test the functionality
        self._ellipse_item.setPos(float(np.random.choice(range(0, 300))), float(np.random.choice(range(0, 240))))
        print("time.time()::{}".format(time.time()))

    def Play_video(self):
        self.my_eyetracker.subscribe_to(tr.EYETRACKER_GAZE_DATA, self.gaze_data_callback, as_dictionary=True)
        #size = QtCore.QSizeF(1920.0, 1080.0)#I hope it can fullscreen the video
        #self._videoitem.setSize(size)
        #self._gv.showFullScreen()
        self._gv.resize(720,720)
        self._gv.show()
        self._player.play()

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

cmd printout information here

Body:
According to the warning message:

QObject::startTimer: Timers can only be used with threads started with QThread

it can be deduced that the callback associated with "my_eyetracker" is executed in a secondary thread, so the position of the item from a different thread to the main thread would be updated, which could generate the problem described by the OP.

The solution is to send the callback information to the guide through signals.

import os
import time

from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia, QtMultimediaWidgets
import tobii_research as tr
import numpy as np

class EyeTracker(QtCore.QObject):
    positionChanged = QtCore.pyqtSignal(float, float)

    def __init__(self, tracker, parent=None):
        super(EyeTracker, self).__init__(parent)
        self._tracker = tracker

    @property
    def tracker(self):
        return self._tracker

    def start(self):
        self.tracker.subscribe_to(
            tr.EYETRACKER_GAZE_DATA, self._callback, as_dictionary=True
        )

    def _callback(self, gaze_data_):
        self.positionChanged.emit(
            float(np.random.choice(range(0, 300))),
            float(np.random.choice(range(0, 240))),
        )
        print("time.time()::{}".format(time.time()))

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):

        super(Widget, self).__init__(parent)

        # first window,just have a single button for play the video
        self.resize(256, 256)
        self.btn_play = QtWidgets.QPushButton(self)
        self.btn_play.setGeometry(QtCore.QRect(100, 100, 28, 28))
        self.btn_play.setObjectName("btn_open")
        self.btn_play.setText("Play")
        self.btn_play.clicked.connect(self.Play_video)  # click to play video
        #

        self._scene = QtWidgets.QGraphicsScene(self)
        self._gv = QtWidgets.QGraphicsView(self._scene)
        # construct a videoitem for showing the video
        self._videoitem = QtMultimediaWidgets.QGraphicsVideoItem()
        # add it into the scene
        self._scene.addItem(self._videoitem)

        # assign _ellipse_item is the gaze data, and embed it into videoitem,so it can show above the video.
        self._ellipse_item = QtWidgets.QGraphicsEllipseItem(
            QtCore.QRectF(0, 0, 40, 40), self._videoitem
        )
        self._ellipse_item.setBrush(QtGui.QBrush(QtCore.Qt.black))
        self._ellipse_item.setPen(QtGui.QPen(QtCore.Qt.red))
        # self._scene.addItem(self._ellipse_item)
        self._gv.fitInView(self._videoitem)

        self._player = QtMultimedia.QMediaPlayer(
            self, QtMultimedia.QMediaPlayer.VideoSurface
        )
        self._player.setVideoOutput(self._videoitem)
        file = os.path.join(
            os.path.dirname(__file__), "video.mp4"
        )  # video.mp4 is under the same dirctory
        self._player.setMedia(
            QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(file))
        )
        print(f"self._videoitem::{self._videoitem.size()}")

        # get eye tracker
        eyetrackers = tr.find_all_eyetrackers()
        self.tracker = EyeTracker(eyetrackers[0])
        self.tracker.positionChanged.connect(self._ellipse_item.setPos)

    def Play_video(self):
        self.tracker.start()
        # size = QtCore.QSizeF(1920.0, 1080.0)#I hope it can fullscreen the video
        # self._videoitem.setSize(size)
        # self._gv.showFullScreen()
        self._gv.resize(720, 720)
        self._gv.show()
        self._player.play()

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())


问:
Optimizing R objective function with Rcpp slower, why?
I am currently working on a Bayesian method that requires multiple steps of optimisation of a multinomial logit model per iteration. I am using optim() to perform those optimisations, and an objective function written in R. A profiling revealed that optim() is the main bottleneck.

After digging around, I found this question in which they suggest that recoding the objective function with Rcpp could speed up the process. I followed the suggestion and recoded my objective function with Rcpp, but it ended up being slower (about two times slower!).

This was my first time with Rcpp (or anything related to C++) and I was not able to find a way of vectorising the code. Any idea how to make it faster?

Tl;dr: Current implementation of function in Rcpp is not as fast as vectorised R; how to make it faster?

A reproducible example:

Define objective functions in R and Rcpp: log-likelihood of an intercept only multinomial model

```<code>library(Rcpp)
library(microbenchmark)

llmnl_int <- function(beta, Obs, n_cat) {
  n_Obs     <- length(Obs)
  Xint      <- matrix(c(0, beta), byrow = T, ncol = n_cat, nrow = n_Obs)
  ind       <- cbind(c(1:n_Obs), Obs)
  Xby       <- Xint[ind]
  Xint      <- exp(Xint)
  iota      <- c(rep(1, (n_cat)))
  denom     <- log(Xint %*% iota)
  return(sum(Xby - denom))
}

cppFunction('double llmnl_int_C(NumericVector beta, NumericVector Obs, int n_cat) {

    int n_Obs = Obs.size();

    NumericVector betas = (beta.size()+1);
    for (int i = 1; i < n_cat; i++) {
        betas[i] = beta[i-1];
    };

    NumericVector Xby = (n_Obs);
    NumericMatrix Xint(n_Obs, n_cat);
    NumericVector denom = (n_Obs);
    for (int i = 0; i < Xby.size(); i++) {
        Xint(i,_) = betas;
        Xby[i] = Xint(i,Obs[i]-1.0);
        Xint(i,_) = exp(Xint(i,_));
        denom[i] = log(sum(Xint(i,_)));
    };

    return sum(Xby - denom);
}')

</code>```

Compare their efficiency:

```<code>## Draw sample from a multinomial distribution
set.seed(2020)
mnl_sample <- t(rmultinom(n = 1000,size = 1,prob = c(0.3, 0.4, 0.2, 0.1)))
mnl_sample <- apply(mnl_sample,1,function(r) which(r == 1))

## Benchmarking
microbenchmark("llmml_int" = llmnl_int(beta = c(4,2,1), Obs = mnl_sample, n_cat = 4),
               "llmml_int_C" = llmnl_int_C(beta = c(4,2,1), Obs = mnl_sample, n_cat = 4),
               times = 100)
## Results
# Unit: microseconds
#         expr     min       lq     mean   median       uq     max neval
#    llmnl_int  76.809  78.6615  81.9677  79.7485  82.8495 124.295   100
#  llmnl_int_C 155.405 157.7790 161.7677 159.2200 161.5805 201.655   100

</code>```

Now calling them in optim:

```<code>## Benchmarking with optim
microbenchmark("llmnl_int" = optim(c(4,2,1), llmnl_int, Obs = mnl_sample, n_cat = 4, method = "BFGS", hessian = T, control = list(fnscale = -1)),
               "llmnl_int_C" = optim(c(4,2,1), llmnl_int_C, Obs = mnl_sample, n_cat = 4, method = "BFGS", hessian = T, control = list(fnscale = -1)),
               times = 100)
## Results
# Unit: milliseconds
#         expr      min       lq     mean   median       uq      max neval
#    llmnl_int 12.49163 13.26338 15.74517 14.12413 18.35461 26.58235   100
#  llmnl_int_C 25.57419 25.97413 28.05984 26.34231 30.44012 37.13442   100

</code>```

I was somewhat surprised that the vectorised implementation in R was faster. Implementing a more efficient version in Rcpp (say, with RcppArmadillo?) can produce any gains? Is it a better idea to recode everything in Rcpp using a C++ optimiser?

答:
In general if you are able to use vectorized functions, you will find it to be (almost) as fast as running your code directly in Rcpp. This is because many vectorized functions in R (almost all vectorized functions in Base R) are written in C, Cpp or Fortran and as such there is often little to gain.

That said, there are improvements to gain both in your R and Rcpp code. Optimization comes from carefully studying the code, and removing unnecessary steps (memory assignment, sums, etc.).

Lets start with the Rcpp code optimization.

In your case the main optimization is to remove unnecessary matrix and vector calculations. The code is in essence

Shift beta

calculate the log of the sum of exp(shift beta) [log-sum-exp]

use Obs as an index for the shifted beta and sum over all the probabilities

substract the log-sum-exp

Using this observation we can reduce your code to 2 for-loops. Note that sum is simply another for-loop (more or less: for(i = 0; i < max; i++){ sum += x }) so avoiding the sums can speed up ones code further (in most situations this is unnecessary optimization!). In addition your input Obs is an integer vector, and we can further optimize the code by using the IntegerVector type to avoid casting the double elements to integer values (Credit to Ralf Stubner's answer).

```<code>cppFunction('double llmnl_int_C_v2(NumericVector beta, IntegerVector Obs, int n_cat)
 {

    int n_Obs = Obs.size();

    NumericVector betas = (beta.size()+1);
    //1: shift beta
    for (int i = 1; i < n_cat; i++) {
        betas[i] = beta[i-1];
    };
    //2: Calculate log sum only once:
    double expBetas_log_sum = log(sum(exp(betas)));
    // pre allocate sum
    double ll_sum = 0;

    //3: Use n_Obs, to avoid calling Xby.size() every time
    for (int i = 0; i < n_Obs; i++) {
        ll_sum += betas(Obs[i] - 1.0) ;
    };
    //4: Use that we know denom is the same for all I:
    ll_sum = ll_sum - expBetas_log_sum * n_Obs;
    return ll_sum;
}')
</code>```

Note that I have removed quite a few memory allocations and removed unnecessary calculations in the for-loop. Also i have used that denom is the same for all iterations and simply multiplied for the final result.

We can perform similar optimizations in your R-code, which results in the below function:

```<code>llmnl_int_R_v2 <- function(beta, Obs, n_cat) {
    n_Obs <- length(Obs)
    betas <- c(0, beta)
    #note: denom = log(sum(exp(betas)))
    sum(betas[Obs]) - log(sum(exp(betas))) * n_Obs
}
</code>```

Note the complexity of the function has been drastically reduced making it simpler for others to read. Just to be sure that I haven't messed up in the code somewhere let's check that they return the same results:

```<code>set.seed(2020)
mnl_sample <- t(rmultinom(n = 1000,size = 1,prob = c(0.3, 0.4, 0.2, 0.1)))
mnl_sample <- apply(mnl_sample,1,function(r) which(r == 1))

beta = c(4,2,1)
Obs = mnl_sample
n_cat = 4
xr <- llmnl_int(beta = beta, Obs = mnl_sample, n_cat = n_cat)
xr2 <- llmnl_int_R_v2(beta = beta, Obs = mnl_sample, n_cat = n_cat)
xc <- llmnl_int_C(beta = beta, Obs = mnl_sample, n_cat = n_cat)
xc2 <- llmnl_int_C_v2(beta = beta, Obs = mnl_sample, n_cat = n_cat)
all.equal(c(xr, xr2), c(xc, xc2))
TRUE
</code>```

well that's a relief.

Performance:

I'll use microbenchmark to illustrate the performance. The optimized functions are fast, so I'll run the functions 1e5 times to reduce the effect of the garbage collector

```<code>microbenchmark("llmml_int_R" = llmnl_int(beta = beta, Obs = mnl_sample, n_cat = n_cat),
               "llmml_int_C" = llmnl_int_C(beta = beta, Obs = mnl_sample, n_cat = n_cat),
               "llmnl_int_R_v2" = llmnl_int_R_v2(beta = beta, Obs = mnl_sample, n_cat = n_cat),
               "llmml_int_C_v2" = llmnl_int_C_v2(beta = beta, Obs = mnl_sample, n_cat = n_cat),
               times = 1e5)
#Output:
#Unit: microseconds
#           expr     min      lq       mean  median      uq        max neval
#    llmml_int_R 202.701 206.801 288.219673 227.601 334.301  57368.902 1e+05
#    llmml_int_C 250.101 252.802 342.190342 272.001 399.251 112459.601 1e+05
# llmnl_int_R_v2   4.800   5.601   8.930027   6.401   9.702   5232.001 1e+05
# llmml_int_C_v2   5.100   5.801   8.834646   6.700  10.101   7154.901 1e+05
</code>```

Here we see the same result as before. Now the new functions are roughly 35x faster (R) and 40x faster (Cpp) compared to their first counter-parts. Interestingly enough the optimized R function is still very slightly (0.3 ms or 4 %) faster than my optimized Cpp function. My best bet here is that there is some overhead from the Rcpp package, and if this was removed the two would be identical or the R.

Similarly we can check performance using Optim.

```<code>microbenchmark("llmnl_int" = optim(beta, llmnl_int, Obs = mnl_sample,
                                   n_cat = n_cat, method = "BFGS", hessian = F,
                                   control = list(fnscale = -1)),
               "llmnl_int_C" = optim(beta, llmnl_int_C, Obs = mnl_sample,
                                     n_cat = n_cat, method = "BFGS", hessian = F,
                                     control = list(fnscale = -1)),
               "llmnl_int_R_v2" = optim(beta, llmnl_int_R_v2, Obs = mnl_sample,
                                     n_cat = n_cat, method = "BFGS", hessian = F,
                                     control = list(fnscale = -1)),
               "llmnl_int_C_v2" = optim(beta, llmnl_int_C_v2, Obs = mnl_sample,
                                     n_cat = n_cat, method = "BFGS", hessian = F,
                                     control = list(fnscale = -1)),
               times = 1e3)
#Output:
#Unit: microseconds
#           expr       min        lq      mean    median         uq      max neval
#      llmnl_int 29541.301 53156.801 70304.446 76753.851  83528.101 196415.5  1000
#    llmnl_int_C 36879.501 59981.901 83134.218 92419.551 100208.451 190099.1  1000
# llmnl_int_R_v2   667.802  1253.452  1962.875  1585.101   1984.151  22718.3  1000
# llmnl_int_C_v2   704.401  1248.200  1983.247  1671.151   2033.401  11540.3  1000
</code>```

Once again the result is the same.

Conclusion:

As a short conclusion it is worth noting that this is one example, where converting your code to Rcpp is not really worth the trouble. This is not always the case, but often it is worth taking a second look at your function, to see if there are areas of your code, where unnecessary calculations are performed. Especially in situations where one uses buildin vectorized functions, it is often not worth the time to convert code to Rcpp. More often one can see great improvements if one uses for-loops with code that cant easily be vectorized in order to remove the for-loop.

Body:
I am currently working on a Bayesian method that requires multiple steps of optimisation of a multinomial logit model per iteration. I am using optim() to perform those optimisations, and an objective function written in R. A profiling revealed that optim() is the main bottleneck.

After digging around, I found this question in which they suggest that recoding the objective function with Rcpp could speed up the process. I followed the suggestion and recoded my objective function with Rcpp, but it ended up being slower (about two times slower!).

This was my first time with Rcpp (or anything related to C++) and I was not able to find a way of vectorising the code. Any idea how to make it faster?

Tl;dr: Current implementation of function in Rcpp is not as fast as vectorised R; how to make it faster?

A reproducible example:

Define objective functions in R and Rcpp: log-likelihood of an intercept only multinomial model

library(Rcpp)
library(microbenchmark)

llmnl_int <- function(beta, Obs, n_cat) {
  n_Obs     <- length(Obs)
  Xint      <- matrix(c(0, beta), byrow = T, ncol = n_cat, nrow = n_Obs)
  ind       <- cbind(c(1:n_Obs), Obs)
  Xby       <- Xint[ind]
  Xint      <- exp(Xint)
  iota      <- c(rep(1, (n_cat)))
  denom     <- log(Xint %*% iota)
  return(sum(Xby - denom))
}

cppFunction('double llmnl_int_C(NumericVector beta, NumericVector Obs, int n_cat) {

    int n_Obs = Obs.size();

    NumericVector betas = (beta.size()+1);
    for (int i = 1; i < n_cat; i++) {
        betas[i] = beta[i-1];
    };

    NumericVector Xby = (n_Obs);
    NumericMatrix Xint(n_Obs, n_cat);
    NumericVector denom = (n_Obs);
    for (int i = 0; i < Xby.size(); i++) {
        Xint(i,_) = betas;
        Xby[i] = Xint(i,Obs[i]-1.0);
        Xint(i,_) = exp(Xint(i,_));
        denom[i] = log(sum(Xint(i,_)));
    };

    return sum(Xby - denom);
}')

Compare their efficiency:

## Draw sample from a multinomial distribution
set.seed(2020)
mnl_sample <- t(rmultinom(n = 1000,size = 1,prob = c(0.3, 0.4, 0.2, 0.1)))
mnl_sample <- apply(mnl_sample,1,function(r) which(r == 1))

## Benchmarking
microbenchmark("llmml_int" = llmnl_int(beta = c(4,2,1), Obs = mnl_sample, n_cat = 4),
               "llmml_int_C" = llmnl_int_C(beta = c(4,2,1), Obs = mnl_sample, n_cat = 4),
               times = 100)
## Results
# Unit: microseconds
#         expr     min       lq     mean   median       uq     max neval
#    llmnl_int  76.809  78.6615  81.9677  79.7485  82.8495 124.295   100
#  llmnl_int_C 155.405 157.7790 161.7677 159.2200 161.5805 201.655   100

Now calling them in optim:

## Benchmarking with optim
microbenchmark("llmnl_int" = optim(c(4,2,1), llmnl_int, Obs = mnl_sample, n_cat = 4, method = "BFGS", hessian = T, control = list(fnscale = -1)),
               "llmnl_int_C" = optim(c(4,2,1), llmnl_int_C, Obs = mnl_sample, n_cat = 4, method = "BFGS", hessian = T, control = list(fnscale = -1)),
               times = 100)
## Results
# Unit: milliseconds
#         expr      min       lq     mean   median       uq      max neval
#    llmnl_int 12.49163 13.26338 15.74517 14.12413 18.35461 26.58235   100
#  llmnl_int_C 25.57419 25.97413 28.05984 26.34231 30.44012 37.13442   100

I was somewhat surprised that the vectorised implementation in R was faster. Implementing a more efficient version in Rcpp (say, with RcppArmadillo?) can produce any gains? Is it a better idea to recode everything in Rcpp using a C++ optimiser?

Body:
In general if you are able to use vectorized functions, you will find it to be (almost) as fast as running your code directly in Rcpp. This is because many vectorized functions in R (almost all vectorized functions in Base R) are written in C, Cpp or Fortran and as such there is often little to gain.

That said, there are improvements to gain both in your R and Rcpp code. Optimization comes from carefully studying the code, and removing unnecessary steps (memory assignment, sums, etc.).

Lets start with the Rcpp code optimization.

In your case the main optimization is to remove unnecessary matrix and vector calculations. The code is in essence

Shift beta

calculate the log of the sum of exp(shift beta) [log-sum-exp]

use Obs as an index for the shifted beta and sum over all the probabilities

substract the log-sum-exp

Using this observation we can reduce your code to 2 for-loops. Note that sum is simply another for-loop (more or less: for(i = 0; i < max; i++){ sum += x }) so avoiding the sums can speed up ones code further (in most situations this is unnecessary optimization!). In addition your input Obs is an integer vector, and we can further optimize the code by using the IntegerVector type to avoid casting the double elements to integer values (Credit to Ralf Stubner's answer).

cppFunction('double llmnl_int_C_v2(NumericVector beta, IntegerVector Obs, int n_cat)
 {

    int n_Obs = Obs.size();

    NumericVector betas = (beta.size()+1);
    //1: shift beta
    for (int i = 1; i < n_cat; i++) {
        betas[i] = beta[i-1];
    };
    //2: Calculate log sum only once:
    double expBetas_log_sum = log(sum(exp(betas)));
    // pre allocate sum
    double ll_sum = 0;

    //3: Use n_Obs, to avoid calling Xby.size() every time
    for (int i = 0; i < n_Obs; i++) {
        ll_sum += betas(Obs[i] - 1.0) ;
    };
    //4: Use that we know denom is the same for all I:
    ll_sum = ll_sum - expBetas_log_sum * n_Obs;
    return ll_sum;
}')

Note that I have removed quite a few memory allocations and removed unnecessary calculations in the for-loop. Also i have used that denom is the same for all iterations and simply multiplied for the final result.

We can perform similar optimizations in your R-code, which results in the below function:

llmnl_int_R_v2 <- function(beta, Obs, n_cat) {
    n_Obs <- length(Obs)
    betas <- c(0, beta)
    #note: denom = log(sum(exp(betas)))
    sum(betas[Obs]) - log(sum(exp(betas))) * n_Obs
}

Note the complexity of the function has been drastically reduced making it simpler for others to read. Just to be sure that I haven't messed up in the code somewhere let's check that they return the same results:

set.seed(2020)
mnl_sample <- t(rmultinom(n = 1000,size = 1,prob = c(0.3, 0.4, 0.2, 0.1)))
mnl_sample <- apply(mnl_sample,1,function(r) which(r == 1))

beta = c(4,2,1)
Obs = mnl_sample
n_cat = 4
xr <- llmnl_int(beta = beta, Obs = mnl_sample, n_cat = n_cat)
xr2 <- llmnl_int_R_v2(beta = beta, Obs = mnl_sample, n_cat = n_cat)
xc <- llmnl_int_C(beta = beta, Obs = mnl_sample, n_cat = n_cat)
xc2 <- llmnl_int_C_v2(beta = beta, Obs = mnl_sample, n_cat = n_cat)
all.equal(c(xr, xr2), c(xc, xc2))
TRUE

well that's a relief.

Performance:

I'll use microbenchmark to illustrate the performance. The optimized functions are fast, so I'll run the functions 1e5 times to reduce the effect of the garbage collector

microbenchmark("llmml_int_R" = llmnl_int(beta = beta, Obs = mnl_sample, n_cat = n_cat),
               "llmml_int_C" = llmnl_int_C(beta = beta, Obs = mnl_sample, n_cat = n_cat),
               "llmnl_int_R_v2" = llmnl_int_R_v2(beta = beta, Obs = mnl_sample, n_cat = n_cat),
               "llmml_int_C_v2" = llmnl_int_C_v2(beta = beta, Obs = mnl_sample, n_cat = n_cat),
               times = 1e5)
#Output:
#Unit: microseconds
#           expr     min      lq       mean  median      uq        max neval
#    llmml_int_R 202.701 206.801 288.219673 227.601 334.301  57368.902 1e+05
#    llmml_int_C 250.101 252.802 342.190342 272.001 399.251 112459.601 1e+05
# llmnl_int_R_v2   4.800   5.601   8.930027   6.401   9.702   5232.001 1e+05
# llmml_int_C_v2   5.100   5.801   8.834646   6.700  10.101   7154.901 1e+05

Here we see the same result as before. Now the new functions are roughly 35x faster (R) and 40x faster (Cpp) compared to their first counter-parts. Interestingly enough the optimized R function is still very slightly (0.3 ms or 4 %) faster than my optimized Cpp function. My best bet here is that there is some overhead from the Rcpp package, and if this was removed the two would be identical or the R.

Similarly we can check performance using Optim.

microbenchmark("llmnl_int" = optim(beta, llmnl_int, Obs = mnl_sample,
                                   n_cat = n_cat, method = "BFGS", hessian = F,
                                   control = list(fnscale = -1)),
               "llmnl_int_C" = optim(beta, llmnl_int_C, Obs = mnl_sample,
                                     n_cat = n_cat, method = "BFGS", hessian = F,
                                     control = list(fnscale = -1)),
               "llmnl_int_R_v2" = optim(beta, llmnl_int_R_v2, Obs = mnl_sample,
                                     n_cat = n_cat, method = "BFGS", hessian = F,
                                     control = list(fnscale = -1)),
               "llmnl_int_C_v2" = optim(beta, llmnl_int_C_v2, Obs = mnl_sample,
                                     n_cat = n_cat, method = "BFGS", hessian = F,
                                     control = list(fnscale = -1)),
               times = 1e3)
#Output:
#Unit: microseconds
#           expr       min        lq      mean    median         uq      max neval
#      llmnl_int 29541.301 53156.801 70304.446 76753.851  83528.101 196415.5  1000
#    llmnl_int_C 36879.501 59981.901 83134.218 92419.551 100208.451 190099.1  1000
# llmnl_int_R_v2   667.802  1253.452  1962.875  1585.101   1984.151  22718.3  1000
# llmnl_int_C_v2   704.401  1248.200  1983.247  1671.151   2033.401  11540.3  1000

Once again the result is the same.

Conclusion:

As a short conclusion it is worth noting that this is one example, where converting your code to Rcpp is not really worth the trouble. This is not always the case, but often it is worth taking a second look at your function, to see if there are areas of your code, where unnecessary calculations are performed. Especially in situations where one uses buildin vectorized functions, it is often not worth the time to convert code to Rcpp. More often one can see great improvements if one uses for-loops with code that cant easily be vectorized in order to remove the for-loop.


问:
DRF - add argument to Model.save(...)
I have an Invoice model and there is a recalculate argument in the overridden Invoice.save() method.

I want Invoice to be recalculated always except when it's created using it's serializer.

Is it possible?

Serializers use create so I'm not sure how to do that. (It's a ModelSerializer)

答:
You can create a mixin to override the create method and pass in the recalculate argument, without calling super().create(), then use it in your serializer: e.g. InvoiceSerializer(CreateMixin, serlializers.ModelSerializer)

```<code>class CreateMixin:
    def create(self, validated_data, recalculate):
        raise_errors_on_nested_writes('create', self, validated_data)

        ModelClass = self.Meta.model

        info = model_meta.get_field_info(ModelClass)
        many_to_many = {}
        for field_name, relation_info in info.relations.items():
            if relation_info.to_many and (field_name in validated_data):
                many_to_many[field_name] = validated_data.pop(field_name)

        try:
            instance = ModelClass(**validated_data)
            '''
            your custom logic with recalculate argument
            '''

        except TypeError:
            tb = traceback.format_exc()
            msg = (
                    'Got a `TypeError` when calling `%s.%s.create()`. '
                    'This may be because you have a writable field on the '
                    'serializer class that is not a valid argument to '
                    '`%s.%s.create()`. You may need to make the field '
                    'read-only, or override the %s.create() method to handle '
                    'this correctly.\nOriginal exception was:\n %s' %
                    (
                        ModelClass.__name__,
                        ModelClass._default_manager.name,
                        ModelClass.__name__,
                        ModelClass._default_manager.name,
                        self.__class__.__name__,
                        tb
                    )
            )
            raise TypeError(msg)

        # Save many-to-many relationships after the instance is created.
        if many_to_many:
            for field_name, value in many_to_many.items():
                field = getattr(instance, field_name)
                field.set(value)

        return instance
</code>```

Title: DRF - add argument to Model.save(...)

Body:
You can create a mixin to override the create method and pass in the recalculate argument, without calling super().create(), then use it in your serializer: e.g. InvoiceSerializer(CreateMixin, serlializers.ModelSerializer)

class CreateMixin:
    def create(self, validated_data, recalculate):
        raise_errors_on_nested_writes('create', self, validated_data)

        ModelClass = self.Meta.model

        info = model_meta.get_field_info(ModelClass)
        many_to_many = {}
        for field_name, relation_info in info.relations.items():
            if relation_info.to_many and (field_name in validated_data):
                many_to_many[field_name] = validated_data.pop(field_name)

        try:
            instance = ModelClass(**validated_data)
            '''
            your custom logic with recalculate argument
            '''

        except TypeError:
            tb = traceback.format_exc()
            msg = (
                    'Got a `TypeError` when calling `%s.%s.create()`. '
                    'This may be because you have a writable field on the '
                    'serializer class that is not a valid argument to '
                    '`%s.%s.create()`. You may need to make the field '
                    'read-only, or override the %s.create() method to handle '
                    'this correctly.\nOriginal exception was:\n %s' %
                    (
                        ModelClass.__name__,
                        ModelClass._default_manager.name,
                        ModelClass.__name__,
                        ModelClass._default_manager.name,
                        self.__class__.__name__,
                        tb
                    )
            )
            raise TypeError(msg)

        # Save many-to-many relationships after the instance is created.
        if many_to_many:
            for field_name, value in many_to_many.items():
                field = getattr(instance, field_name)
                field.set(value)

        return instance


问:
Round selection of location on the MKMapView
I want to implement a circular selection (with center and radius) on the MKMapView like it looks on the screenshot below.
Should be possible to move the selection pulling the green pointer and change circle radius pulling the dark gray pointer.

What the best way to implement it? Maybe there's already some solution?

I would be grateful for any help.

答:
You can add a UISlider to your map and update MKCircle radius on the Value Changed action.

Please take a look how to use MKCircle here - How to create MKCircle in Swift?


问:
load a php image using src
Is it possible to load a image using:

```<code><img src="image.php?image_id=1">
</code>```

?

for image.php:

```<code>$image_id = $_GET['image_id'];
echo "image".$image_id.".png";
</code>```

答:
one liner....</p>

```<code>echo (file_exists($_GET['image_id'])) ? header("Content-Type:image/png").readfile($_GET['image_id']).die() : false;
</code>```

Title: load a php image using src

Body:
Is it possible to load a image using:

?

for image.php:

$image_id = $_GET['image_id'];
echo "image".$image_id.".png";

Body:
one liner....

echo (file_exists($_GET['image_id'])) ? header("Content-Type:image/png").readfile($_GET['image_id']).die() : false;


问:
Fix HTML header and button tag not updating text
I am trying to write some code that updates a header tag and a button tag. However, when I use the method .text(); it does not work. So I looked up the proper way to do it via other stack overflow questions, and I see basically the same thing. Everyone is telling me to use .text() or .html(). So I am really confused on why it is not working. I am not sure if it has anything to do with values already in the tag.

HTML:

```<code><div class="contents">
  <div class="card text-center myCard">
    <div class="card-header"></div>
    <div class="card-body">
      <h5 class="card-title"></h5>
      <p class="card-text"></p>
      <button type="button" class="btn btn-primary ttBtn"></button>
    </div>
    <div class="card-footer text-muted"></div>
  </div>
</div>
</code>```

jQuery:

```<code>$(".eBtn").on(
                    "click",
                    function(event) {

                        event.preventDefault();

                        var href = $(this).attr('href');
                        console.log(href);

                        $.get(href, function(ary2, status) {
                            $("#displayAppName").val(ary2.appname);
                            $("#appcode").val(ary2.appcode);
                            $("#editStatus").val(ary2.status);

                            if (ary2.mapstatus == "" || ary2.mapstatus == null) {
                                mapBool = true;
                                $("#mapStatus").val("");
                                $("#createBtn").val('Create');
                                $('#modalCreateBtn').attr(
                                        'href',
                                        '/create?currentAppcode='
                                                + ary2.appcode
                                                + "&currentAcro="
                                                + ary2.acronym
                                                + "&currentAppname="
                                                + ary2.appname);

                                console.log("Card Create: " + $(".card-title").val());

                            } else {
                                $("#mapStatus").val("Mapped");
                                $("#createBtn").val('Edit');
                                $('#modalCreateBtn').attr(
                                        'href',
                                        '/edit?currentAppcode='
                                                + ary2.appcode
                                                + "&currentAcro="
                                                + ary2.acronym);

                                  mapBool = true;

                                console.log("Card Edit: " + $(".card-title").val());

                            }

                        });

                          console.log("Main Boolean : "  + this.mapBool)
                          console.log("Main Boolean : "  + mapBool)
                            if(mapBool){
                                 $(".card-title").text("Application Mapped!");
                                 $(".card-text").text("Continue to view application");
                                $(".ttBtn").text("New Mapping after");
                            }

                        $("#exampleModal").modal();

                    });
</code>```

jQuery Change HTML:

```<code>  $(".card-title").text("Application Mapped!");
  $(".card-text").text("Continue to view application");
  $(".ttBtn").text("Continue");
</code>```

答:
Created variable ary2. Hope this help you.

var ary2 = [];
if (ary2.mapstatus == "" || ary2.mapstatus == null) {
  $("#mapStatus").val("");
  $("#createBtn").val('Create');
  $('#modalCreateBtn').attr(
    'href',
    '/create?currentAppcode=' +
    ary2.code +
    "&currentAcro=" +
    ary2.acro +
    "&currentAppname=" +
    ary2.name);

  $(".card-title").text("Application Mapped!");
  $(".card-text").text("Continue to view application");
  $(".ttBtn").html("Continue");

} else {
  $("#mapStatus").val("Mapped");
  $("#createBtn").val('Edit');
  $('#modalCreateBtn').attr(
    'href',
    '/edit?currentAppcode=' +
    ary2.code +
    "&currentAcro=" +
    ary2.acro);

}
$(document).ready(function() {
  $(".card-title").text("Application Mapped!");
  $(".card-text").text("Continue to view application");
  $(".ttBtn").html("Continue");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contents">
  <div class="card text-center myCard">
    <div class="card-header"></div>
    <div class="card-body">
      <h5 class="card-title">Application not mapped!</h5>
      <p class="card-text">Click the "New Tier" button to begin mapping.
      </p>
      <button type="button" class="btn btn-primary ttBtn">New
        Mapping</button>
    </div>
    <div class="card-footer text-muted"></div>
  </div>
</div></code>```

Body:
I am trying to write some code that updates a header tag and a button tag. However, when I use the method .text(); it does not work. So I looked up the proper way to do it via other stack overflow questions, and I see basically the same thing. Everyone is telling me to use .text() or .html(). So I am really confused on why it is not working. I am not sure if it has anything to do with values already in the tag.

HTML:

      <button type="button" class="btn btn-primary ttBtn"></button>

jQuery:

$(".eBtn").on(
                    "click",
                    function(event) {

                        event.preventDefault();

                        var href = $(this).attr('href');
                        console.log(href);

                        $.get(href, function(ary2, status) {
                            $("#displayAppName").val(ary2.appname);
                            $("#appcode").val(ary2.appcode);
                            $("#editStatus").val(ary2.status);

                            if (ary2.mapstatus == "" || ary2.mapstatus == null) {
                                mapBool = true;
                                $("#mapStatus").val("");
                                $("#createBtn").val('Create');
                                $('#modalCreateBtn').attr(
                                        'href',
                                        '/create?currentAppcode='
                                                + ary2.appcode
                                                + "&currentAcro="
                                                + ary2.acronym
                                                + "&currentAppname="
                                                + ary2.appname);

                                console.log("Card Create: " + $(".card-title").val());

                            } else {
                                $("#mapStatus").val("Mapped");
                                $("#createBtn").val('Edit');
                                $('#modalCreateBtn').attr(
                                        'href',
                                        '/edit?currentAppcode='
                                                + ary2.appcode
                                                + "&currentAcro="
                                                + ary2.acronym);

                                  mapBool = true;

                                console.log("Card Edit: " + $(".card-title").val());

                            }

                        });

                          console.log("Main Boolean : "  + this.mapBool)
                          console.log("Main Boolean : "  + mapBool)
                            if(mapBool){
                                 $(".card-title").text("Application Mapped!");
                                 $(".card-text").text("Continue to view application");
                                $(".ttBtn").text("New Mapping after");
                            }

                        $("#exampleModal").modal();

                    });

jQuery Change HTML:

  $(".card-title").text("Application Mapped!");
  $(".card-text").text("Continue to view application");
  $(".ttBtn").text("Continue");

Body:
Created variable ary2. Hope this help you.

var ary2 = [];
if (ary2.mapstatus == "" || ary2.mapstatus == null) {
  $("#mapStatus").val("");
  $("#createBtn").val('Create');
  $('#modalCreateBtn').attr(
    'href',
    '/create?currentAppcode=' +
    ary2.code +
    "&currentAcro=" +
    ary2.acro +
    "&currentAppname=" +
    ary2.name);

  $(".card-title").text("Application Mapped!");
  $(".card-text").text("Continue to view application");
  $(".ttBtn").html("Continue");

} else {
  $("#mapStatus").val("Mapped");
  $("#createBtn").val('Edit');
  $('#modalCreateBtn').attr(
    'href',
    '/edit?currentAppcode=' +
    ary2.code +
    "&currentAcro=" +
    ary2.acro);

}
$(document).ready(function() {
  $(".card-title").text("Application Mapped!");
  $(".card-text").text("Continue to view application");
  $(".ttBtn").html("Continue");
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contents">
  <div class="card text-center myCard">
    <div class="card-header"></div>
    <div class="card-body">
      <h5 class="card-title">Application not mapped!</h5>
      <p class="card-text">Click the "New Tier" button to begin mapping.
      </p>
      <button type="button" class="btn btn-primary ttBtn">New
        Mapping</button>
    </div>
    <div class="card-footer text-muted"></div>
  </div>
</div>


问:
Setting a maximum possible value to a variable C++
it's supposed to be an easy question, but i couldnt find the answer on google. So, how do i assign a maximum possible value to a variable?
So i want my variable to be no more than 10 as apossible value no matter what</p>

```<code>int example;
example = ?;
</code>```

答:
You might create a custom class to handle your needs, something like:

```<code>template <int Min, int Max>
class BoundedValue
{
public:
    BoundedValue(int value = Min) : mValue(Min) { set_value(value); }

    int get_value() const { return mValue; }
    void set_value(int value) {
        if (value < Min || Max < value) {
            throw std::out_of_range("!"); // Or other error handling as clamping
            // value = std::clamp(value, Min, Max);
        }
        mValue = value;
    }

    BoundedValue& operator= (int value) { set_value(value); }

    BoundedValue& operator ++() { set_value(mValue + 1); return *this; }
    BoundedValue operator ++(int) { auto tmp = *this; ++*this; return tmp; }

    // other convenient functions

    operator int() const { return mValue; }

private:
    int mValue = Min;
};
</code>```

And then use it:

```<code>BoundedValue<0, 10> example;

++example;
example = 11; // "Error"
</code>```

Body:
it's supposed to be an easy question, but i couldnt find the answer on google. So, how do i assign a maximum possible value to a variable?
So i want my variable to be no more than 10 as apossible value no matter what

int example;
example = ?;

Body:
You might create a custom class to handle your needs, something like:

template <int Min, int Max>
class BoundedValue
{
public:
    BoundedValue(int value = Min) : mValue(Min) { set_value(value); }

    int get_value() const { return mValue; }
    void set_value(int value) {
        if (value < Min || Max < value) {
            throw std::out_of_range("!"); // Or other error handling as clamping
            // value = std::clamp(value, Min, Max);
        }
        mValue = value;
    }

    BoundedValue& operator= (int value) { set_value(value); }

    BoundedValue& operator ++() { set_value(mValue + 1); return *this; }
    BoundedValue operator ++(int) { auto tmp = *this; ++*this; return tmp; }

    // other convenient functions

    operator int() const { return mValue; }

private:
    int mValue = Min;
};

And then use it:

BoundedValue<0, 10> example;

++example;
example = 11; // "Error"


问:
How can I get the PowerShell ISE to do syntax highlighting on files with a custom extension?
I'd like to start using a custom extension for some of my Powershell scripts, but when I drag them into the PowerShell ISE, they are treated as plaintext, and I don't get any syntax highlighting.  Is there anything I can do to get the ISE to recognize my custom file extension as a PowerShell script?</p>

答: For me, the PS script file extension was inadvertently .ps, when I renamed it to have .ps1 extension, all the syntax highlighting revived.  Hope this helps others.


问:
number of kafka topic partitons and number of different keys in data
I want to use key/value pattern writing to Kafka in order to keep the same order of data writing while reading it.
My question is should the number of partitions in the topic be equal to the number of different keys in the incoming data.
I already know that with the key/value pattern data having the same key will go to the same partition. </p>

<p>Hence if number of partitions is not equal to the number of different keys in data, we can have data having different keys in the same partition?  In this case how data order is kept? </p>

答:
My question is should the number of partitions in the topic be equal to the number of different keys in the incoming data.

I don't think that this is generally a good idea. It totally depends on the data you are processing. In case you have a fixed amount of keys (such as female, male and diverse) it might make sense. However, even then you need to be careful as the this could lead to an unbalance of data load over the broker as there might be less diverse. So you could end up having most of the data in one partition whereas the other partition(s) would be left empty. In general, the amount of partitions should be adjusted to your throughput requirements.

Hence if number of partitions is not equal to the number of different keys in data, we can have data having different keys in the same partition? In this case how data order is kept?

Yes, you could end up having different key in the same partition. Then the ordering is kept for this particular partition but not guaranteed in the topic overall.So assume, you have the keys A, B, and C and a topic with two partitions. A and C goes to the first partition and B is stored in the second partition. If data is flowing like this:
A/V1, A/V2, B/V1, C/V1, B/V2

Then your partitions will be filled like this:

partition0: A/V1, A/V2, C/V1

partition1: B/V1, B/V2

When consuming this topic it is not clear how the ordering between A and C messages are in relation to B messages. However, it is always guaranteed that the message A/V1 is consumed before A/V2, A/V2 before C/V1, and B/V1 before B/V2.

If you are looking for a more flexible way of directing your messages into partitions you can also think of writing a custom partitioner.

Body:
I want to use key/value pattern writing to Kafka in order to keep the same order of data writing while reading it.
My question is should the number of partitions in the topic be equal to the number of different keys in the incoming data.
I already know that with the key/value pattern data having the same key will go to the same partition.

Hence if number of partitions is not equal to the number of different keys in data, we can have data having different keys in the same partition?  In this case how data order is kept?


问:
Is there a way to apply different configmap for each pod generated by damonset?
I am using filebeat as a daemonset and I would like each generated pod to export to a single port for the logstash.

Is there an approach to be used for this?

答: No. You cannot provide different configmap to the pods of same daemonset or deployment. If you want each of your pods of daemonset to have different configurations then you can mount some local-volume (using hostpath) so that all the pods will take configuration from that path and that can be different on each node. Or you need to deploy different daemonsets with different configmaps and select different nodes for each of them. </p>


问:
Microsft graph api query not showing required result
I am trying to run this query, it runs fine but it is not returning the required output.it shows all events with different startDateTime rather than required. What I am doing wrong? I am running this query in Graph explorer.

https://graph.microsoft.com/v1.0/me/planner/tasks?$filter=startDateTime
  eq 2017-09-08T00:00:00Z

答:
Make a call to https://graph.microsoft.com/v1.0/me/planner/tasks

Use a json parser to parse the output and look for the startDateTime attribute and compare to the dateTime you are interested in.

Please do a +1 on this request here. https://microsoftgraph.uservoice.com/forums/920506-microsoft-graph-feature-requests/suggestions/38542351-graph-api-planner-api-odata-support-filter