问:
What changes I should make change the get to filter?
I am doing a project for my college work.
In that, I need to change a function. That function is giving error saying multiple objects returned. The function works well if there is only one object to return. But I need to change it to return it to return all the objects. So what changes do I need to do. I am attaching the function code. Pls provide the code to modify also. I am just beginner in coding. Thanks

I am using Pycharm, Django and. MySQL to do my project

The problem is obj=booking.objects.get is returning multiple objects and it can't displayed by the function . So I need to get the code to display all objects. I understood that using filter() will solve the problem. But I don't know what are the changes to make and where should I make it. So pls help. I am just a beginner.

```<code>    def vpay(request) :

        b=request.session['uid']
        ob=TurfManager.objects.get(t_id=b)
        bb=ob.tf_id
        obj=Booking.objects.get(tf_id=bb)
        nn=obj.b_id

        o = Payment.objects.filter(book_id=nn)
        context = {
            'obval': o,
        }
</code>```
```<code>class Payment(models.Model):
    p_id = models.AutoField(primary_key=True)
    # u_id = models.IntegerField()
    u=models.ForeignKey(User,to_field='u_id',on_delete=models.CASCADE)
    payment = models.CharField(max_length=50)
    # book_id = models.IntegerField()
    book=models.ForeignKey(Booking,to_field='b_id',on_delete=models.CASCADE)
    upi_id = models.CharField(max_length=50)
</code>```
```<code>class Booking(models.Model):
    b_id = models.AutoField(primary_key=True)
    # u_id = models.IntegerField()
    u=models.ForeignKey(User,to_field='u_id',on_delete=models.CASCADE)
    # tf_id = models.IntegerField()
    tf = models.ForeignKey(TurfLocation, to_field='tf_id', on_delete=models.CASCADE)
    date = models.DateField()
    #timeslot_id = models.CharField(max_length=50)
    timeslot = models.ForeignKey(TimeSlot, to_field='timeslot_id', on_delete=models.CASCADE)
    status = models.CharField(max_length=50)
</code>```

答:
You can use filter as

```<code>    def vpay(request) :

        b = request.session['uid']
        ob = TurfManager.objects.get(t_id=b)
        obj = Booking.objects.filter(tf_id=ob.tf_id)
        o = Payment.objects.filter(book_id__in=obj)
        context = {
            'obval': o,
        }
</code>```

Body:
I am doing a project for my college work.
In that, I need to change a function. That function is giving error saying multiple objects returned. The function works well if there is only one object to return. But I need to change it to return it to return all the objects. So what changes do I need to do. I am attaching the function code. Pls provide the code to modify also. I am just beginner in coding. Thanks

I am using Pycharm, Django and. MySQL to do my project

The problem is obj=booking.objects.get is returning multiple objects and it can't displayed by the function . So I need to get the code to display all objects. I understood that using filter() will solve the problem. But I don't know what are the changes to make and where should I make it. So pls help. I am just a beginner.

    def vpay(request) :

        b=request.session['uid']
        ob=TurfManager.objects.get(t_id=b)
        bb=ob.tf_id
        obj=Booking.objects.get(tf_id=bb)
        nn=obj.b_id

        o = Payment.objects.filter(book_id=nn)
        context = {
            'obval': o,
        }

class Payment(models.Model):
    p_id = models.AutoField(primary_key=True)
    # u_id = models.IntegerField()
    u=models.ForeignKey(User,to_field='u_id',on_delete=models.CASCADE)
    payment = models.CharField(max_length=50)
    # book_id = models.IntegerField()
    book=models.ForeignKey(Booking,to_field='b_id',on_delete=models.CASCADE)
    upi_id = models.CharField(max_length=50)

class Booking(models.Model):
    b_id = models.AutoField(primary_key=True)
    # u_id = models.IntegerField()
    u=models.ForeignKey(User,to_field='u_id',on_delete=models.CASCADE)
    # tf_id = models.IntegerField()
    tf = models.ForeignKey(TurfLocation, to_field='tf_id', on_delete=models.CASCADE)
    date = models.DateField()
    #timeslot_id = models.CharField(max_length=50)
    timeslot = models.ForeignKey(TimeSlot, to_field='timeslot_id', on_delete=models.CASCADE)
    status = models.CharField(max_length=50)

Body:
You can use filter as

    def vpay(request) :

        b = request.session['uid']
        ob = TurfManager.objects.get(t_id=b)
        obj = Booking.objects.filter(tf_id=ob.tf_id)
        o = Payment.objects.filter(book_id__in=obj)
        context = {
            'obval': o,
        }


来源: stackexchange

问:
MYSQL how to update the ship amount for the order dates after 2015-03-30 15:22:31 to 15
I'm having trouble with this question: Write an UPDATE statement that modifies the Orders table. Change all ship amount for order dates after 2015-03-30 15:22:31 to 15.  If you get an error due to safe-update mode, you can add a LIMIT clause to update the first 100 rows of the table. (This should update all rows in the table.)

I've written it like this:

```<code>UPDATE orders
SET ship_amount = 15
WHERE order_date = 2015-03-30 15:22:31
LIMIT 100;
</code>```

but I'm getting an error in the where clause and I'm using the my_guitar_shop schema

答:
The date value 2015-03-30 15:22:31 should written under '' single cotes.

```<code>UPDATE order_details SET add_by_admin = 15 WHERE created_at > '2022-02-09 18:44:01' LIMIT 100
</code>```

eg.

```<code>UPDATE orders
SET ship_amount = 15
WHERE order_date > '2015-03-30 15:22:31'
LIMIT 100;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having trouble with this question: Write an UPDATE statement that modifies the Orders table. Change all ship amount for order dates after 2015-03-30 15:22:31 to 15.  If you get an error due to safe-update mode, you can add a LIMIT clause to update the first 100 rows of the table. (This should update all rows in the table.)

I've written it like this:

UPDATE orders
SET ship_amount = 15
WHERE order_date = 2015-03-30 15:22:31
LIMIT 100;

but I'm getting an error in the where clause and I'm using the my_guitar_shop schema

Body:
The date value 2015-03-30 15:22:31 should written under '' single cotes.

UPDATE order_details SET add_by_admin = 15 WHERE created_at > '2022-02-09 18:44:01' LIMIT 100

eg.

UPDATE orders
SET ship_amount = 15
WHERE order_date > '2015-03-30 15:22:31'
LIMIT 100;


问:
How to reset a Stack in a different Tab using React Navigation 6.x
i have bottom tab stack....in each stack there are either single screen or nested stack navigator.

Problem:

first tab - Home screen
second tab - MyDetailsStack(createStackNavigator)
- detailScreen1 (initialRoute)
- detailScreen2

Goal:
when user visits detail detailScreen2.... then goes back go homescreen and clicks back second tab....i need to reset the second tab to show initial route it is pointing which is detailScreen1.
At this moment what ever screen i left (that is detailScreen2) is shown.

Please check the expo for the problem.

https://snack.expo.dev/@rosnk/nested-route-reset-on-tabchange

Currently tried solution:

tried adding following code:

```<code><Tab.Screen
        name="MyDetailsTabStack"
        component={MyDetailsStack}
        options={{
          title: 'My Details',
          tabBarLabel: 'My Details',
        }}
        listeners={({ navigation, route }) => ({
          tabPress: (e) => {
            navigation.dispatch(
              CommonActions.reset({
                index: 1,
                routes: [
                  { name: 'DetailScreen1' },
                  {
                    name: 'DetailScreen2',
                  },
                ],
              })
            );
          },
        })}
      />
</code>```

tried solution reference to this stack suggestion:
How to reset a Stack in a different Tab using React Navigation 5.x

答:
I was also having this problem. I want to reset the navigation stack back to the first index when the user leaves the tab. I followed the reference in your link and from that, created my solution to the problem.

Using the useFocusEffect() described here, and after reading about the Navigation Lifecycle here, below is my solution that works for me.

```<code>const { reset } = useNavigation();
useFocusEffect(
  useCallback(() => {
    // If you want to do something when screen is focused
    return () => {
      // This is called when the screen is not focused
      // i.e. switched to a different tab or the hardware back button is pressed (Android)
      reset({ index: 0, routes: [{ name: "detailScreen1" }] });
    };
  }, []),
);
</code>```

Place this inside your detailScreen2 and it should reset back that stack navigators state whenever the user leaves the screen

Body:
i have bottom tab stack....in each stack there are either single screen or nested stack navigator.

Problem:

first tab - Home screen
second tab - MyDetailsStack(createStackNavigator)
- detailScreen1 (initialRoute)
- detailScreen2

Goal:
when user visits detail detailScreen2.... then goes back go homescreen and clicks back second tab....i need to reset the second tab to show initial route it is pointing which is detailScreen1.
At this moment what ever screen i left (that is detailScreen2) is shown.

Please check the expo for the problem.

https://snack.expo.dev/@rosnk/nested-route-reset-on-tabchange

Currently tried solution:

tried adding following code:

<Tab.Screen
        name="MyDetailsTabStack"
        component={MyDetailsStack}
        options={{
          title: 'My Details',
          tabBarLabel: 'My Details',
        }}
        listeners={({ navigation, route }) => ({
          tabPress: (e) => {
            navigation.dispatch(
              CommonActions.reset({
                index: 1,
                routes: [
                  { name: 'DetailScreen1' },
                  {
                    name: 'DetailScreen2',
                  },
                ],
              })
            );
          },
        })}
      />

tried solution reference to this stack suggestion:
How to reset a Stack in a different Tab using React Navigation 5.x

Body:
I was also having this problem. I want to reset the navigation stack back to the first index when the user leaves the tab. I followed the reference in your link and from that, created my solution to the problem.

Using the useFocusEffect() described here, and after reading about the Navigation Lifecycle here, below is my solution that works for me.

const { reset } = useNavigation();
useFocusEffect(
  useCallback(() => {
    // If you want to do something when screen is focused
    return () => {
      // This is called when the screen is not focused
      // i.e. switched to a different tab or the hardware back button is pressed (Android)
      reset({ index: 0, routes: [{ name: "detailScreen1" }] });
    };
  }, []),
);

Place this inside your detailScreen2 and it should reset back that stack navigators state whenever the user leaves the screen


问:
How can I separate 3 different information in a column?
For example, in the column I have, there is a line written 'Ser25Phe'. And I want to split the column HGVS.Consequence e.g. as 'Ser 25 Phe'...

```<code>HGVS.Consequence
           Met1?
           Met1?
           Met1?
         Ala2Glu
         Ala2Ala
         Asn3Asp
         Asn3Asn
         Gly4Trp
         Gly4Arg
         Ala6Glu
           AsAsp
         Arg9Arg
        Lys10Arg
        Lys10Lys
        LeullLeu
        Phe12Ser
        Phe12Cys
        lle13Leu
        lle13Val
        lle13Phe
        Thr15Pro
</code>```

答:
Another solution :

```<code>x <- c("Ala2Ala", "Asn3Asp", "Ser25Phe")
stringr::str_split(sub("(\\d+)", ";\\1;", x), ";", simplify = T)
</code>```

A different form of the solution :

```<code>sub("(\\d+)", " \\1 ", x)
</code>```

Body:
For example, in the column I have, there is a line written 'Ser25Phe'. And I want to split the column HGVS.Consequence e.g. as 'Ser 25 Phe'...

HGVS.Consequence
           Met1?
           Met1?
           Met1?
         Ala2Glu
         Ala2Ala
         Asn3Asp
         Asn3Asn
         Gly4Trp
         Gly4Arg
         Ala6Glu
           AsAsp
         Arg9Arg
        Lys10Arg
        Lys10Lys
        LeullLeu
        Phe12Ser
        Phe12Cys
        lle13Leu
        lle13Val
        lle13Phe
        Thr15Pro

Body:
Another solution :

x <- c("Ala2Ala", "Asn3Asp", "Ser25Phe")
stringr::str_split(sub("(\\d+)", ";\\1;", x), ";", simplify = T)

A different form of the solution :

sub("(\\d+)", " \\1 ", x)


问:
Sharing utility objects between domain and repository
I'm currently building a framework that uses a MySQL database. I can't use the MySQL implementation of the entity framework, so I'm trying to figure out the best way of generalising search and paging functionality.

The simplest solution would be to have repository methods with signatures such as:

```<code>IList<Blah> GetSomething(string _query,
                         int _page,
                         int _pageSize,
                         out int _numPages)
</code>```

but this seems slightly anti-OOD.

An idea I had was to create a utility dll with an ISearchParameter and an IPaging object that both the domain level and repository level could access, this would avoid having to recreate these two interfaces and implimentations of them in each domain and repository.

```<code>public interface ISearchParameters
{
    Direction Direction { get; set; }
    string DirectionField { get; set; }
    string Query { get; set; }
    IList<string> SearchFields { get; set; }
}

public interface IPaging
{
    int CurrentPage { get; set; }
    int PageSize { get; set; }
    int NumberOfPages { get; set; }

    int GetQueryPage();
}
</code>```

I'd usually map DTOs from the repositories to domain objects, but if both levels referenced this utility .dll, would it be bad design to pass ISearchParameter objects between these two levels without mapping? If so, are there any better solutions?

答:
Use the Repository Pattern to abstract away your interaction with data access layer.

Use an Inversion of Control container to create your repository, to avoid a reference from your domain to data access layer.

The data access can then hold a reference to your domain classes, or to the domain class factories--avoiding the need for DTOs (following the DRY principle).

Design your interfaces to be stateless.  When crossing layers (which may become tiers), think of services instead of objects.  This would prefer the simpler approach.

Avoid having a utility.dll. You really only need to share your repository interfaces between your domain and data access layer.  You could put those in your domain assembly, or better, a separate assembly.

ContentLicense: CC BY-SA 3.0

Body:
I'm currently building a framework that uses a MySQL database. I can't use the MySQL implementation of the entity framework, so I'm trying to figure out the best way of generalising search and paging functionality.

The simplest solution would be to have repository methods with signatures such as:

IList<Blah> GetSomething(string _query,
                         int _page,
                         int _pageSize,
                         out int _numPages)

but this seems slightly anti-OOD.

An idea I had was to create a utility dll with an ISearchParameter and an IPaging object that both the domain level and repository level could access, this would avoid having to recreate these two interfaces and implimentations of them in each domain and repository.

public interface ISearchParameters
{
    Direction Direction { get; set; }
    string DirectionField { get; set; }
    string Query { get; set; }
    IList<string> SearchFields { get; set; }
}

public interface IPaging
{
    int CurrentPage { get; set; }
    int PageSize { get; set; }
    int NumberOfPages { get; set; }

    int GetQueryPage();
}

I'd usually map DTOs from the repositories to domain objects, but if both levels referenced this utility .dll, would it be bad design to pass ISearchParameter objects between these two levels without mapping? If so, are there any better solutions?


问:
Javascript / React - Remove specific item from Local Storage on click when rendered in another component
I have a React application (like Netflix) that displays movies thumbnails on the homepage.

When you click on a thumbnail, a modal window appears where you can click on a button to add the movie to your Watchlist. These movies will be saved in local storage and if you go to the component "Watchlist", you can see all the favorite movies displayed.

Here is the code that handles the click (this function is stored in the Context) (I don't use useState because a re-render would trigger a change in the background of the app):

```<code>     const storageArray = [];

      const handleWatchlist = (objectData) => {
        let index = storageArray.indexOf(objectData);

        if (index === -1) {
          storageArray.push(objectData);
        } else {
          storageArray.splice(index, 1);
        }
        localStorage.setItem('currentWatchlist', JSON.stringify(storageArray));
        const retrieveData = JSON.parse(localStorage.getItem('currentWatchlist'));
        console.log(retrieveData);
      };
</code>```

It works perfectly fine on the homepage. HOWEVER, in the watchlist component, if I click on a thumbnails, and then click on the button to remove the item from the storage, here is what happens:

Example: 1 movie stored in localStorage, before I click:

Inside of the watchlist component, after I click on the button, to remove it from the storage and the component:

When I click on the button, instead of removing it the element, it doesn't consider it a duplicate and so add a new object to the Local Storage (which is removed if I click again).

How can I make sure that when I click on the favorite button in the Watchlist component, the storage is updated correctly and the movie removed from the component?

Thank you for your help.

答:
You're starting with an empty array:

```<code>const storageArray = [];
</code>```

And then check if the objectData is in the array or not with:

```<code>storageArray.indexOf(objectData);
</code>```

This will never find the existing item in the localStorage because you never read from localStorage. What you need to do is, when handleWatchlist is called:

Read from the localStorage and parse to a list

Find an existing item within that list by a unique key from objectData

If it's there, remove it

if not, add it

It'll be something like:

```<code>const handleWatchlist = (objectData) => {
  let storageArray = JSON.parse(localStorage.getItem("currentWatchlist"));
  let existingItem = storageArray.find(item => item.id === objectData.id);

  if (existingItem) {
    let result = storageArray.filter(item => item.id !== objectData.id);
  } else {
    let result = [...storageArray, objectData];
  }
  localStorage.setItem("currentWatchlist", JSON.stringify(result));
};
</code>```

Body:
I have a React application (like Netflix) that displays movies thumbnails on the homepage.

When you click on a thumbnail, a modal window appears where you can click on a button to add the movie to your Watchlist. These movies will be saved in local storage and if you go to the component "Watchlist", you can see all the favorite movies displayed.

Here is the code that handles the click (this function is stored in the Context) (I don't use useState because a re-render would trigger a change in the background of the app):

     const storageArray = [];

      const handleWatchlist = (objectData) => {
        let index = storageArray.indexOf(objectData);

        if (index === -1) {
          storageArray.push(objectData);
        } else {
          storageArray.splice(index, 1);
        }
        localStorage.setItem('currentWatchlist', JSON.stringify(storageArray));
        const retrieveData = JSON.parse(localStorage.getItem('currentWatchlist'));
        console.log(retrieveData);
      };

It works perfectly fine on the homepage. HOWEVER, in the watchlist component, if I click on a thumbnails, and then click on the button to remove the item from the storage, here is what happens:

Example: 1 movie stored in localStorage, before I click:

Inside of the watchlist component, after I click on the button, to remove it from the storage and the component:

When I click on the button, instead of removing it the element, it doesn't consider it a duplicate and so add a new object to the Local Storage (which is removed if I click again).

How can I make sure that when I click on the favorite button in the Watchlist component, the storage is updated correctly and the movie removed from the component?

Thank you for your help.

Body:
You're starting with an empty array:

const storageArray = [];

And then check if the objectData is in the array or not with:

storageArray.indexOf(objectData);

This will never find the existing item in the localStorage because you never read from localStorage. What you need to do is, when handleWatchlist is called:

Read from the localStorage and parse to a list

Find an existing item within that list by a unique key from objectData

If it's there, remove it

if not, add it

It'll be something like:

const handleWatchlist = (objectData) => {
  let storageArray = JSON.parse(localStorage.getItem("currentWatchlist"));
  let existingItem = storageArray.find(item => item.id === objectData.id);

  if (existingItem) {
    let result = storageArray.filter(item => item.id !== objectData.id);
  } else {
    let result = [...storageArray, objectData];
  }
  localStorage.setItem("currentWatchlist", JSON.stringify(result));
};


问:
c++20 handling of string literals
We’re updating a project to c++20, and are running into errors where we pass string literals into functions which take char *. I know this has been changed to make code more safe, but we are interfacing with libraries which we cannot change.

I’d rather not disable the strict treatment of literals via compiler flags, so is there a good way to wrap these literals just in these particular cases?

I was thinking of an inline function, that was named something specific to the library, that internally would use const_cast. That way later if we want to change the code because the library gets updated, we know exactly where to look.

Any other ideas?

答:
The following string literal creates a std::string for each literal and implicitly converts to char*.

```<code>#include <string>

struct stringlitwrapper
{
    constexpr stringlitwrapper(const char* c) : s(c) {};
    operator char*() { return s.data(); }
    std::string s;
};

constexpr stringlitwrapper operator"" _w (const char* c, std::size_t n)
{
    return stringlitwrapper(c);
}

void libfunction(char* param) {
    // uses non-const char* as parameter
}

int main() {
    libfunction("string literal"_w);
    return 0;
}
</code>```

For compilers, which do not support constexpr here (e.g. msvc does, clang not), leave both constexpr away.

By internally storing the literal as non-const string, there is no undefined behaviour involved.

(The library function of course should not overwrite at all or at least not write over the end of the string.)

To prevent heap allocations, the std::string could be replaced by a char array with fixed (maximal) size.

Title: c++20 handling of string literals

Body:
The following string literal creates a std::string for each literal and implicitly converts to char*.

#include <string>

struct stringlitwrapper
{
    constexpr stringlitwrapper(const char* c) : s(c) {};
    operator char*() { return s.data(); }
    std::string s;
};

constexpr stringlitwrapper operator"" _w (const char* c, std::size_t n)
{
    return stringlitwrapper(c);
}

void libfunction(char* param) {
    // uses non-const char* as parameter
}

int main() {
    libfunction("string literal"_w);
    return 0;
}

For compilers, which do not support constexpr here (e.g. msvc does, clang not), leave both constexpr away.

By internally storing the literal as non-const string, there is no undefined behaviour involved.

(The library function of course should not overwrite at all or at least not write over the end of the string.)

To prevent heap allocations, the std::string could be replaced by a char array with fixed (maximal) size.


问:
How to increase the font size of result text in Azure Data Studio Notebook?
I have found how to increase the font size of about everything except the result text of a code cell in an Azure Data Studio notebook.  Zoom works, but is not ideal.  Does anyone know of a way to increase the font size of that text?

答:
I have found that using the zoom-in and zoom-out shortcuts ('ctrl+' and 'ctr-' for me) will also increase the text size in the notes/messages pane.

I am using version 1.28.0 and it works that way.

By hitting 'ctrl+shift+p' will also pop up the command palette where you can further customize the shortcuts after searching for 'zoom'.

I hope it will help you, too.


问:
Is there a way to have different tick rates for differents parts of my code in pygame?
So, I want to have one part of my code refresh at a certain rate, while the other refreshes instantly.

```<code>import pygame
import random

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
YELLOW = (255,255,0)
PINK = (255,182,193)
INDIGO = (111,0,255)

pygame.init()
pygame.display.set_caption("Game TITLE")
screen = pygame.display.set_mode((400,400))
myText = "Score: 0"
myTextScore = 0
quitVar = True

FPS = 2
fpsClock = pygame.time.Clock()

while quitVar == True:

    screen.fill(WHITE)

    x = (random.randrange(1, 300))
    y = (random.randrange(1, 300))
    red_rect = pygame.draw.rect(screen, RED, (x, y, 100, 100))

    #this is the code that i want to refresh slower
    font = pygame.font.Font('./Roboto-Regular.ttf',20)
    text = font.render(myText, True, GREEN)
    textRect = text.get_rect(center = (200,350))
    screen.blit(text, textRect)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quitVar = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            position = pygame.mouse.get_pos()
            #i want the code below to refresh at a faster rate than what is above
            if red_rect.collidepoint(position):
                myTextScore += 1
                myText = "Score " + str(myTextScore)

    pygame.display.update()
    fpsClock.tick(FPS)

pygame.quit()
</code>```

is there a way for different code fps/refreshing different parts at different rates? The fps i have currently affects EVERYTHING in the loop, but i want it to only affect a certain part, while another part goes faster, and refreshes at 10-20 fps instead of the 2 that the other code does. My GOAL is to have a square that moves around the screen, and that when the user clicks on it, their score updates. I am trying to recreate "Whack-A-Mole"

答:
No, there is no way. See also How to run multiple while loops at a time in Python.

If you want to control something over time in Pygame you have two options:

Use pygame.time.get_ticks() to measure time and and implement logic that controls the object depending on the time.

Use the timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. Change object states when the event occurs.

For examples see Spawning multiple instances of the same object concurrently in python or Adding a particle effect to my clicker game (and many more with a little search).

Minimal example based on your code:

import pygame
import random

WHITE, BLACK = (255,255,255), (0,0,0)
RED, GREEN, BLUE = (255,0,0), (0,255,0), (0,0,255)
YELLOW, PINK, INDIGO = (255,255,0), (255,182,193), (111,0,255)

pygame.init()
pygame.display.set_caption("Game TITLE")
screen = pygame.display.set_mode((400,400))

myTextScore = 0
#font = pygame.font.Font('./Roboto-Regular.ttf',20)
font = pygame.font.SysFont(None, 20)
text = font.render("Score " + str(myTextScore), True, GREEN)

change_event = pygame.USEREVENT
pygame.time.set_timer(change_event, 500) # 0.5 seconds
red_rect = pygame.Rect((random.randrange(1, 300)), (random.randrange(1, 300)), 100, 100)

FPS = 100
fpsClock = pygame.time.Clock()
quitVar = True
while quitVar == True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quitVar = False

        if event.type == change_event:
            red_rect.x = (random.randrange(1, 300))
            red_rect.y = (random.randrange(1, 300))

        if event.type == pygame.MOUSEBUTTONDOWN:
            if red_rect.collidepoint(event.pos):
                myTextScore += 1
                text = font.render("Score " + str(myTextScore), True, GREEN)

    screen.fill(WHITE)
    pygame.draw.rect(screen, RED, red_rect)
    screen.blit(text, text.get_rect(center = (200,350)))
    pygame.display.update()
    fpsClock.tick(FPS)

pygame.quit()
```

Body:
So, I want to have one part of my code refresh at a certain rate, while the other refreshes instantly.

import pygame
import random

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
YELLOW = (255,255,0)
PINK = (255,182,193)
INDIGO = (111,0,255)

pygame.init()
pygame.display.set_caption("Game TITLE")
screen = pygame.display.set_mode((400,400))
myText = "Score: 0"
myTextScore = 0
quitVar = True

FPS = 2
fpsClock = pygame.time.Clock()

while quitVar == True:

    screen.fill(WHITE)

    x = (random.randrange(1, 300))
    y = (random.randrange(1, 300))
    red_rect = pygame.draw.rect(screen, RED, (x, y, 100, 100))

    #this is the code that i want to refresh slower
    font = pygame.font.Font('./Roboto-Regular.ttf',20)
    text = font.render(myText, True, GREEN)
    textRect = text.get_rect(center = (200,350))
    screen.blit(text, textRect)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quitVar = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            position = pygame.mouse.get_pos()
            #i want the code below to refresh at a faster rate than what is above
            if red_rect.collidepoint(position):
                myTextScore += 1
                myText = "Score " + str(myTextScore)

    pygame.display.update()
    fpsClock.tick(FPS)

pygame.quit()

is there a way for different code fps/refreshing different parts at different rates? The fps i have currently affects EVERYTHING in the loop, but i want it to only affect a certain part, while another part goes faster, and refreshes at 10-20 fps instead of the 2 that the other code does. My GOAL is to have a square that moves around the screen, and that when the user clicks on it, their score updates. I am trying to recreate "Whack-A-Mole"


问:
Dynamically building WHERE clauses in SQL statements
I have a question regarding SQL. I have the following SQL statement:

```<code>SELECT id, First, Last, E_Mail, Notes
FROM mytable
WHERE SOMETHING_SHOULD_BE_HERE IS NOT NULL;
</code>```

I know that the SOMETHING_SHOULD_BE_HERE should be a column(attribute) in my table. Is their a way I can put a variable that can refer to the column I'm trying to access? In my case their are 30 columns. Can I have a string for SOMETHING_SHOULD_BE_HERE that can be assigned in my program to the column in which I want to search?

Thanks

答:
You can have different SQLs queries in your code and use each one according to the case.

Another way is generate dynamically the query according the fields you want.

Body:
I have a question regarding SQL. I have the following SQL statement:

SELECT id, First, Last, E_Mail, Notes
FROM mytable
WHERE SOMETHING_SHOULD_BE_HERE IS NOT NULL;

I know that the SOMETHING_SHOULD_BE_HERE should be a column(attribute) in my table. Is their a way I can put a variable that can refer to the column I'm trying to access? In my case their are 30 columns. Can I have a string for SOMETHING_SHOULD_BE_HERE that can be assigned in my program to the column in which I want to search?

Thanks


问:
Add a string column from JSON object array in T-SQL
I want to create a single string from specific values in a nested JSON array and add the resulting string as a column. I have code similar to this:

DECLARE @json NVARCHAR(MAX) = N'[
  {
      "id": 2,
      "info": {
          "name": "John",
          "surname": "Smith",
          "age": 25
        }
    },
    {
        "id": 5,
        "info": {
            "name": "Jane",
            "surname": "Smith",
            "skills": [
                {
                    "name": "SQL",
                    "group": "SQLnerds"
                },
                {
                    "name": "C#",
                    "group": "C#nerds"
                },
                {
                    "name": "Azure",
                    "group": "Azurenerds"
                }
            ]
        },
        "dob": "2005-11-04T12:00:00"
    }
]';

SELECT id,
firstName,
lastName,
age,
dateOfBirth,
JSON_VALUE(skills, '$[0].name') as singleskill,
skills,
STRING_AGG(CONVERT(nvarchar(max), JSON_VALUE(skills, '$.name')), ',') as skillstring
FROM OPENJSON(@json)
  WITH (
    id INT '$.id',
    firstName NVARCHAR(50) '$.info.name',
    lastName NVARCHAR(50) '$.info.surname',
    age INT '$.info.age',
    dateOfBirth DATETIME2 '$.dob',
    skills NVARCHAR(MAX) '$.info.skills' AS JSON
  )
GROUP BY  id, firstName, lastName, age, dateOfBirth, skills
```

The result I want is 2 lines with a skills column containing the json and a skillstring column containing a aggregated string with skill names like 'SQL,C#,Azure' and NULL if no skills are present.

I'm pretty sure the STRING_AGG can do this for me, but I cannot figure out how to get the values out of the JSON string.

答:
You can try to use OUTER APPLY with another OPENJSON by skills column, then you will get the skill name from JSON array per id.

final you might use STRING_AGG function to get your expect result

```<code>SELECT v.id,
      v.firstName,
      v.lastName,
      v.age,
      v.dateOfBirth,
      JSON_VALUE(v.skills, '$[0].name') as singleskill,
      v.skills,
      STRING_AGG( v2.skill_name, ',') as skillstring
FROM OPENJSON(@json)
  WITH (
    id INT '$.id',
    firstName NVARCHAR(50) '$.info.name',
    lastName NVARCHAR(50) '$.info.surname',
    age INT '$.info.age',
    dateOfBirth DATETIME2 '$.dob',
    skills NVARCHAR(MAX) '$.info.skills' AS JSON
) as v
OUTER APPLY OPENJSON(skills) WITH (
   skill_name NVARCHAR(100) '$.name'
) as v2
GROUP BY  v.id, v.firstName, v.lastName, v.age, v.dateOfBirth, v.skills

;
</code>```

sqlfiddle

Body:
I want to create a single string from specific values in a nested JSON array and add the resulting string as a column. I have code similar to this:

DECLARE @json NVARCHAR(MAX) = N'[
  {
      "id": 2,
      "info": {
          "name": "John",
          "surname": "Smith",
          "age": 25
        }
    },
    {
        "id": 5,
        "info": {
            "name": "Jane",
            "surname": "Smith",
            "skills": [
                {
                    "name": "SQL",
                    "group": "SQLnerds"
                },
                {
                    "name": "C#",
                    "group": "C#nerds"
                },
                {
                    "name": "Azure",
                    "group": "Azurenerds"
                }
            ]
        },
        "dob": "2005-11-04T12:00:00"
    }
]';

SELECT id,
firstName,
lastName,
age,
dateOfBirth,
JSON_VALUE(skills, '$[0].name') as singleskill,
skills,
STRING_AGG(CONVERT(nvarchar(max), JSON_VALUE(skills, '$.name')), ',') as skillstring
FROM OPENJSON(@json)
  WITH (
    id INT '$.id',
    firstName NVARCHAR(50) '$.info.name',
    lastName NVARCHAR(50) '$.info.surname',
    age INT '$.info.age',
    dateOfBirth DATETIME2 '$.dob',
    skills NVARCHAR(MAX) '$.info.skills' AS JSON
  )
GROUP BY  id, firstName, lastName, age, dateOfBirth, skills

The result I want is 2 lines with a skills column containing the json and a skillstring column containing a aggregated string with skill names like 'SQL,C#,Azure' and NULL if no skills are present.

I'm pretty sure the STRING_AGG can do this for me, but I cannot figure out how to get the values out of the JSON string.

Body:
You can try to use OUTER APPLY with another OPENJSON by skills column, then you will get the skill name from JSON array per id.

final you might use STRING_AGG function to get your expect result

SELECT v.id,
      v.firstName,
      v.lastName,
      v.age,
      v.dateOfBirth,
      JSON_VALUE(v.skills, '$[0].name') as singleskill,
      v.skills,
      STRING_AGG( v2.skill_name, ',') as skillstring
FROM OPENJSON(@json)
  WITH (
    id INT '$.id',
    firstName NVARCHAR(50) '$.info.name',
    lastName NVARCHAR(50) '$.info.surname',
    age INT '$.info.age',
    dateOfBirth DATETIME2 '$.dob',
    skills NVARCHAR(MAX) '$.info.skills' AS JSON
) as v
OUTER APPLY OPENJSON(skills) WITH (
   skill_name NVARCHAR(100) '$.name'
) as v2
GROUP BY  v.id, v.firstName, v.lastName, v.age, v.dateOfBirth, v.skills

;

sqlfiddle


问:
E0153 - expression must have class type but it has type "void"
I have been trying to make my program work but I have run into an issue.

The error I get on Visual Studio is: expression must have class type but it has type "void"

The error comes from my main.cpp file on line 24:

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "Robot.h"

using namespace std;
using namespace sdds;

int main()
{
    const int num_robots = 6;
    int broken_robot = 0;
    char replacmentName[] = "C3PO";
    Robot robot[num_robots] = {
        {},
        {"KC1", "kitchen", 25.33, 4.55, 2, 2.2, false},
        {"BR1", "bedroom", 5.22, 2.54, 1, 2.2, true},
        {"Broken", "Bedroom", 10.12, 2.5,1.55, 0, true},
        {"KC2", "kitchen", 20.56, 5, 2, 3.5, true},
        {"BR2", "bedroom", 25.32, 6.5, 2.5, 3.1, true}
    };

    while ((broken_robot = conrtolRooomReport(robot, num_robots)) >= 0) {
        cout << endl << "Attention: There is a broken robot! Fixing the problem..." << endl;
        robot[broken_robot].set(replacmentName, "Control Room", 10.0, 4, 1, 2.09, false).display();
        replacmentName[0]++;
        cout << "Replacement Provided!" << endl << endl;
    }

    return 0;
}
</code>```

The Robot.h header file:

```<code>#ifndef _ROBOT_H
#define _ROBOT_H
namespace sdds {
    class Robot {
        char* name;
        char* location;
        double weight;
        double width;
        double height;
        double speeed;
        bool deployed;
    public:
            // Constructs & Destructor:
        Robot();
        Robot(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy);
        ~Robot();
            // Queries:
        char* getName() const;
        char* getLocation() const;
        bool isDeployed() const;
        bool isValid() const;
        double speed() const;
        void display() const;
            // Modifiers
        void set(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy);
        void setLocation(char* newestLoc);
        void setDeployed(bool deploy);
    };
            // Other Functions:
    int conrtolRooomReport(const Robot robot[], int num_robots);
}
#endif
</code>```

display() function implementation:

```<code>void Robot::display() const{
    cout << "| ";
    cout.setf(ios::left);
    cout.width(10);
    cout << name << " | ";
    cout.width(15);
    cout << location << " | ";
    cout.setf(ios::right);
    cout.setf(ios::fixed);
    cout.width(6);
    cout << setprecision(1) << weight << " | ";
    cout.width(6);
    cout << setprecision(1) << width << " | ";
    cout.width(6);
    cout << setprecision(1) << height << " | ";
    cout.width(6);
    cout << setprecision(1) << speeed << " | ";
    cout.width(8);
    cout.unsetf(ios::right);
    cout.setf(ios::left);
    if(isDeployed() == true)
        cout << "YES" << " |" << endl;
    else
        cout << "NO" << " |" << endl;
    cout.unsetf(ios::left);
}
</code>```

set() function implementation:

```<code>void Robot::set(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy) {
    if (newName[0] != '\0' && newName != nullptr && newLoc[0] != '\0' && newLoc != nullptr && newWeight > 0.00 && newWidth > 0.00 && newHeight > 0.00 && newSpeed > 0.00) {
        name = new char[strlen(newName) + 1];
        strcpy(name, newName);
        location = new char[strlen(newLoc) + 1];
        strcpy(location, newLoc);
        weight = newWeight;
        width = newWidth;
        height = newHeight;
        speeed = newSpeed;
        deployed = deploy;
    }
}
</code>```

Any help would be much appreciated. Tried scouring through Google but couldn't find a solution.

答: So I had to change the return type of the set(); function to Robot& and everything worked. Thanks to everyone who contributed and helped!</p>

Body:
I have been trying to make my program work but I have run into an issue.

The error I get on Visual Studio is: expression must have class type but it has type "void"

The error comes from my main.cpp file on line 24:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "Robot.h"

using namespace std;
using namespace sdds;

int main()
{
    const int num_robots = 6;
    int broken_robot = 0;
    char replacmentName[] = "C3PO";
    Robot robot[num_robots] = {
        {},
        {"KC1", "kitchen", 25.33, 4.55, 2, 2.2, false},
        {"BR1", "bedroom", 5.22, 2.54, 1, 2.2, true},
        {"Broken", "Bedroom", 10.12, 2.5,1.55, 0, true},
        {"KC2", "kitchen", 20.56, 5, 2, 3.5, true},
        {"BR2", "bedroom", 25.32, 6.5, 2.5, 3.1, true}
    };

    while ((broken_robot = conrtolRooomReport(robot, num_robots)) >= 0) {
        cout << endl << "Attention: There is a broken robot! Fixing the problem..." << endl;
        robot[broken_robot].set(replacmentName, "Control Room", 10.0, 4, 1, 2.09, false).display();
        replacmentName[0]++;
        cout << "Replacement Provided!" << endl << endl;
    }

    return 0;
}

The Robot.h header file:

#ifndef _ROBOT_H
#define _ROBOT_H
namespace sdds {
    class Robot {
        char* name;
        char* location;
        double weight;
        double width;
        double height;
        double speeed;
        bool deployed;
    public:
            // Constructs & Destructor:
        Robot();
        Robot(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy);
        ~Robot();
            // Queries:
        char* getName() const;
        char* getLocation() const;
        bool isDeployed() const;
        bool isValid() const;
        double speed() const;
        void display() const;
            // Modifiers
        void set(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy);
        void setLocation(char* newestLoc);
        void setDeployed(bool deploy);
    };
            // Other Functions:
    int conrtolRooomReport(const Robot robot[], int num_robots);
}
#endif

display() function implementation:

void Robot::display() const{
    cout << "| ";
    cout.setf(ios::left);
    cout.width(10);
    cout << name << " | ";
    cout.width(15);
    cout << location << " | ";
    cout.setf(ios::right);
    cout.setf(ios::fixed);
    cout.width(6);
    cout << setprecision(1) << weight << " | ";
    cout.width(6);
    cout << setprecision(1) << width << " | ";
    cout.width(6);
    cout << setprecision(1) << height << " | ";
    cout.width(6);
    cout << setprecision(1) << speeed << " | ";
    cout.width(8);
    cout.unsetf(ios::right);
    cout.setf(ios::left);
    if(isDeployed() == true)
        cout << "YES" << " |" << endl;
    else
        cout << "NO" << " |" << endl;
    cout.unsetf(ios::left);
}

set() function implementation:

void Robot::set(const char* newName, const char* newLoc, double newWeight, double newWidth, double newHeight, double newSpeed, bool deploy) {
    if (newName[0] != '\0' && newName != nullptr && newLoc[0] != '\0' && newLoc != nullptr && newWeight > 0.00 && newWidth > 0.00 && newHeight > 0.00 && newSpeed > 0.00) {
        name = new char[strlen(newName) + 1];
        strcpy(name, newName);
        location = new char[strlen(newLoc) + 1];
        strcpy(location, newLoc);
        weight = newWeight;
        width = newWidth;
        height = newHeight;
        speeed = newSpeed;
        deployed = deploy;
    }
}

Any help would be much appreciated. Tried scouring through Google but couldn't find a solution.


问:
Seed Django + Postgres with .sql file
I have a .sql file which I'd like to seed my django + postgres app with on build. That way I'll have some data in my app during development.

Here's my docker stuff:

Dockerfile

```<code>FROM python:3
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirements.txt /code/
RUN pip3 install -r requirements.txt
COPY . /code/
</code>```

docker-compose.yml

```<code>version: "3.9"

services:
  db:
    image: postgres
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
</code>```

答:
Django supports this usecase with fixtures: https://docs.djangoproject.com/en/3.2/howto/initial-data/
You can serialize your .sql database into a json file and feed that during build with the loaddata command.</p>

Title: Seed Django + Postgres with .sql file

Body:
I have a .sql file which I'd like to seed my django + postgres app with on build. That way I'll have some data in my app during development.

Here's my docker stuff:

Dockerfile

FROM python:3
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirements.txt /code/
RUN pip3 install -r requirements.txt
COPY . /code/

docker-compose.yml

version: "3.9"

services:
  db:
    image: postgres
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db


问:
Getting error on closing excel macro using vbscript
```<code>Dim ObjExcel, ObjWB

Set ObjExcel = CreateObject("Excel.Application")
Set ObjWB = ObjExcel.Workbooks.Open("C: \Net_Zero_Final.xlsm",0,True)

ObjExcel.Visible = True

ObjExcel.Run "Net_Zero"

ObjExcel.application.quit ' <--- error here

Set ObjWB = Nothing

Set ObjExcel = Nothing
</code>```

Getting error on the BOLD Part
Can anyone please suggest. tried everything to fix this.

答:
I think you are trying to run a VBA Macro from a .vbs file (or any other location).

I tested the following code inside test.vbs.

```<code>Set ObjExcel = CreateObject("Excel.Application")

Set ObjWB = ObjExcel.Workbooks.Open("C:\Users\PC\Downloads\TestMacro2.xlsm", False, False)

ObjExcel.Visible = True

ObjExcel.Application.Run "TestMacro2.xlsm!TheMacro"

ObjWB.Close

Set ObjWB= Nothing

Set ObjExcel = Nothing
</code>```

Where the macro inside the Excel file TestMacro2.xlsm was pretty simple

```<code>Sub TheMacro()
    MsgBox ("Hello")
End Sub
</code>```

It worked without any problems.

Notice that instead of trying to close Excel application (ObjExcel.Application.Quit), I just close the opened Workbook (ObjWB.Close). This will avoid the script to close Excel while the user is working in another project.

Body:
Dim ObjExcel, ObjWB

Set ObjExcel = CreateObject("Excel.Application")
Set ObjWB = ObjExcel.Workbooks.Open("C: \Net_Zero_Final.xlsm",0,True)

ObjExcel.Visible = True

ObjExcel.Run "Net_Zero"

ObjExcel.application.quit ' <--- error here

Set ObjWB = Nothing

Set ObjExcel = Nothing

Getting error on the BOLD Part
Can anyone please suggest. tried everything to fix this.

Body:
I think you are trying to run a VBA Macro from a .vbs file (or any other location).

I tested the following code inside test.vbs.

Set ObjExcel = CreateObject("Excel.Application")

Set ObjWB = ObjExcel.Workbooks.Open("C:\Users\PC\Downloads\TestMacro2.xlsm", False, False)

ObjExcel.Visible = True

ObjExcel.Application.Run "TestMacro2.xlsm!TheMacro"

ObjWB.Close

Set ObjWB= Nothing

Set ObjExcel = Nothing

Where the macro inside the Excel file TestMacro2.xlsm was pretty simple

Sub TheMacro()
    MsgBox ("Hello")
End Sub

It worked without any problems.

Notice that instead of trying to close Excel application (ObjExcel.Application.Quit), I just close the opened Workbook (ObjWB.Close). This will avoid the script to close Excel while the user is working in another project.


问:
Python function that returns the first location as index in which the strings differ. If the strings are identical, it should return -1
I am writing a python program that uses a function, the function name I have for example is first_difference(str1, str2) that accepts two strings as parameters and returns the first location in which the strings differ. If the strings are identical, it should return -1. However, I could not get the index of the character. What I have right now is just the character which is the first location of difference, does anyone know a good way to get the  index number of the character in the loop?

```<code>def first_difference(str1, str2):
    """
    Returns the first location in which the strings differ.
    If the strings are identical, it should return -1.
    """
    if str1 == str2:
        return -1
    else:
        for str1, str2 in zip(str1, str2):
            if str1 != str2:
                return str1

string1 = input("Enter first string:")
string2 = input("Enter second string:")
print(first_difference(string1, string2))
</code>```

TEST CASE:

INPUT

Enter first string: python

Enter second string: cython

OUTPUT

Enter first string: python

Enter second string: cython

p

So instead of 'p', the goal is to get the index number of p which is at index 0.

答:
You just need an index counter as follows:</p>
```<code>s1 = 'abc'
s2 = 'abcd'

def first_difference(str1, str2):
    if str1 == str2:
        return -1
    i = 0
    for a, b in zip(str1, str2):
        if a != b:
            break
        i += 1
    return i

print(first_difference(s1, s2))
</code>```

Body:
I am writing a python program that uses a function, the function name I have for example is first_difference(str1, str2) that accepts two strings as parameters and returns the first location in which the strings differ. If the strings are identical, it should return -1. However, I could not get the index of the character. What I have right now is just the character which is the first location of difference, does anyone know a good way to get the  index number of the character in the loop?

def first_difference(str1, str2):
    """
    Returns the first location in which the strings differ.
    If the strings are identical, it should return -1.
    """
    if str1 == str2:
        return -1
    else:
        for str1, str2 in zip(str1, str2):
            if str1 != str2:
                return str1

string1 = input("Enter first string:")
string2 = input("Enter second string:")
print(first_difference(string1, string2))

TEST CASE:

INPUT

Enter first string: python

Enter second string: cython

OUTPUT

Enter first string: python

Enter second string: cython

p

So instead of 'p', the goal is to get the index number of p which is at index 0.

Body:
You just need an index counter as follows:

s1 = 'abc'
s2 = 'abcd'

def first_difference(str1, str2):
    if str1 == str2:
        return -1
    i = 0
    for a, b in zip(str1, str2):
        if a != b:
            break
        i += 1
    return i

print(first_difference(s1, s2))


问:
Why doesn't SQL support "= null" instead of "is null"?
I'm not asking if it does.  I know that it doesn't.

I'm curious as to the reason.  I've read support docs such as as this one on Working With Nulls in MySQL but they don't really give any reason.  They only repeat the mantra that you have to use "is null" instead.

This has always bothered me.  When doing dynamic SQL (those rare times when it has to be done) it would be so much easier to pass "null" into where clause like this:

```<code>@where = "where GroupId = null"
</code>```

Which would be a simple replacement for a regular variable.  Instead we have to use if/else blocks to do stuff like:

```<code>if @groupId is null then
     @where = "where GroupId is null"
else
     @where = "where GroupId = @groupId"
end
</code>```

In larger more-complicated queries, this is a huge pain in the neck.  Is there a specific reason that SQL and all the major RDBMS vendors don't allow this?  Some kind of keyword conflict or value conflict that it would create?

Edit:

The problem with a lot of the answers (in my opinion) is that everyone is setting up an equivalency between null and "I don't know what the value is".  There's a huge difference between those two things.  If null meant "there's a value but it's unknown" I would 100% agree that nulls couldn't be equal.  But SQL null doesn't mean that.  It means that there is no value.  Any two SQL results that are null both have no value.   No value does not equal unknown value.  Two different things.  That's an important distinction.

Edit 2:

The other problem I have is that other HLLs allow null=null perfectly fine and resolve it appropriately.  In C# for instance, null=null returns true.

答:
NULL doesn't equal NULL. It can't equal NULL. It doesn't make sense for them to be equal.

A few ways to think about it:

Imagine a contacts database, containing fields like FirstName, LastName, DateOfBirth and HairColor. If I looked for records WHERE DateOfBirth = HairColor, should it ever match anything? What if someone's DateOfBirth was NULL, and their HairColor was too? An unknown hair color isn't equal to an unknown anything else.

Let's join the contacts table with purchases and product tables. Let's say I want to find all the instances where a customer bought a wig that was the same color as their own hair. So I query WHERE contacts.HairColor = product.WigColor. Should I get matches between every customer I don't know the hair color of and products that don't have a WigColor? No, they're a different thing.

Let's consider that NULL is another word for unknown. What's the result of ('Smith' = NULL)? The answer is not false, it's unknown. Unknown is not true, therefore it behaves like false. What's the result of (NULL = NULL)? The answer is also unknown, therefore also effectively false. (This is also why concatenating a string with a NULL value makes the whole string become NULL -- the result really is unknown.)

Body:
I'm not asking if it does.  I know that it doesn't.

I'm curious as to the reason.  I've read support docs such as as this one on Working With Nulls in MySQL but they don't really give any reason.  They only repeat the mantra that you have to use "is null" instead.

This has always bothered me.  When doing dynamic SQL (those rare times when it has to be done) it would be so much easier to pass "null" into where clause like this:

@where = "where GroupId = null"

Which would be a simple replacement for a regular variable.  Instead we have to use if/else blocks to do stuff like:

if @groupId is null then
     @where = "where GroupId is null"
else
     @where = "where GroupId = @groupId"
end

In larger more-complicated queries, this is a huge pain in the neck.  Is there a specific reason that SQL and all the major RDBMS vendors don't allow this?  Some kind of keyword conflict or value conflict that it would create?

Edit:

The problem with a lot of the answers (in my opinion) is that everyone is setting up an equivalency between null and "I don't know what the value is".  There's a huge difference between those two things.  If null meant "there's a value but it's unknown" I would 100% agree that nulls couldn't be equal.  But SQL null doesn't mean that.  It means that there is no value.  Any two SQL results that are null both have no value.   No value does not equal unknown value.  Two different things.  That's an important distinction.

Edit 2:

The other problem I have is that other HLLs allow null=null perfectly fine and resolve it appropriately.  In C# for instance, null=null returns true.


问:
Difference in ptr,&ptr,&ptr[0]
Below is the test code:

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

int funtion(int *ptr)
{
    int temp;
    temp = *ptr;
    printf("ptr = %p %p %p %d\n", ptr, &ptr, &ptr[0], *ptr);
    printf("*ptr = %d\n", *ptr);
    return temp;
}

int main()
{
    int i = 10;
    int *tp = &i;
    printf("tp = %p %p %p %d\n", tp, &tp, &tp[0], *tp);
    (void)funtion(tp);
    return 0;
}
answer:
tp = 0x7ffc1117392c 0x7ffc11173930 0x7ffc1117392c 10
ptr= 0x7ffc1117392c 0x7ffc111738f8 0x7ffc1117392c 10
*ptr =10
</code>```

**question:

what are the difference between tp &tp &tp[0]

Which passing parameter we should use.

is this difference only for passing parameter?**

答:
1. what are the difference between tp &tp &tp[0]

Its their type.

The type of tp is int *.

The type of &tp is int **.

The type of &tp[0] is int * because &tp[0] is equivalent to tp1) :

```<code>&tp[0]  ->  &(tp[0])  ->  &(*(tp) + (0))  ->  &(*tp)  ->  tp
</code>```

Note : You do not need to use [0] with pointer to access the value of a scalar type, which the pointer is pointing at.

2. Which passing parameter we should use.

Its not clear, what exactly you want to ask.

You are passing value of tp to function() function which is nothing but &i. The ptr parameter of function() function will hold the &i when it is called. If you want to make changes to the value of i within the function() function then you can do it because ptr hold address of i and *ptr will give value at that address which is nothing but the value of variable i. If you just want to access the value of i, you can simply pass the value of variable i.

3. is this difference only for passing parameter?

Which difference? I believe, you mean - why there is difference in &tp and &ptr?

ptr is local variable of function() function and tp is local variable of main() function. Though, they both hold the address of variable i their own addresses are different because they are different variables.

1). C Standards#6.5.2.1

The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))..

Title: Difference in ptr,&ptr,&ptr[0]

Body:
Below is the test code:

#include <stdio.h>

int funtion(int *ptr)
{
    int temp;
    temp = *ptr;
    printf("ptr = %p %p %p %d\n", ptr, &ptr, &ptr[0], *ptr);
    printf("*ptr = %d\n", *ptr);
    return temp;
}

int main()
{
    int i = 10;
    int *tp = &i;
    printf("tp = %p %p %p %d\n", tp, &tp, &tp[0], *tp);
    (void)funtion(tp);
    return 0;
}
answer:
tp = 0x7ffc1117392c 0x7ffc11173930 0x7ffc1117392c 10
ptr= 0x7ffc1117392c 0x7ffc111738f8 0x7ffc1117392c 10
*ptr =10

**question:

what are the difference between tp &tp &tp[0]

Which passing parameter we should use.

is this difference only for passing parameter?**

Body:
1. what are the difference between tp &tp &tp[0]

Its their type.

The type of tp is int *.

The type of &tp is int **.

The type of &tp[0] is int * because &tp[0] is equivalent to tp1) :

&tp[0]  ->  &(tp[0])  ->  &(*(tp) + (0))  ->  &(*tp)  ->  tp

Note : You do not need to use [0] with pointer to access the value of a scalar type, which the pointer is pointing at.

2. Which passing parameter we should use.

Its not clear, what exactly you want to ask.

You are passing value of tp to function() function which is nothing but &i. The ptr parameter of function() function will hold the &i when it is called. If you want to make changes to the value of i within the function() function then you can do it because ptr hold address of i and *ptr will give value at that address which is nothing but the value of variable i. If you just want to access the value of i, you can simply pass the value of variable i.

3. is this difference only for passing parameter?

Which difference? I believe, you mean - why there is difference in &tp and &ptr?

ptr is local variable of function() function and tp is local variable of main() function. Though, they both hold the address of variable i their own addresses are different because they are different variables.

1). C Standards#6.5.2.1

The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))..


问:
Getting bootstrap dropdown value return to work in flask
I am trying to get a value (player) from the dropdown select. Once I click the dropdown button, I want the value 'player' to get sent to flask and render the new player's image on the website.
HTML:

```<code><form method="POST">
    <div class="input-group">
      <select class="custom-select" id="inputGroupSelect04" name="player" value="{{ player }}">
          {% for key, value in team.items() %}
            <option value={{ value }}>{{ value }}</option>
          {% endfor %}
      </select>
      <div class="input-group-append">
        <button class="btn btn-outline-secondary" type="submit">Select</button>
      </div>
    </div>

</form>
    <img src="/static/{{ player }}.png" alt="{{ player }}">
</code>```

Flask:

```<code>@app.route("/", methods=['POST', 'GET'])
def main_page():
    player = okc[1628983]
    if request.method == "POST":
        print("this posted")
        player = request.form.get('player')
        print(request.form.get('player'))
        return render_template("index.html", team=okc, player=player)
    return render_template("index.html", team=okc, player=player)
</code>```

答:
instead of your:

 player = request.form.get('player')

you can try this:

player = request.form['player']

Body:
I am trying to get a value (player) from the dropdown select. Once I click the dropdown button, I want the value 'player' to get sent to flask and render the new player's image on the website.
HTML:

<form method="POST">

      <select class="custom-select" id="inputGroupSelect04" name="player" value="{{ player }}">
          {% for key, value in team.items() %}
            <option value={{ value }}>{{ value }}</option>
          {% endfor %}
      </select>

        <button class="btn btn-outline-secondary" type="submit">Select</button>

</form>

Flask:

@app.route("/", methods=['POST', 'GET'])
def main_page():
    player = okc[1628983]
    if request.method == "POST":
        print("this posted")
        player = request.form.get('player')
        print(request.form.get('player'))
        return render_template("index.html", team=okc, player=player)
    return render_template("index.html", team=okc, player=player)


问:
How can I make a button avoid the mouse in hta?
I have tried many ways to make the button avoid the mouse. I have tried all the onmouse functions, yet they don't seem to work, btw I am trying to make the button get the size of the computers screen, and make the button move all around the screen.
Here is the code that I have:</p>
```<code><body onload="WindowResize()">

<div class="align-topleft">
    <button onmouseover="moveObj(this)" id="ClickMe" class="btn" type="button">Click Me...</button>
</div>

<script>
function moveObj(obj){
var w = window.screen.width, h = window.screen.height; // width and height
newWidth = Math.floor(Math.random() * w);
newHeight = Math.floor(Math.random() * h);
obj.style.position="absolute";
obj.style.left=newWidth+"px";
obj.style.top=newHeight+"px";
}
function checkObj(event,obj){
var top = obj.style.top.split("px")[0];
var left = obj.style.left.split("px")[0];
if(top+5 > event.y || left+5 > event.x){moveObj(obj);}
}
//--></script>

<script>
function WindowResize()
{
    window.screen.width
    window.screen.height
}
</script>

</body>
</html>
</code>```

答:
It's easier if you make use of the HTA:Application option windowState=maximize. You also need an adjustment after each random to ensure the entire button is on screen. Here's the cleaned up code:

```<code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9">
<hta:application
  id=oHTA
  windowState=maximize
  border=none
  scroll=no
>
<style>
.btn {width:100px}
</style>
</head>
<body>
<script>
var w = window.screen.width, h = window.screen.height;

function moveObj(obj){
  newWidth = Math.floor(Math.random() * w);
  newHeight = Math.floor(Math.random() * h);
  if(newWidth>w-100){newWidth=newWidth-100;}
  if(newHeight>h-20){newHeight=newHeight-20;}
  obj.style.position="absolute";
  obj.style.left=newWidth+"px";
  obj.style.top=newHeight+"px";
}
function checkObj(event,obj){
  var top = obj.style.top.split("px")[0];
  var left = obj.style.left.split("px")[0];
  if(top+5 > event.y || left+5 > event.x){moveObj(obj);}
}
</script>

<div class="align-topleft">
    <button onmouseover="moveObj(this)" id="ClickMe" class="btn" type="button">Click Me...</button>
</div>
</body>
</html>
</code>```

Note: Press Alt-F4 to exit

Body:
I have tried many ways to make the button avoid the mouse. I have tried all the onmouse functions, yet they don't seem to work, btw I am trying to make the button get the size of the computers screen, and make the button move all around the screen.
Here is the code that I have:

    <button onmouseover="moveObj(this)" id="ClickMe" class="btn" type="button">Click Me...</button>

Body:
It's easier if you make use of the HTA:Application option windowState=maximize. You also need an adjustment after each random to ensure the entire button is on screen. Here's the cleaned up code:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9">
<hta:application
  id=oHTA
  windowState=maximize
  border=none
  scroll=no
>
<style>
.btn {width:100px}
</style>
</head>
<body>
<script>
var w = window.screen.width, h = window.screen.height;

function moveObj(obj){
  newWidth = Math.floor(Math.random() * w);
  newHeight = Math.floor(Math.random() * h);
  if(newWidth>w-100){newWidth=newWidth-100;}
  if(newHeight>h-20){newHeight=newHeight-20;}
  obj.style.position="absolute";
  obj.style.left=newWidth+"px";
  obj.style.top=newHeight+"px";
}
function checkObj(event,obj){
  var top = obj.style.top.split("px")[0];
  var left = obj.style.left.split("px")[0];
  if(top+5 > event.y || left+5 > event.x){moveObj(obj);}
}
</script>

<div class="align-topleft">
    <button onmouseover="moveObj(this)" id="ClickMe" class="btn" type="button">Click Me...</button>
</div>
</body>
</html>

Note: Press Alt-F4 to exit


问:
How to set a timeout for the connections in HTTPConnectionPool when using requests
I have the following script:

```<code>from requests import Session
from time import sleep

session = Session()
url = 'http://tsetmc.com'
r = session.get(url, timeout=5)  # 200 OK

sleep(200)  # if the idle time is greater than ~120 seconds, then the next `session.get` attempt will fail

# the following line fails with
# `requests.exceptions.ReadTimeout: HTTPConnectionPool(host='tsetmc.com', port=80): Read timed out. (read timeout=5)`
# but will work if I use headers={"Connection": "close"} parameter
session.get(url, timeout=5)
</code>```

It fails with:

```<code>Traceback (most recent call last):
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 449, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 444, in _make_request
    httplib_response = conn.getresponse()
  File "...\Python310\lib\http\client.py", line 1374, in getresponse
    response.begin()
  File "...\Python310\lib\http\client.py", line 318, in begin
    version, status, reason = self._read_status()
  File "...\Python310\lib\http\client.py", line 279, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "...\Python310\lib\socket.py", line 705, in readinto
    return self._sock.recv_into(b)
TimeoutError: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "...\Python310\lib\site-packages\requests\adapters.py", line 440, in send
    resp = conn.urlopen(
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 785, in urlopen
    retries = retries.increment(
  File "...\Python310\lib\site-packages\urllib3\util\retry.py", line 550, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "...\Python310\lib\site-packages\urllib3\packages\six.py", line 770, in reraise
    raise value
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 451, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 340, in _raise_timeout
    raise ReadTimeoutError(
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='tsetmc.com', port=80): Read timed out. (read timeout=5)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "F:\stock\stock-market-scripts\ETFs\temp\sessiontest3.py", line 14, in <module>
    session.get(url, timeout=5)
  File "...\Python310\lib\site-packages\requests\sessions.py", line 542, in get
    return self.request('GET', url, **kwargs)
  File "...\Python310\lib\site-packages\requests\sessions.py", line 529, in request
    resp = self.send(prep, **send_kwargs)
  File "...\Python310\lib\site-packages\requests\sessions.py", line 645, in send
    r = adapter.send(request, **kwargs)
  File "...\Python310\lib\site-packages\requests\adapters.py", line 532, in send
    raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='tsetmc.com', port=80): Read timed out. (read timeout=5)

Process finished with exit code 1
</code>```

As you can see the second call to session.get will raise an error if there has been a significant idle time during the script run.

I believe the cause of this error is a server configuration that causes connections to be dropped after a certain period of time (~120s), but requests tries to reuse the expired connection.

I have also noticed that passing headers={"Connection": "close"} argument to session.get will fix the issue, but I believe that also means the connections won't be sent back to the pool?

My question: Is there a way to set a timeout for the connections in the HTTPConnectionPool so that they won't be used if expired?

(
other options I can think of are:

the headers={"Connection": "close"} above (inefficient?)

using threading.Timer to create and use a new session object which I belive will have a fresh connection pool. (sounds too complicated?)

catch the error and retry (too slow?)
)

答:
As noted in: https://stackoverflow.com/a/59163501/9992341

"The key to keeping the connection open would be to continue polling at regular intervals. The interval you use must be less than the server's configured connection timeout."

Keep-Alive is the default as well, the following answer may give more insight into what is happening server side https://stackoverflow.com/a/25239947/9992341.

Then based off what you see if you either increase the polling interval (s in your case, make a request periodically before 120 seconds or whatever you have discovered) or explicitly try except the ReadTimeout and recreate the session (which also depends on how many requests you may be sending) and can go from there.

Body:
I have the following script:

from requests import Session
from time import sleep

session = Session()
url = 'http://tsetmc.com'
r = session.get(url, timeout=5)  # 200 OK

sleep(200)  # if the idle time is greater than ~120 seconds, then the next `session.get` attempt will fail

# the following line fails with
# `requests.exceptions.ReadTimeout: HTTPConnectionPool(host='tsetmc.com', port=80): Read timed out. (read timeout=5)`
# but will work if I use headers={"Connection": "close"} parameter
session.get(url, timeout=5)

It fails with:

Traceback (most recent call last):
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 449, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 444, in _make_request
    httplib_response = conn.getresponse()
  File "...\Python310\lib\http\client.py", line 1374, in getresponse
    response.begin()
  File "...\Python310\lib\http\client.py", line 318, in begin
    version, status, reason = self._read_status()
  File "...\Python310\lib\http\client.py", line 279, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "...\Python310\lib\socket.py", line 705, in readinto
    return self._sock.recv_into(b)
TimeoutError: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "...\Python310\lib\site-packages\requests\adapters.py", line 440, in send
    resp = conn.urlopen(
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 785, in urlopen
    retries = retries.increment(
  File "...\Python310\lib\site-packages\urllib3\util\retry.py", line 550, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "...\Python310\lib\site-packages\urllib3\packages\six.py", line 770, in reraise
    raise value
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 451, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  File "...\Python310\lib\site-packages\urllib3\connectionpool.py", line 340, in _raise_timeout
    raise ReadTimeoutError(
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='tsetmc.com', port=80): Read timed out. (read timeout=5)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "F:\stock\stock-market-scripts\ETFs\temp\sessiontest3.py", line 14, in <module>
    session.get(url, timeout=5)
  File "...\Python310\lib\site-packages\requests\sessions.py", line 542, in get
    return self.request('GET', url, **kwargs)
  File "...\Python310\lib\site-packages\requests\sessions.py", line 529, in request
    resp = self.send(prep, **send_kwargs)
  File "...\Python310\lib\site-packages\requests\sessions.py", line 645, in send
    r = adapter.send(request, **kwargs)
  File "...\Python310\lib\site-packages\requests\adapters.py", line 532, in send
    raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPConnectionPool(host='tsetmc.com', port=80): Read timed out. (read timeout=5)

Process finished with exit code 1

As you can see the second call to session.get will raise an error if there has been a significant idle time during the script run.

I believe the cause of this error is a server configuration that causes connections to be dropped after a certain period of time (~120s), but requests tries to reuse the expired connection.

I have also noticed that passing headers={"Connection": "close"} argument to session.get will fix the issue, but I believe that also means the connections won't be sent back to the pool?

My question: Is there a way to set a timeout for the connections in the HTTPConnectionPool so that they won't be used if expired?

(
other options I can think of are:

the headers={"Connection": "close"} above (inefficient?)

using threading.Timer to create and use a new session object which I belive will have a fresh connection pool. (sounds too complicated?)

catch the error and retry (too slow?)
)


问:
How to underline text in TextView with some different color than that of text?
I know how to underline text in a textview. But how to underline text with some different color ?
Underline can be done with:

```<code>TextView t = (TextView) findViewById(R.id.textview);
t.setPaintFlags(t.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
t.setText("Underline Text");
</code>```

Let say my textcolor is black and I want to underline the same with blue color, how to do it ?
Thanks in advance.

答:
Inspired by this android developer's answer, I come up with another solution, for better understanding the bounds and position of the underline.

text_underline.xml

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:height="1dp"
        android:gravity="bottom|center_horizontal"
        android:left="1dp"
        android:right="1dp">

        <shape android:shape="rectangle">
            <!--<corners android:radius="2dp" /> -->
            <solid android:color="#D9FFFFFF" />
            <!--background color of box-->
        </shape>
    </item>
</layer-list>
</code>```

usage in TextView or Button:

```<code>SpannableString(text).apply {
    setSpan(object : ReplacementSpan() {
        @SuppressLint("UseCompatLoadingForDrawables")
        private val drawable: Drawable = resources.getDrawable(R.drawable.text_underline, null)

        override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
            drawable.setBounds(x.toInt(),
                top,
                (x + measureText(paint, text, start, end)).toInt(),
                (bottom + (buttonHeight - (bottom - top)) / 2.0f).roundToInt())

            canvas.drawText(text, start, end, x, y.toFloat(), paint)
            drawable.draw(canvas)
        }

        override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int =
            paint.measureText(text, start, end).roundToInt()

        private fun measureText(paint: Paint, text: CharSequence, start: Int, end: Int): Float = paint.measureText(text, start, end)

    },
        0,
        text.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

    setText(this, BufferType.SPANNABLE)
}
</code>```

buttonHeight is the height of the View you want to apply the underline style to.

Here is the result:

Body:
I know how to underline text in a textview. But how to underline text with some different color ?
Underline can be done with:

TextView t = (TextView) findViewById(R.id.textview);
t.setPaintFlags(t.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
t.setText("Underline Text");

Let say my textcolor is black and I want to underline the same with blue color, how to do it ?
Thanks in advance.

Body:
Inspired by this android developer's answer, I come up with another solution, for better understanding the bounds and position of the underline.

text_underline.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:height="1dp"
        android:gravity="bottom|center_horizontal"
        android:left="1dp"
        android:right="1dp">

        <shape android:shape="rectangle">
            <!--<corners android:radius="2dp" /> -->
            <solid android:color="#D9FFFFFF" />
            <!--background color of box-->
        </shape>
    </item>
</layer-list>

usage in TextView or Button:

SpannableString(text).apply {
    setSpan(object : ReplacementSpan() {
        @SuppressLint("UseCompatLoadingForDrawables")
        private val drawable: Drawable = resources.getDrawable(R.drawable.text_underline, null)

        override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
            drawable.setBounds(x.toInt(),
                top,
                (x + measureText(paint, text, start, end)).toInt(),
                (bottom + (buttonHeight - (bottom - top)) / 2.0f).roundToInt())

            canvas.drawText(text, start, end, x, y.toFloat(), paint)
            drawable.draw(canvas)
        }

        override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int =
            paint.measureText(text, start, end).roundToInt()

        private fun measureText(paint: Paint, text: CharSequence, start: Int, end: Int): Float = paint.measureText(text, start, end)

    },
        0,
        text.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

    setText(this, BufferType.SPANNABLE)
}

buttonHeight is the height of the View you want to apply the underline style to.

Here is the result:


问:
'v-model' directives cannot update the iteration variable itself
I read an article about Renderless Components,it split a component into a presentational component (view part) and a renderless component(logical part) via $scopedSlots property.Here is a simple Tag component. when you press enter , you'll add a new tag

```<code><!DOCTYPE html>
<html>
<head>
<script src="http://vuejs.org/js/vue.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="app">
    <custom-component v-model="tags">
      <div slot-scope="{tags,addTag,newTag}">
        <span v-for="tag in tags">
          {{tag}}
        </span>
        <input type="text" @keydown.enter.prevent="addTag" v-model="newTag">
      </div>
    </custom-component>
  </div>

   <script>
     Vue.component('custom-component',{
        props:['value'],
        data(){
          return {
            newTag:''
          }
        },
        methods:{
          addTag(){
            this.$emit('input',[...this.value,this.newTag])
            this.newTag = ''
          }
        },
        render(h){
          return this.$scopedSlots.default({
            tags:this.value,
            addTag:this.addTag,
            newTag:this.newTag
          })
        }
      })

      new Vue({
        el:'#app',
        data:{
        tags:[
         'Test',
         'Design'
         ]
        }
      })

   </script>
</body>
</html>

</code>```

But,it doesn't work,it seems that the newTag always is ''(empty string), when I use SPA way,
the emulator says "'v-model' directives cannot update the iteration variable 'newTag' itself" ,Here is demo on jsbin

The solution is , as mentioned in the article ,use :value attribute binding, and an @input event binding ,instead of v-model. demo on jsbin

```<code><!DOCTYPE html>
<html>
<head>
<script src="http://vuejs.org/js/vue.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="app">
    <custom-component v-model="tags">
      <div slot-scope="{tags,addTag,inputAttrs,inputEvents}">
        <span v-for="tag in tags">
          {{tag}}
        </span>
        <input type="text" v-bind="inputAttrs" v-on="inputEvents">
      </div>
    </custom-component>
  </div>

   <script>
     Vue.component('custom-component',{
       props:['value'],
       data(){
         return {
           newTag:''
         }
       },
       methods:{
         addTag(){
          this.$emit('input',[...this.value,this.newTag])
          this.newTag = ''
         }
       },
       render(h){
         return this.$scopedSlots.default({
           tags:this.value,
           addTag:this.addTag,
           inputAttrs:{
             value:this.newTag
           },
           inputEvents:{
             input:(e) => {
               this.newTag = e.target.value
             },
             keydown:(e) => {
               if(e.keyCode === 13){
               e.preventDefault()
               this.addTag()
           }
         }
        }
      })
     }
    })

    new Vue({
     el:'#app',
     data:{
       tags:[
        'Test',
        'Design'
       ]
     }
   })

   </script>
</body>
</html>

</code>```

I don't know why v-model doesn't work.

EDIT

Questions above have been answered clearly, while I got another question after I read a reference link, and still v-model doesn't work question

```<code>
<!DOCTYPE html>
<html>
<head>
<script src="http://vuejs.org/js/vue.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<div id="app">
  <base-test v-slot="sp">
    <input type="text" v-model="sp.foo">
    <div>{{ sp}}</div>
  </base-test>
</div>
<script>
  Vue.component('base-test', {
  template: `
  <div>
    <slot :foo="foo"></slot>
  </div>
  `,
  data(){
    return{
      foo: 'Bar',
    }
  }
});

// Mount
new Vue({
  el: '#app',
});
</script>
</body>
</html>

</code>```

As we can see, sp is an object. why v-model seems to be not working this time?

答:
Please use Ref of Vuejs Object for you solution, here use refence and testing for me, use tailwind, vue3, as a standalone component.

remember to rate this helps me a lot

// import function ref extiende of object
// importamos la funcion ref que extiende objeto vue
import { ref } from 'vue';

export default {
  data() {
    return {
      // create refence with object for change
      // creamos una referencia con los objetos que van a cambiar
      fruits: ref({
        oranges: {
          name: 'naranjas',
          value: false
        },
        apple: {
          name: 'manzanas',
          value: false
        },
        pear: {
          name: 'peras',
          value: false
        }
      })
    };
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div>
    <!-- use tailwindcss vue -->
    <div class="w-2xl bg-blue-50 text-gray-400 font-bold">
      <!-- iteration is here -->
      <div v-for="fruit in fruits" :key="fruit">
        <label for="">{{ fruit.name }}</label>
        <!-- this can be a component example: @headlessui/vue-->
        <input v-model="fruit.value" type="checkbox">
      </div>
    </div>
    <div class="w-2xl bg-blue-50 text-gray-400 font-bold">
      {{fruits}}
    </div>
  </div>
</template></code>```

I had tried many ways to change the v-model but nothing just by referencing the javascript object

Body:
I read an article about Renderless Components,it split a component into a presentational component (view part) and a renderless component(logical part) via $scopedSlots property.Here is a simple Tag component. when you press enter , you'll add a new tag

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

    <custom-component v-model="tags">

          {{tag}}

        <input type="text" @keydown.enter.prevent="addTag" v-model="newTag">

    </custom-component>

But,it doesn't work,it seems that the newTag always is ''(empty string), when I use SPA way,
the emulator says "'v-model' directives cannot update the iteration variable 'newTag' itself" ,Here is demo on jsbin

The solution is , as mentioned in the article ,use :value attribute binding, and an @input event binding ,instead of v-model. demo on jsbin

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

    <custom-component v-model="tags">

          {{tag}}

        <input type="text" v-bind="inputAttrs" v-on="inputEvents">

    </custom-component>

I don't know why v-model doesn't work.

EDIT

Questions above have been answered clearly, while I got another question after I read a reference link, and still v-model doesn't work question

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

  <base-test v-slot="sp">
    <input type="text" v-model="sp.foo">

{{ sp}}

  </base-test>

As we can see, sp is an object. why v-model seems to be not working this time?

Body:
Please use Ref of Vuejs Object for you solution, here use refence and testing for me, use tailwind, vue3, as a standalone component.

remember to rate this helps me a lot

// import function ref extiende of object
// importamos la funcion ref que extiende objeto vue
import { ref } from 'vue';

export default {
  data() {
    return {
      // create refence with object for change
      // creamos una referencia con los objetos que van a cambiar
      fruits: ref({
        oranges: {
          name: 'naranjas',
          value: false
        },
        apple: {
          name: 'manzanas',
          value: false
        },
        pear: {
          name: 'peras',
          value: false
        }
      })
    };
  }
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div>
    <!-- use tailwindcss vue -->
    <div class="w-2xl bg-blue-50 text-gray-400 font-bold">
      <!-- iteration is here -->
      <div v-for="fruit in fruits" :key="fruit">
        <label for="">{{ fruit.name }}</label>
        <!-- this can be a component example: @headlessui/vue-->
        <input v-model="fruit.value" type="checkbox">
      </div>
    </div>
    <div class="w-2xl bg-blue-50 text-gray-400 font-bold">
      {{fruits}}
    </div>
  </div>
</template>

I had tried many ways to change the v-model but nothing just by referencing the javascript object


问:
How to listen to scroll events of a list view inside a list view in Flutter?
I have my widget tree as follows:

```<code>ListView
  - ListItem1
  - ListItem2
  - AnotherListView (shrinkWrap: true, primary: false)
</code>```

This is working as expected and I can scroll this complete widget tree as it is a one widget. Problem arises when AnotherListView reaches to end of the list and I try to fetch more data from server. The scroll controller of AnotherListView is not firing when placed like this in parent ListView. It works as expected independently.

Here's my code. StreamWidget is returning the list view.

```<code>Expanded(
   child: ListView(
      children: [
         _buildPostBody(),
         const Divider(),
         PostEngagementControlsWidget(postModel: widget.postModel),
         const Divider(),
         StreamWidget(
           iStreamDataFactory: PostCommentsDataFactory(
              context: context,
              post: widget.postModel,
            ),
           iStreamWidgetFactory: PostCommentsWidgetFactory(),
           ),
         ],
        ),
    );

</code>```

答:
You can define a ScrollController and can listen to its events in initState like this:

```<code>final ScrollController winController = ScrollController();

winController.addListener(() {
      if (winController.position.pixels == winController.position.maxScrollExtent) {
          loadWin();
      }
    });
</code>```

Body:
I have my widget tree as follows:

ListView
  - ListItem1
  - ListItem2
  - AnotherListView (shrinkWrap: true, primary: false)

This is working as expected and I can scroll this complete widget tree as it is a one widget. Problem arises when AnotherListView reaches to end of the list and I try to fetch more data from server. The scroll controller of AnotherListView is not firing when placed like this in parent ListView. It works as expected independently.

Here's my code. StreamWidget is returning the list view.

Expanded(
   child: ListView(
      children: [
         _buildPostBody(),
         const Divider(),
         PostEngagementControlsWidget(postModel: widget.postModel),
         const Divider(),
         StreamWidget(
           iStreamDataFactory: PostCommentsDataFactory(
              context: context,
              post: widget.postModel,
            ),
           iStreamWidgetFactory: PostCommentsWidgetFactory(),
           ),
         ],
        ),
    );

Body:
You can define a ScrollController and can listen to its events in initState like this:

final ScrollController winController = ScrollController();

winController.addListener(() {
      if (winController.position.pixels == winController.position.maxScrollExtent) {
          loadWin();
      }
    });


问:
pushviewController/popviewController animation duration
When I push or pop a UIViewController, how long does the animation takes to complete the slide animation. I have a view on the main window, which I need to slide in sync when a ViewController is pushed or popped.

Does anyone has any idea on the type and duration of animation that takes place when I push or pop a view.

Thanks in advance.

答: Almost all animations in the iPhone are 0.3 seconds.</p>


问:
Axios.post sends request two times
I have a problem with axios.post sending two times the same request with the same body. I have tried to Google the problem but find nothing. How can I fix it?

App.js

```<code>import logo from './logo.svg';
import './App.css';
import Register from "./register";
import SendToken from "./sendToken";
import {BrowserRouter, Routes, Route} from "react-router-dom";
import Confirmation from "./Confirmation";

import {useParams} from "react-router-dom";

function App() {
  return (
      <BrowserRouter>
          <div>
              <Routes>
                  <Route path="/registration" element={<Register/>}/>
                  <Route path="/confirmation" element={<Confirmation/>}/>
                  <Route path="/account/registrationConfirm/:data" element={<SendToken/>}/>
              </Routes>
          </div>
      </BrowserRouter>

  );
}

export default App;
</code>```

sendToken.js

```<code>import axios from 'axios';

const SendToken = () => {
    let parts = window.location.href.split('/');
    let length = parts.length;
    let token = parts[length - 1] == '' ? parts[length - 2] : parts[length - 1]

    axios.post("http://localhost:8080/api/v1/registration/registrationConfirm", {token}).then((data) => {
        console.log(data.status)
        console.log(data.data)
        console.log(token);
        }
    }).catch(() => {
        alert("An error occurred on the server")
    })

    return (
        <div>
            Token send
        </div>
    )
}

export default SendToken;
</code>```

答:
when you use to send request like this everytime that page rerenders it sends the request try using useEffect:

```<code>useEffect(() => {
    axios
    .post("http://localhost:8080/api/v1/registration/registrationConfirm", {token})
    .then((data) => {
        console.log(data.status)
        console.log(data.data)
        console.log(token);
    })
    .catch(() => {
        alert("An error occurred on the server")
    })
},[]}
</code>```

the second parameter tells you that this code will run only one time.

Title: Axios.post sends request two times

Body:
I have a problem with axios.post sending two times the same request with the same body. I have tried to Google the problem but find nothing. How can I fix it?

App.js

import logo from './logo.svg';
import './App.css';
import Register from "./register";
import SendToken from "./sendToken";
import {BrowserRouter, Routes, Route} from "react-router-dom";
import Confirmation from "./Confirmation";

import {useParams} from "react-router-dom";

function App() {
  return (
      <BrowserRouter>

              <Routes>
                  <Route path="/registration" element={<Register/>}/>
                  <Route path="/confirmation" element={<Confirmation/>}/>
                  <Route path="/account/registrationConfirm/:data" element={<SendToken/>}/>
              </Routes>

      </BrowserRouter>

  );
}

export default App;

sendToken.js

import axios from 'axios';

const SendToken = () => {
    let parts = window.location.href.split('/');
    let length = parts.length;
    let token = parts[length - 1] == '' ? parts[length - 2] : parts[length - 1]

    axios.post("http://localhost:8080/api/v1/registration/registrationConfirm", {token}).then((data) => {
        console.log(data.status)
        console.log(data.data)
        console.log(token);
        }
    }).catch(() => {
        alert("An error occurred on the server")
    })

    return (

            Token send

    )
}

export default SendToken;

Body:
when you use to send request like this everytime that page rerenders it sends the request try using useEffect:

useEffect(() => {
    axios
    .post("http://localhost:8080/api/v1/registration/registrationConfirm", {token})
    .then((data) => {
        console.log(data.status)
        console.log(data.data)
        console.log(token);
    })
    .catch(() => {
        alert("An error occurred on the server")
    })
},[]}

the second parameter tells you that this code will run only one time.


问:
Flutter: How to solve this Cocoapods version problem?
The App is working perfectly on Android but on iOS it shows me this Error when I try to launch:

```<code>Warning: CocoaPods minimum required version 1.9.0 or greater not installed. Skipping pod install.
  CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
  Without CocoaPods, plugins will not work on iOS or macOS.
  For more info, see https://flutter.dev/platform-plugins
To upgrade see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

CocoaPods not installed or not in valid state.
Error launching application on iPhone 13.
</code>```

And I'm actually shocked by this Flutter command of Cocoapods version 1.9.0! because I have just installed the latest Cocoapods version which is 1.5.2 on GitHub through brew install cocoapods.

Did someone face this problem before?

Please help :'(!

答:
Solved it by:

Uninstall Hebrew completely from Mac.

Install rvm.

Install latest ruby version through rvm.

Install cocoapods---> sudo gem install cocoapods.

Body:
The App is working perfectly on Android but on iOS it shows me this Error when I try to launch:

Warning: CocoaPods minimum required version 1.9.0 or greater not installed. Skipping pod install.
  CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
  Without CocoaPods, plugins will not work on iOS or macOS.
  For more info, see https://flutter.dev/platform-plugins
To upgrade see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

CocoaPods not installed or not in valid state.
Error launching application on iPhone 13.

And I'm actually shocked by this Flutter command of Cocoapods version 1.9.0! because I have just installed the latest Cocoapods version which is 1.5.2 on GitHub through brew install cocoapods.

Did someone face this problem before?

Please help :'(!