问:
Vectorize custom RL stable.baselines3 environment from pygame and display the output of all
This is my first custom RL stable.baselines3 project so feel free to ask for more information. It's a Snake game.

I want to create 4 environments which train the model simultaneously and see all 4 outputs. Ideally in a 2x2 grid in one pygame window.

This is the code of the game:

class SnakeGame():

    def __init__(self) -> None:
        pygame.init()

        self.width = 720
        self.height = 480

        self.window = pygame.display.set_mode((self.width, self.height))

        # ... init additional game stuff

    def main(self, direction = None, render=True):

        # ... do game stuff

        if render: # renders if a real human plays the game
            self.render()

        return reward, False

    def render(self, mode='human'):

        if mode == 'human':

            self.window.fill(self.BLACK)

            # ... render objects

            pygame.display.update()
```
<p>This is the code of my custom env:</p>
<pre class="lang-py prettyprint-override"><code>class SnakeENV(Env):

    def __init__(self) -> None:
        super(SnakeENV, self).__init__()
        metadata = {'render.modes': ['human',]}

        self.game = SnakeGame()

        self.action_space = Discrete(4)
        self.observation_space = ...

    def step(self, action):

        direction = self.action_to_direction(action)
        reward, done = self.game.main(direction, render=False)

        info = {}

        return self.state, reward, done, info

    def render(self, mode='human'):
        self.game.render(mode=mode)
</code>```

I create and train the model like this:

from stable_baselines3.common.env_util import make_vec_env
env = make_vec_env(SnakeENV, n_envs=4)

model = PPO("MultiInputPolicy", env, verbose=1, tensorboard_log=log_path)
model.learn(total_timesteps=100000)
```

It seems like all 4 environments get rendered in the same window. So like:

env_no 1; frame 1

env_no 2; frame 1

env_no 3; frame 1

env_no 4; frame 1

env_no 1; frame 2

env_no 2; frame 2

...

I tried to create multiple instances of my SnakeGame in one SnakeENV and assign each one one to one place in a 2x2 grid in a new window. This could be the right path, but I failed to implement that, because now I had to deal with multiple environments at once in my render and step method of my SnakeENV class.
I really want to know if there is an easier solution I just have been missing: So creating 4 SnakeENV instances and not 4 SnakeGame instances inside one SnakeENV.

Body:
This is my first custom RL stable.baselines3 project so feel free to ask for more information. It's a Snake game.

I want to create 4 environments which train the model simultaneously and see all 4 outputs. Ideally in a 2x2 grid in one pygame window.

This is the code of the game:

class SnakeGame():

    def __init__(self) -> None:
        pygame.init()

        self.width = 720
        self.height = 480

        self.window = pygame.display.set_mode((self.width, self.height))

        # ... init additional game stuff

    def main(self, direction = None, render=True):

        # ... do game stuff

        if render: # renders if a real human plays the game
            self.render()

        return reward, False

    def render(self, mode='human'):

        if mode == 'human':

            self.window.fill(self.BLACK)

            # ... render objects

            pygame.display.update()

This is the code of my custom env:

class SnakeENV(Env):

    def __init__(self) -> None:
        super(SnakeENV, self).__init__()
        metadata = {'render.modes': ['human',]}

        self.game = SnakeGame()

        self.action_space = Discrete(4)
        self.observation_space = ...

    def step(self, action):

        direction = self.action_to_direction(action)
        reward, done = self.game.main(direction, render=False)

        info = {}

        return self.state, reward, done, info

    def render(self, mode='human'):
        self.game.render(mode=mode)

I create and train the model like this:

from stable_baselines3.common.env_util import make_vec_env
env = make_vec_env(SnakeENV, n_envs=4)

model = PPO("MultiInputPolicy", env, verbose=1, tensorboard_log=log_path)
model.learn(total_timesteps=100000)

It seems like all 4 environments get rendered in the same window. So like:

env_no 1; frame 1

env_no 2; frame 1

env_no 3; frame 1

env_no 4; frame 1

env_no 1; frame 2

env_no 2; frame 2

...

I tried to create multiple instances of my SnakeGame in one SnakeENV and assign each one one to one place in a 2x2 grid in a new window. This could be the right path, but I failed to implement that, because now I had to deal with multiple environments at once in my render and step method of my SnakeENV class.
I really want to know if there is an easier solution I just have been missing: So creating 4 SnakeENV instances and not 4 SnakeGame instances inside one SnakeENV.


来源: stackexchange

问:
Why can't I pipe into gpg --recv-keys?
I have been stumped here for a couple weeks on and off.  I have a file that contains a key, I can get that key and print (to stdout) via something like grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p" but then anything  I do to try and pipe the output of that into gpg --recv-keys just doesn't work. There's no error it just seems like the pipe doesn't work or the command is not run at all.

Originally I started with this

```<code>grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p" | gpg --recv-keys
</code>```

that didn't work so I kept looking around until I got to this:

```<code>gpg --recv-keys <(grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p")
</code>```

which gave me the response:gpg: "/dev/fd/63" not a key ID: skipping
so I played around with this variation to get things like

```<code>gpg --recv-keys <(grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p" | cat)
</code>```

or

```<code>gpg --recv-keys < <(grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p")
</code>```

or

```<code>gpg --recv-keys <<< grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p"
</code>```

but nothing seems to work.  It's almost as if the command can recognize that something is being pipd in and avoids it be cause if i take the output of grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p") and paste it to the end of gpg --recv-keys it works fine.  So lets say  the first command produces something like ABCDEFG12345 if I do gpg --recv-keys ABCDEFG12345 it works fine.

What am I missing here?

ContentLicense: CC BY-SA 4.0

Title: Why can't I pipe into gpg --recv-keys?

Body:
I have been stumped here for a couple weeks on and off.  I have a file that contains a key, I can get that key and print (to stdout) via something like grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p" but then anything  I do to try and pipe the output of that into gpg --recv-keys just doesn't work. There's no error it just seems like the pipe doesn't work or the command is not run at all.

Originally I started with this

grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p" | gpg --recv-keys

that didn't work so I kept looking around until I got to this:

gpg --recv-keys <(grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p")

which gave me the response:gpg: "/dev/fd/63" not a key ID: skipping
so I played around with this variation to get things like

gpg --recv-keys <(grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p" | cat)

or

gpg --recv-keys < <(grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p")

or

gpg --recv-keys <<< grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p"

but nothing seems to work.  It's almost as if the command can recognize that something is being pipd in and avoids it be cause if i take the output of grep validpgpkeys PKGBUILD | sed -n "s/^.*'\(.*\)'.*$/\1/ p") and paste it to the end of gpg --recv-keys it works fine.  So lets say  the first command produces something like ABCDEFG12345 if I do gpg --recv-keys ABCDEFG12345 it works fine.

What am I missing here?


问:
Why does onFocus on my React Native app not fire when i focus on a TouchableOpacity
I am building an android-tv application with react native and i have been having issues dealing with the onFocus on a Touchable Opacity. I expect Focused to be logged to the console when i focus on the TouchableOpacity but yet nothing happens.

```<code><TouchableOpacity
        style={[styles.channelView]}
        onPress={() => {
          setChannelPlaying(item);
        }}
        onFocus={() => {
          console.log("Focused");
        }}
      >
</code>```
```<code><TouchableOpacity
        style={[styles.channelView]}
        onPress={() => {
          setChannelPlaying(item);
        }}
        onPressIn={() => {
          console.log("Focused");
        }}
      >
</code>```

I tried using onPressIn, but it doesn't fire when i use the TV remote to navigate and focus on it.

Body:
I am building an android-tv application with react native and i have been having issues dealing with the onFocus on a Touchable Opacity. I expect Focused to be logged to the console when i focus on the TouchableOpacity but yet nothing happens.

<TouchableOpacity
        style={[styles.channelView]}
        onPress={() => {
          setChannelPlaying(item);
        }}
        onFocus={() => {
          console.log("Focused");
        }}
      >

<TouchableOpacity
        style={[styles.channelView]}
        onPress={() => {
          setChannelPlaying(item);
        }}
        onPressIn={() => {
          console.log("Focused");
        }}
      >

I tried using onPressIn, but it doesn't fire when i use the TV remote to navigate and focus on it.


问:
Why when animating using animateContentSize(), the content bounces off the edge of the container
Below is a simplified version of the bar from the diagram that I am implementing. While scrolling the chart, I change its scale and would like to animate it, but during the animation, the edge of the column moves away from the edge of the chart. How can I avoid this?

demo

```<code>@Composable
fun AnimationTest() {
    var toggle by remember { mutableStateOf(true) }
    Row(
        modifier = Modifier
            .padding(8.dp)
            .animateContentSize()
            .clickable { toggle = !toggle },
    ) {
        Spacer(modifier = Modifier.weight(if (toggle) 0.4f else 0.6f))
        Card(
            modifier = Modifier
                .animateContentSize()
                .weight(if (toggle) 0.6f else 0.4f)
        ) {
            Row {
                Box(
                    modifier = Modifier
                        .weight(if (toggle) 0.2f else 0.1f)
                        .background(Color.Magenta)
                        .height(56.dp)
                )
                Box(
                    modifier = Modifier
                        .weight(if (toggle) 0.4f else 0.3f)
                        .background(Color.Blue)
                        .height(56.dp)
                )
            }
        }
    }
}
</code>```

I tried to use Animated Content, but I don't quite understand what to specify as transitionSpec.
I guess the problem is that the Card to which I apply the animateContentSize() also changes its size, but not by changing the size of children, but by changing its own weight.

Body:
Below is a simplified version of the bar from the diagram that I am implementing. While scrolling the chart, I change its scale and would like to animate it, but during the animation, the edge of the column moves away from the edge of the chart. How can I avoid this?

demo

@Composable
fun AnimationTest() {
    var toggle by remember { mutableStateOf(true) }
    Row(
        modifier = Modifier
            .padding(8.dp)
            .animateContentSize()
            .clickable { toggle = !toggle },
    ) {
        Spacer(modifier = Modifier.weight(if (toggle) 0.4f else 0.6f))
        Card(
            modifier = Modifier
                .animateContentSize()
                .weight(if (toggle) 0.6f else 0.4f)
        ) {
            Row {
                Box(
                    modifier = Modifier
                        .weight(if (toggle) 0.2f else 0.1f)
                        .background(Color.Magenta)
                        .height(56.dp)
                )
                Box(
                    modifier = Modifier
                        .weight(if (toggle) 0.4f else 0.3f)
                        .background(Color.Blue)
                        .height(56.dp)
                )
            }
        }
    }
}

I tried to use Animated Content, but I don't quite understand what to specify as transitionSpec.
I guess the problem is that the Card to which I apply the animateContentSize() also changes its size, but not by changing the size of children, but by changing its own weight.


问:
Map texture to single points rather than quads?
Using OpenGL, is it possible to apply a fragment shader to a specified region around a single vertex i.e. glPoint, rather than creating an array of quads and mapping a texture coordinate of a "duck" to each vertex?

I guess it would be more efficient as it would only require one vertex to be sent to the GPU per duck displayed, rather than the four vertices currently needed.

I have achieved a similar effect by using a geometry shader to build a quad around each vertex. Still, I am wondering if it is possible to achieve the same result without using a geometry shader.

I played around with gl_PointSize, but it is a limited feature, and I don't think it is the proper way to do it.

To summarize, I would like to know if OpenGL would allow filling a region around a single vertex using the fragment shader rather than, expressively creating a quad. Is that possible?


问:
How to run react-cli project in expo-cli?
I have downloaded a react-cli project from github and copied the necessary files from it and paste it to empty expo project and when I am running npm start, I am facing issues. Is there a way to run react-cli project in expo project?

I did npm install and installed all necessary packages but still I could not able to run my project in expo. Is there a way to do this?

I am a beginner so, I don't have hands on react-cli. I want to execute that react-cli in expo-cli. Please help me with this. Please tell me the procedure after downloading a react-cli project from github.


问:
Assembly: uninitialized space declared in .bss: section: zeroing [-w+zeroing]
I am in the process of learning assembly.

So far I have learned about different segments called text for the instructions, bss for variables, and data for constants.

```<code>section .bss:
    var     resb 4

section .text:
    global _start

_start:
    mov dword [var], 0 ;

loop:
    inc dword [var]
    jmp loop

</code>```

I have a run.sh script to simplify the testing process:

```<code>nasm -f elf main.asm && ld -m elf_i386 -s -o main main.o && ./main
</code>```

I get the following error when i compile with nasm:

```<code>$ sh run.sh
main.asm:16: warning: uninitialized space declared in non-BSS section `.bss:': zeroing [-w+zeroing]
run.sh: line 1: 49015 Segmentation fault      (core dumped) ./main
</code>```

What did I do wrong?

I was expecting the var variable to get incremented. Instead I got an error

Body:
I am in the process of learning assembly.

So far I have learned about different segments called text for the instructions, bss for variables, and data for constants.

section .bss:
    var     resb 4

section .text:
    global _start

_start:
    mov dword [var], 0 ;

loop:
    inc dword [var]
    jmp loop

I have a run.sh script to simplify the testing process:

nasm -f elf main.asm && ld -m elf_i386 -s -o main main.o && ./main

I get the following error when i compile with nasm:

$ sh run.sh
main.asm:16: warning: uninitialized space declared in non-BSS section `.bss:': zeroing [-w+zeroing]
run.sh: line 1: 49015 Segmentation fault      (core dumped) ./main

What did I do wrong?

I was expecting the var variable to get incremented. Instead I got an error


问:
R Subset dataframe by factor to new dataframes with factor names
I have a dataframe 'df' that has a column with a factor that looks like:

Species

CANG

CANG

AMRO

AMRO

MOBL

MOBL

MOBL

I would like to create a new data frame for each factor level with the name of the data frame being the factor level so that I end up with:

'CANG'

Species

CANG

CANG

'AMRO'

Species

AMRO

AMRO

'MOBL'

Species

MOBL

MOBL

MOBL


问:
Trying to design a post system, fan-out to followers, etc -- using Redis
I am aiming to build a scalable infrastructure (for fun) for a user posting system where timelines exist, such as a feed system. Feeds would include posts of a users followings.

Anyways, the current approach is this.

UserA follows UserB

Save the follows relationship in the DB

Create a redis list <userBiD-followers> -> [userAid, ...]

UserB creates a post

Save that post into the DB

Push the <postId> into their Redis list <userId-posts> -> [postId1, postId2, postId3, ...]

Now since UserA has a feed redis list <userAid-feed> -> [postId1, postId2, ...]

I essentially iterate over UserB followings, and push UserBs new post into all of their timelines. (fan-out)

Is this the right approach? Anything better I can do?

Another question of mine is, is it much faster to retrieve a redis list of postIds, and pass them into Prisma to get the actual posts than doing queries with just Prisma?

Example below.

```<code>const redisUserPosts = redis.lrange(`${userId}-posts`, 0, -1) = ['1', '2', ...]

posts.findMany({
 where: {
  id: {
    in: redisUserPosts
  }
 }
})
</code>```

The alternative would be to find by user, do potential other joins, etc, rather than knowing the exact postId which belongs to a user.

I am simply asking for advice on design, this is already implemented.

Body:
I am aiming to build a scalable infrastructure (for fun) for a user posting system where timelines exist, such as a feed system. Feeds would include posts of a users followings.

Anyways, the current approach is this.

UserA follows UserB

Save the follows relationship in the DB

Create a redis list <userBiD-followers> -> [userAid, ...]

UserB creates a post

Save that post into the DB

Push the <postId> into their Redis list <userId-posts> -> [postId1, postId2, postId3, ...]

Now since UserA has a feed redis list <userAid-feed> -> [postId1, postId2, ...]

I essentially iterate over UserB followings, and push UserBs new post into all of their timelines. (fan-out)

Is this the right approach? Anything better I can do?

Another question of mine is, is it much faster to retrieve a redis list of postIds, and pass them into Prisma to get the actual posts than doing queries with just Prisma?

Example below.

const redisUserPosts = redis.lrange(`${userId}-posts`, 0, -1) = ['1', '2', ...]

posts.findMany({
 where: {
  id: {
    in: redisUserPosts
  }
 }
})

The alternative would be to find by user, do potential other joins, etc, rather than knowing the exact postId which belongs to a user.

I am simply asking for advice on design, this is already implemented.


问:
usleep() in while loop causing issues - whole process freezes
I am using php, Laravel, Redis, and SQL on an Ubuntu localhost server. I have made a bunch of methods that return results from API searches after some processing. I am calling 5 of these methods which will be very slow if done synchronously, so I've been experimenting with async approaches (which I know php isn't optimised for). After a few approaches I have found some success with pcntl_fork(), but I'm running into some nasty problems.

Edit: After some messing around I have found that if I remove the while loop then the code afterward executes properly, I have removed the while loop and placed it in the second 'search' method. However it still causes a freeze of the system. This makes no sense as there shouldn't be an infinite loop as if I manually query the Redis db, all 5 results are there.

This is my code: (I have a few custom classes for making and processing the API calls, fyi these methods work flawlessly)

```<code>//this caches the individual api results to a Redis list
public static function cacheAsyncApiSearch(string $searchQuery, int $maxResults = 20)
{
        $key = "search:".$searchQuery; //for Redis

        if(!Redis::client()->exists($key)) {

            for ($i = 0; $i < 5; $i++) {
                // Create a child process
                $pid = pcntl_fork();

                if ($pid == -1) {
                    // Fork failed
                    exit(1);
                } elseif ($pid) {
                    // This is the parent process
                      // I have tried many versions of pcntl_wait, none work! They all still don't allow code to be ran afterwards (even within this elseif block), and the best it does is cache the 1st api case (YouTube)

//                    while (!pcntl_wait($status, WNOHANG)) {
//                        $exitStatus = pcntl_wexitstatus($status);
//                        // Do something with the exit status of the child process
//                    }
//                    dd($pid);
//                pcntl_waitpid($pid, $status, WUNTRACED);
                } else {
                    //child processes
                    switch ($i) {
                        case 0:
                            $results = YouTube::search($searchQuery, $maxResults)['results'];
                            Redis::client()->rPush($key,SearchResultDTO::jsonEncodeArray($results));
                            SearchResultDTO::convertResultDTOToModels($results);
                            break;
                        case 1:
                            $results = Dailymotion::search($searchQuery, $maxResults)['results'];
                            Redis::client()->rPush($key,SearchResultDTO::jsonEncodeArray($results));
                            SearchResultDTO::convertResultDTOToModels($results);
                            break;
                        case 2:
                            $results = Vimeo::search($searchQuery, $maxResults)['results'];
                            Redis::client()->rPush($key,SearchResultDTO::jsonEncodeArray($results));
                            SearchResultDTO::convertResultDTOToModels($results);
                            break;
                        case 3:
                            $results = Twitch::search($searchQuery, 2)['results'];
                            Redis::client()->rPush($key,SearchResultDTO::jsonEncodeArray($results));
                            SearchResultDTO::convertResultDTOToModels($results);
                            break;
                        case 4:
                            $results = Podcasts::getPodcastsFromItunesResults(Podcasts::search($searchQuery, 2)["response"]->results);
                            Redis::client()->rPush($key,SearchResultDTO::jsonEncodeArray($results));
                            SearchResultDTO::convertResultDTOToModels($results);
                            break;
                    }
                    $i = 10000;
                    exit(0);
                }
            }

            // for noting the process id of the given process that gets to this point
            Redis::client()->lPush("search_pid:".$searchQuery, $pid);

            // sets a time out for the redis cache
            Redis::client()->expire($key, 60*60*4);

            while (is_numeric( Redis::client()->lLen($key)) && Redis::client()->lLen($key) < 5) {
                usleep(500000); // 0.5 seconds
//                pcntl_waitpid(-1, $status); //does this even do anything? not for me
            }
            return false; // not already cached
        }
        return true; // already cached
    }
</code>```

This code somewhat works, It performs the api calls and caches the Redis perfectly. However when the method is ran, no code will be ran after it (unless redis has found a cached version and the process is not forked).

This made me think that all processes are being exited (possibly true? if so i dont know why), so I tried writing a version without the exit(0) line. This works, I can then perform code after the method call, however I noticed (when getting SQL race conditions) that all 6 (5 child, 1 parent) processes continued to run their own version of the code after this method (e.g. some database writes)

```<code>public static function search(string $searchQuery, int $maxResults = 20): array
    {
        $key = "search:".$searchQuery;
        $results = [];

        // the quoted method above
        self::cacheAsyncApiSearch($searchQuery, $maxResults);

        foreach (Redis::client()->lRange($key,0,-1) as $result){
            $results = array_merge($results, SearchResultDTO::jsonDecodeArray($result));
        }

        $creatorDTOs = [];
        $videoDTOs = [];
        $streamDTOs = [];
        $playlistDTOs = [];
        $podcastDTOs = [];

        /** @var SearchResultDTO $result */
        foreach ($results as $result) {
            match ($result->kind) {
                Kind::Creator => $creatorDTOs[] = $result,
                Kind::Video => $videoDTOs[] = $result,
                Kind::Stream => $streamDTOs[] = $result,
                Kind::Playlist => $playlistDTOs[] = $result,
                Kind::Podcast => $podcastDTOs[] = $result,
            };
        }

        // did this to test how many times the code was being ran (the list has 6 1's in it)
        Redis::client()->lPush("here", '1');

        // I know this code isn't completely efficient since I already called these conversion methods before, however I am just trying to get the forking stuff to work right now.
        return [
            "creators" => SearchResultDTO::convertResultDTOToModels($creatorDTOs),
            "videos" => SearchResultDTO::convertResultDTOToModels($videoDTOs),
            "streams" => SearchResultDTO::convertResultDTOToModels($streamDTOs),
            "playlists" => SearchResultDTO::convertResultDTOToModels($playlistDTOs),
            "podcasts" => SearchResultDTO::convertResultDTOToModels($podcastDTOs)
        ];
    }
</code>```

These DTO's (Data Transfer Objects) are being used to populate a UI. So for example, when I make a search (that isn't cached), the page is blank forever. But if I refresh the page (after the search is cached) then the results show just fine.

This is the most bizarre problem I have ever ran into and I really appreciate any help.

Edit please read:
After some messing around I have found that if I remove the while loop then the code afterward executes properly, I have removed the while loop and placed it in the second 'search' method. However it still causes a freeze of the system. This makes no sense as there shouldn't be an infinite loop as if I manually query the Redis db, all 5 results are there. And the dd("two") can never be excecated unless the usleep() is removed. Hopefully this narrows the problem down.

Edit 2 please read:
I have figured out that I can get the dd("two") to work when usleep() is reduced to 0.05s from 0.5 seconds, but it still doesnt seem to run long enough for it to work.

```<code>if(!self::cacheAsyncApiSearch($searchQuery, $maxResults))
            {
                // make sure Redis is properly returning a number not object
                $len = Redis::client()->lLen($key);
                while(!is_numeric($len)){
                    usleep(500000); // 0.5 seconds
                    $len = Redis::client()->lLen($key);
                }
                //dd($len); //this dd() works
                while ($len < 5) {
                    dd("one"); // this dd() works

                    usleep(500000); // 0.5 seconds
                    dd("two"); **//$this does not work, why?**

                    $len = Redis::client()->lLen($key);
                }

            }
</code>```

Body:
I am using php, Laravel, Redis, and SQL on an Ubuntu localhost server. I have made a bunch of methods that return results from API searches after some processing. I am calling 5 of these methods which will be very slow if done synchronously, so I've been experimenting with async approaches (which I know php isn't optimised for). After a few approaches I have found some success with pcntl_fork(), but I'm running into some nasty problems.

Edit: After some messing around I have found that if I remove the while loop then the code afterward executes properly, I have removed the while loop and placed it in the second 'search' method. However it still causes a freeze of the system. This makes no sense as there shouldn't be an infinite loop as if I manually query the Redis db, all 5 results are there.

This is my code: (I have a few custom classes for making and processing the API calls, fyi these methods work flawlessly)

//this caches the individual api results to a Redis list
public static function cacheAsyncApiSearch(string $searchQuery, int $maxResults = 20)
{
        $key = "search:".$searchQuery; //for Redis

        if(!Redis::client()->exists($key)) {

            for ($i = 0; $i < 5; $i++) {
                // Create a child process
                $pid = pcntl_fork();

                if ($pid == -1) {
                    // Fork failed
                    exit(1);
                } elseif ($pid) {
                    // This is the parent process
                      // I have tried many versions of pcntl_wait, none work! They all still don't allow code to be ran afterwards (even within this elseif block), and the best it does is cache the 1st api case (YouTube)

//                    while (!pcntl_wait($status, WNOHANG)) {
//                        $exitStatus = pcntl_wexitstatus($status);
//                        // Do something with the exit status of the child process
//                    }
//                    dd($pid);
//                pcntl_waitpid($pid, $status, WUNTRACED);
                } else {
                    //child processes
                    switch ($i) {
                        case 0:
                            $results = YouTube::search($searchQuery, $maxResults)['results'];
                            Redis::client()->rPush($key,SearchResultDTO::jsonEncodeArray($results));
                            SearchResultDTO::convertResultDTOToModels($results);
                            break;
                        case 1:
                            $results = Dailymotion::search($searchQuery, $maxResults)['results'];
                            Redis::client()->rPush($key,SearchResultDTO::jsonEncodeArray($results));
                            SearchResultDTO::convertResultDTOToModels($results);
                            break;
                        case 2:
                            $results = Vimeo::search($searchQuery, $maxResults)['results'];
                            Redis::client()->rPush($key,SearchResultDTO::jsonEncodeArray($results));
                            SearchResultDTO::convertResultDTOToModels($results);
                            break;
                        case 3:
                            $results = Twitch::search($searchQuery, 2)['results'];
                            Redis::client()->rPush($key,SearchResultDTO::jsonEncodeArray($results));
                            SearchResultDTO::convertResultDTOToModels($results);
                            break;
                        case 4:
                            $results = Podcasts::getPodcastsFromItunesResults(Podcasts::search($searchQuery, 2)["response"]->results);
                            Redis::client()->rPush($key,SearchResultDTO::jsonEncodeArray($results));
                            SearchResultDTO::convertResultDTOToModels($results);
                            break;
                    }
                    $i = 10000;
                    exit(0);
                }
            }

            // for noting the process id of the given process that gets to this point
            Redis::client()->lPush("search_pid:".$searchQuery, $pid);

            // sets a time out for the redis cache
            Redis::client()->expire($key, 60*60*4);

            while (is_numeric( Redis::client()->lLen($key)) && Redis::client()->lLen($key) < 5) {
                usleep(500000); // 0.5 seconds
//                pcntl_waitpid(-1, $status); //does this even do anything? not for me
            }
            return false; // not already cached
        }
        return true; // already cached
    }

This code somewhat works, It performs the api calls and caches the Redis perfectly. However when the method is ran, no code will be ran after it (unless redis has found a cached version and the process is not forked).

This made me think that all processes are being exited (possibly true? if so i dont know why), so I tried writing a version without the exit(0) line. This works, I can then perform code after the method call, however I noticed (when getting SQL race conditions) that all 6 (5 child, 1 parent) processes continued to run their own version of the code after this method (e.g. some database writes)

public static function search(string $searchQuery, int $maxResults = 20): array
    {
        $key = "search:".$searchQuery;
        $results = [];

        // the quoted method above
        self::cacheAsyncApiSearch($searchQuery, $maxResults);

        foreach (Redis::client()->lRange($key,0,-1) as $result){
            $results = array_merge($results, SearchResultDTO::jsonDecodeArray($result));
        }

        $creatorDTOs = [];
        $videoDTOs = [];
        $streamDTOs = [];
        $playlistDTOs = [];
        $podcastDTOs = [];

        /** @var SearchResultDTO $result */
        foreach ($results as $result) {
            match ($result->kind) {
                Kind::Creator => $creatorDTOs[] = $result,
                Kind::Video => $videoDTOs[] = $result,
                Kind::Stream => $streamDTOs[] = $result,
                Kind::Playlist => $playlistDTOs[] = $result,
                Kind::Podcast => $podcastDTOs[] = $result,
            };
        }

        // did this to test how many times the code was being ran (the list has 6 1's in it)
        Redis::client()->lPush("here", '1');

        // I know this code isn't completely efficient since I already called these conversion methods before, however I am just trying to get the forking stuff to work right now.
        return [
            "creators" => SearchResultDTO::convertResultDTOToModels($creatorDTOs),
            "videos" => SearchResultDTO::convertResultDTOToModels($videoDTOs),
            "streams" => SearchResultDTO::convertResultDTOToModels($streamDTOs),
            "playlists" => SearchResultDTO::convertResultDTOToModels($playlistDTOs),
            "podcasts" => SearchResultDTO::convertResultDTOToModels($podcastDTOs)
        ];
    }

These DTO's (Data Transfer Objects) are being used to populate a UI. So for example, when I make a search (that isn't cached), the page is blank forever. But if I refresh the page (after the search is cached) then the results show just fine.

This is the most bizarre problem I have ever ran into and I really appreciate any help.

Edit please read:
After some messing around I have found that if I remove the while loop then the code afterward executes properly, I have removed the while loop and placed it in the second 'search' method. However it still causes a freeze of the system. This makes no sense as there shouldn't be an infinite loop as if I manually query the Redis db, all 5 results are there. And the dd("two") can never be excecated unless the usleep() is removed. Hopefully this narrows the problem down.

Edit 2 please read:
I have figured out that I can get the dd("two") to work when usleep() is reduced to 0.05s from 0.5 seconds, but it still doesnt seem to run long enough for it to work.

if(!self::cacheAsyncApiSearch($searchQuery, $maxResults))
            {
                // make sure Redis is properly returning a number not object
                $len = Redis::client()->lLen($key);
                while(!is_numeric($len)){
                    usleep(500000); // 0.5 seconds
                    $len = Redis::client()->lLen($key);
                }
                //dd($len); //this dd() works
                while ($len < 5) {
                    dd("one"); // this dd() works

                    usleep(500000); // 0.5 seconds
                    dd("two"); **//$this does not work, why?**

                    $len = Redis::client()->lLen($key);
                }

            }


问:
I tried to convert the following C function to assembly emu8086. But, the function is not working. There are some bugs
I tried to convert the following C function to assembly emu8086. But, the function is not working. There are some bugs. The function is supposed to check if a set of 4 points forms a rectangle. The C function work correctly.

C function
emu8086assembly

```<code>C function
bool isRectangle(unsigned int x1, unsigned int y1, unsigned int x2,
 unsigned int y2, unsigned int x3, unsigned int y3, unsigned int x4,
unsigned int y4)
{
   double cx,cy;
   double dd1,dd2,dd3,dd4;
   cx=(x1+x2+x3+x4)/4;
   cy=(y1+y2+y3+y4)/4;
   dd1=(cx-x1) * (cx-x1) + (cy-y1) * (cy-y1);
   dd2=(cx-x2) * (cx-x2) + (cy-y2) * (cy-y2);
   dd3=(cx-x3) * (cx-x3) + (cy-y3) * (cy-y3);
   dd4=(cx-x4) * (cx-x4) + (cy-y4) * (cy-y4);
   return dd1==dd2 && dd1==dd3 && dd1==dd4;
}
</code>```

Assemply function

```<code>isRectangle PROC

          xor ax,ax
          mov al, matrix[0]

          xor dx,dx
          mov dl,matrix[2]
          add ax,dx

          xor dx,dx
          mov dl,matrix[4]
          add ax,dx

          xor dx,dx
          mov dl,matrix[6]
          add ax,dx

          xor dx,dx
          mov dl,4
          div dl
          xor ah,ah
          mov centerX,ax

          xor ax,ax
          mov al, matrix[1]

          xor dx,dx
          mov dl,matrix[3]
          add ax,dx

          xor dx,dx
          mov dl,matrix[5]
          add ax,dx

          xor dx,dx
          mov dl,matrix[7]
          add ax,dx

          xor dx,dx
          mov dl,4
          div dl
          xor ah,ah
          mov centerY,ax

          mov ax,centerX
          xor cx,cx
          mov cl,matrix[0]
          sub ax,cx
          mul ax
          mov dx,ax
          mov bx,centerY
          xor cx,cx
          mov cl,matrix[1]
          sub bx,cx
          mov ax,bx
          mul ax
          add dx,ax
          mov dd1,dx

          mov ax,centerX
          xor cx,cx
          mov cl,matrix[2]
          sub ax,cx
          mul ax
          mov dx,ax
          mov bx,centerY
          xor cx,cx
          mov cl,matrix[3]
          sub bx,cx
          mov ax,bx
          mul ax
          add dx,ax
          mov dd2,dx

          mov ax,centerX
          xor cx,cx
          mov cl,matrix[4]
          sub ax,cx
          mul ax
          mov dx,ax
          mov bx,centerY
          xor cx,cx
          mov cl,matrix[5]
          sub bx,cx
          mov ax,bx
          mul ax
          mov bx,ax
          add dx,bx
          mov dd3,dx

          mov ax,centerX
          xor cx,cx
          mov cl,matrix[6]
          sub ax,cx
          mul ax
          mov dx,ax
          mov bx,centerY
          xor cx,cx
          mov cl,matrix[7]
          sub bx,cx
          mov ax,bx
          mul ax
          mov bx,ax
          add dx,bx
          mov dd4,dx

          xor ax,ax
          mov ax,dd1

          cmp ax,dd2
          jne return

          cmp ax,dd3
          jne return

          cmp ax,dd4
          jne return

          PRINT "The shape is rectangle"
          int 21h
          ; draw the rectangle

          ret
          return:ret
          centerX dw 0
          centerY dw 0
          dd1 dw 0
          dd2 dw 0
          dd3 dw 0
          dd4 dw 0
isRectangle  ENDP
</code>```

matrix is placed in the ".data" segment
Here is its syntax

```<code>matrix db 2 dup(?)
       db 2 dup(?)
       db 2 dup(?)
       db 2 dup(?)
</code>```

I reviewed the code many times, but I could not find the bugs.

Body:
I tried to convert the following C function to assembly emu8086. But, the function is not working. There are some bugs. The function is supposed to check if a set of 4 points forms a rectangle. The C function work correctly.

C function
emu8086assembly

C function
bool isRectangle(unsigned int x1, unsigned int y1, unsigned int x2,
 unsigned int y2, unsigned int x3, unsigned int y3, unsigned int x4,
unsigned int y4)
{
   double cx,cy;
   double dd1,dd2,dd3,dd4;
   cx=(x1+x2+x3+x4)/4;
   cy=(y1+y2+y3+y4)/4;
   dd1=(cx-x1) * (cx-x1) + (cy-y1) * (cy-y1);
   dd2=(cx-x2) * (cx-x2) + (cy-y2) * (cy-y2);
   dd3=(cx-x3) * (cx-x3) + (cy-y3) * (cy-y3);
   dd4=(cx-x4) * (cx-x4) + (cy-y4) * (cy-y4);
   return dd1==dd2 && dd1==dd3 && dd1==dd4;
}

Assemply function

isRectangle PROC

          xor ax,ax
          mov al, matrix[0]

          xor dx,dx
          mov dl,matrix[2]
          add ax,dx

          xor dx,dx
          mov dl,matrix[4]
          add ax,dx

          xor dx,dx
          mov dl,matrix[6]
          add ax,dx

          xor dx,dx
          mov dl,4
          div dl
          xor ah,ah
          mov centerX,ax

          xor ax,ax
          mov al, matrix[1]

          xor dx,dx
          mov dl,matrix[3]
          add ax,dx

          xor dx,dx
          mov dl,matrix[5]
          add ax,dx

          xor dx,dx
          mov dl,matrix[7]
          add ax,dx

          xor dx,dx
          mov dl,4
          div dl
          xor ah,ah
          mov centerY,ax

          mov ax,centerX
          xor cx,cx
          mov cl,matrix[0]
          sub ax,cx
          mul ax
          mov dx,ax
          mov bx,centerY
          xor cx,cx
          mov cl,matrix[1]
          sub bx,cx
          mov ax,bx
          mul ax
          add dx,ax
          mov dd1,dx

          mov ax,centerX
          xor cx,cx
          mov cl,matrix[2]
          sub ax,cx
          mul ax
          mov dx,ax
          mov bx,centerY
          xor cx,cx
          mov cl,matrix[3]
          sub bx,cx
          mov ax,bx
          mul ax
          add dx,ax
          mov dd2,dx

          mov ax,centerX
          xor cx,cx
          mov cl,matrix[4]
          sub ax,cx
          mul ax
          mov dx,ax
          mov bx,centerY
          xor cx,cx
          mov cl,matrix[5]
          sub bx,cx
          mov ax,bx
          mul ax
          mov bx,ax
          add dx,bx
          mov dd3,dx

          mov ax,centerX
          xor cx,cx
          mov cl,matrix[6]
          sub ax,cx
          mul ax
          mov dx,ax
          mov bx,centerY
          xor cx,cx
          mov cl,matrix[7]
          sub bx,cx
          mov ax,bx
          mul ax
          mov bx,ax
          add dx,bx
          mov dd4,dx

          xor ax,ax
          mov ax,dd1

          cmp ax,dd2
          jne return

          cmp ax,dd3
          jne return

          cmp ax,dd4
          jne return

          PRINT "The shape is rectangle"
          int 21h
          ; draw the rectangle

          ret
          return:ret
          centerX dw 0
          centerY dw 0
          dd1 dw 0
          dd2 dw 0
          dd3 dw 0
          dd4 dw 0
isRectangle  ENDP

matrix is placed in the ".data" segment
Here is its syntax

matrix db 2 dup(?)
       db 2 dup(?)
       db 2 dup(?)
       db 2 dup(?)

I reviewed the code many times, but I could not find the bugs.


问:
Cannot upgrade from imp to importlib - no suitable alternative or am I just missing something obvious
This code works:

module = imp.load_source("module", os.path.join(os.getcwd(), file_name))

This code doesn't:

module = importlib.import_module(os.path.join(os.getcwd(), file_name))

With the error:

ModuleNotFoundError: No module named 'C:\\Users\\...\\functions'

For reference, my module's location is 'C:\\Users\\...\\functions.py'

I've tried referencing via a relative directory, and I've also got init.py in the same directory that I'm working in to ensure that its a package. I've read through the very well written answer here and learned that it might be because the directory my script is running from is the same as the file I'm trying to read from. However, its answer is for "normal" imports, whereas my use-case requires is via imp vs importlib.

This feels simple, but I'm at a total loss. Any advice would be greatly appreciated.


问:
C++ , Why the "double" data type is showing only 7 digits and not 15-16?
I'm new to c++ and i want to represent a value as accurately as possible using "double" data type , why pi & area values aren't represented fully here ?enter image description here

expected that float and double will have different value representations in my code but they are showing the same accuracy with different size

Here is the code

#include <iostream>
using namespace std;
int main()
{
    const double PI = 3.14159265359;
    int radius = 6;
    cout << "Since radius is " << radius << " Cm" << '\n';
    cout << "and pi is " << PI << '\n';
    double area = PI * radius;
    cout << "Then the Area of the circle will equal (pi x radius)= " << area << '\n';
    return 0;
}
```


问:
What is the most effective way to read data from FilePart(Flux<DataBuffer>) object?
I am accepting a FilePart in API and filePart holds Flux<DataBuffer>.
I have two approaches to read data from FilePart and map it to a bean but I am not sure which one is more CPU and IO effective.

Common Function

```<code>private List<DTO> parseToBean(Reader bufferedReader, Class<T> clazz) {
    CsvToBean<DTO> csvTobean = new CsvToBeanBuilder<DTO>(bufferedReader).withType(clazz).build();
    return csvTobean.parse();
  }

</code>```

Approach 1:

```<code> PipedOutputStream osPipe = new PipedOutputStream();
    PipedInputStream isPipe = new PipedInputStream(osPipe);
    DataBufferUtils.write(data, osPipe).doOnComplete(() -> {
      try {
        osPipe.close();
      } catch (IOException e) {
        log.error("");
      }
    }).subscribe(DataBufferUtils.releaseConsumer());
BufferedReader bufferedReader =
        new BufferedReader(new InputStreamReader(isPipe));
    return parseToBean(bufferedReader, targetClass);
</code>```

Approach 2:

```<code>return DataBufferUtils.join(filePart.content())
        .map(DataBuffer::asInputStream)
        .map(InputStreamReader::new)
        .flatMapIterable(reader -> parseToBean(new BufferedReader(reader), targetClass));
</code>```

Which approach is better, in terms of CPU and memory consumption and why?
By CPU and memory consumption, I mean the process should utilize less CPU and fill less heap memory.
Also, is there any other way which is better than these two approaches in term of resources consumption?

Body:
I am accepting a FilePart in API and filePart holds Flux<DataBuffer>.
I have two approaches to read data from FilePart and map it to a bean but I am not sure which one is more CPU and IO effective.

Common Function

private List<DTO> parseToBean(Reader bufferedReader, Class<T> clazz) {
    CsvToBean<DTO> csvTobean = new CsvToBeanBuilder<DTO>(bufferedReader).withType(clazz).build();
    return csvTobean.parse();
  }

Approach 1:

 PipedOutputStream osPipe = new PipedOutputStream();
    PipedInputStream isPipe = new PipedInputStream(osPipe);
    DataBufferUtils.write(data, osPipe).doOnComplete(() -> {
      try {
        osPipe.close();
      } catch (IOException e) {
        log.error("");
      }
    }).subscribe(DataBufferUtils.releaseConsumer());
BufferedReader bufferedReader =
        new BufferedReader(new InputStreamReader(isPipe));
    return parseToBean(bufferedReader, targetClass);

Approach 2:

return DataBufferUtils.join(filePart.content())
        .map(DataBuffer::asInputStream)
        .map(InputStreamReader::new)
        .flatMapIterable(reader -> parseToBean(new BufferedReader(reader), targetClass));

Which approach is better, in terms of CPU and memory consumption and why?
By CPU and memory consumption, I mean the process should utilize less CPU and fill less heap memory.
Also, is there any other way which is better than these two approaches in term of resources consumption?


问:
Unable to open a chat in chatify Laravel
I have created the chat module. It is also searching the username in database(users table) but when I click on the chat, nothing happens. I am attaching the snip of the console.

Error log
Any help would be apperciated.


问:
How do I connect my swift ios app to a database, and why is it giving me a status 500 error?
I am creating an simple ios app that asks the user for userid and sends that to a database. This is my first app so i am new to app-database connection. Here is the entire code for the page that asks for the userid and sends that to the a php file.

```<code>//
//  NextSecondViewController.swift
//  DepressionApp1
//
//  Created by Ashok Nambisan on 12/2/22.
//

import UIKit
import Foundation
struct ResponseObject<T: Decodable>: Decodable {
    let form: T
}

struct Foo: Decodable {
    let name: String
}
extension Dictionary {
    func percentEncoded() -> Data? {
        map { key, value in
            let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            return escapedKey + "=" + escapedValue
        }
        .joined(separator: "&")
        .data(using: .utf8)
    }
}

extension CharacterSet {
    static let urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed: CharacterSet = .urlQueryAllowed
        allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
        return allowed
    }()
}
class NextViewController: UIViewController {

    let URL = ""

    @IBOutlet var Text: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        initializeHideKeyboard()
         }
    func initializeHideKeyboard(){
     //Declare a Tap Gesture Recognizer which will trigger our dismissMyKeyboard() function
     let tap: UITapGestureRecognizer = UITapGestureRecognizer(
     target: self,
     action: #selector(dismissMyKeyboard))
     //Add this tap gesture recognizer to the parent view
     view.addGestureRecognizer(tap)
     }
    @objc func dismissMyKeyboard(){
     //endEditing causes the view (or one of its embedded text fields) to resign the first responder status.
     //In short- Dismiss the active keyboard.
     view.endEditing(true)
     }
    @IBOutlet weak var labelf: UILabel!
    @IBOutlet weak var textg: UITextField!
    @IBAction func Submit(_ sender: Any) {
        //created NSURL
        let url = Foundation.URL(string: "http://ashok.local:8888/insert.php")!
                //creating NSMutableURLRequest
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
                //setting the method to post
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

                //getting values from text fields

        print(textg.text)
        let parameters: [String: Any] = [
            "userid": textg.text
        ]
        request.httpBody = parameters.percentEncoded()
        print("URLRequest: \(request)")
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard
                let data = data,
                let response = response as? HTTPURLResponse,
                error == nil
            else {                                                               // check for fundamental networking error
                print("error", error ?? URLError(.badServerResponse))
                return
            }
            guard (200 ... 299) ~= response.statusCode else {                    // check for http errors
                print("statusCode should be 2xx, but is \(response.statusCode)")
                print("response = \(response)")
                return}
            do {
                    let responseObject = try JSONDecoder().decode(ResponseObject<Foo>.self, from: data)
                    print(responseObject)
                } catch {
                    print(error) // parsing error

                    if let responseString = String(data: data, encoding: .utf8) {
                        print("responseString = \(responseString)")
                    } else {
                        print("unable to parse response as string")
                    }
                }
                    }

                    task.resume()
                //executing the task

                                                      }

    @IBAction func previbutton(_ sender: Any) {
        let vmc = storyboard?.instantiateViewController(withIdentifier: "second") as! SecondViewController
        vmc.modalPresentationStyle  = .fullScreen
        present(vmc,animated:true)
    }
}

</code>```

Then here is the code for the config.php

```<code>
<?php
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_SERVER', 'localhost');
define('DB_NAME', 'emotion');
try{
    $pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
?>

</code>```

and insert.php:

```<code><?php

// set up the response array
$response = array();

// check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  // get the userid from the POST request
  $userid = $_POST['userid'];

  // connect to the database
  require_once "config.php";

  // insert the record into the database
  $sql = "INSERT INTO data (userid) VALUES (:userid)";
  $stmt = $pdo->prepare($sql);
  $stmt->bindParam(':userid', $userid);
  $stmt->execute();

  // set the success message in the response array
  $response['error'] = false;
  $response['message'] = 'Record inserted successfully';
} else {
  // set the error message in the response array
  $response['error'] = true;
  $response['message'] = 'You are not authorized';
}

// return the response as JSON
echo json_encode($response);

// close the database connection
unset($pdo);

</code>```

When i run the code on xcode, it gives me the status 500 error

I know my php-database connection is fine since when i just sent a number to the database in the userid column, it worked. However, when I connected the swift to the php for userid, it gives me a status 500 error and doesn't work. I don't know where the error is, could someone help me?

Body:
I am creating an simple ios app that asks the user for userid and sends that to a database. This is my first app so i am new to app-database connection. Here is the entire code for the page that asks for the userid and sends that to the a php file.

//
//  NextSecondViewController.swift
//  DepressionApp1
//
//  Created by Ashok Nambisan on 12/2/22.
//

import UIKit
import Foundation
struct ResponseObject<T: Decodable>: Decodable {
    let form: T
}

struct Foo: Decodable {
    let name: String
}
extension Dictionary {
    func percentEncoded() -> Data? {
        map { key, value in
            let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            return escapedKey + "=" + escapedValue
        }
        .joined(separator: "&")
        .data(using: .utf8)
    }
}

extension CharacterSet {
    static let urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed: CharacterSet = .urlQueryAllowed
        allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
        return allowed
    }()
}
class NextViewController: UIViewController {

    let URL = ""

    @IBOutlet var Text: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        initializeHideKeyboard()
         }
    func initializeHideKeyboard(){
     //Declare a Tap Gesture Recognizer which will trigger our dismissMyKeyboard() function
     let tap: UITapGestureRecognizer = UITapGestureRecognizer(
     target: self,
     action: #selector(dismissMyKeyboard))
     //Add this tap gesture recognizer to the parent view
     view.addGestureRecognizer(tap)
     }
    @objc func dismissMyKeyboard(){
     //endEditing causes the view (or one of its embedded text fields) to resign the first responder status.
     //In short- Dismiss the active keyboard.
     view.endEditing(true)
     }
    @IBOutlet weak var labelf: UILabel!
    @IBOutlet weak var textg: UITextField!
    @IBAction func Submit(_ sender: Any) {
        //created NSURL
        let url = Foundation.URL(string: "http://ashok.local:8888/insert.php")!
                //creating NSMutableURLRequest
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
                //setting the method to post
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

                //getting values from text fields

        print(textg.text)
        let parameters: [String: Any] = [
            "userid": textg.text
        ]
        request.httpBody = parameters.percentEncoded()
        print("URLRequest: \(request)")
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard
                let data = data,
                let response = response as? HTTPURLResponse,
                error == nil
            else {                                                               // check for fundamental networking error
                print("error", error ?? URLError(.badServerResponse))
                return
            }
            guard (200 ... 299) ~= response.statusCode else {                    // check for http errors
                print("statusCode should be 2xx, but is \(response.statusCode)")
                print("response = \(response)")
                return}
            do {
                    let responseObject = try JSONDecoder().decode(ResponseObject<Foo>.self, from: data)
                    print(responseObject)
                } catch {
                    print(error) // parsing error

                    if let responseString = String(data: data, encoding: .utf8) {
                        print("responseString = \(responseString)")
                    } else {
                        print("unable to parse response as string")
                    }
                }
                    }

                    task.resume()
                //executing the task

                                                      }

    @IBAction func previbutton(_ sender: Any) {
        let vmc = storyboard?.instantiateViewController(withIdentifier: "second") as! SecondViewController
        vmc.modalPresentationStyle  = .fullScreen
        present(vmc,animated:true)
    }
}

Then here is the code for the config.php

<?php
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_SERVER', 'localhost');
define('DB_NAME', 'emotion');
try{
    $pdo = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
?>

and insert.php:

<?php

// set up the response array
$response = array();

// check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  // get the userid from the POST request
  $userid = $_POST['userid'];

  // connect to the database
  require_once "config.php";

  // insert the record into the database
  $sql = "INSERT INTO data (userid) VALUES (:userid)";
  $stmt = $pdo->prepare($sql);
  $stmt->bindParam(':userid', $userid);
  $stmt->execute();

  // set the success message in the response array
  $response['error'] = false;
  $response['message'] = 'Record inserted successfully';
} else {
  // set the error message in the response array
  $response['error'] = true;
  $response['message'] = 'You are not authorized';
}

// return the response as JSON
echo json_encode($response);

// close the database connection
unset($pdo);

When i run the code on xcode, it gives me the status 500 error

I know my php-database connection is fine since when i just sent a number to the database in the userid column, it worked. However, when I connected the swift to the php for userid, it gives me a status 500 error and doesn't work. I don't know where the error is, could someone help me?


问:
STContains returns points that are not in polygon
I am trying to get points from a Microsoft SQL Server table that are inside a polygon from another table.  The current query results in points outside the definition of the polygon.

The main query I have is this:

```<code>select top 10
          ATOMIZER.[ATOMIZER_ID]
          ,ATOMIZER.LAT
          ,ATOMIZER.LONG
          from db..ATOMIZER join db..[AOI]
          on ATOMIZER.ZIP = Cast(AOI.[zip] AS varchar)
          where 1 = CASE AOI.TYPE
          WHEN 'polygon' THEN AOI.[geography].STContains(geography::Point(ATOMIZER.LAT, ATOMIZER.LONG, 4326))
          WHEN 'rectangle' THEN AOI.[geography].STContains(geography::Point(ATOMIZER.LAT, ATOMIZER.LONG, 4326))
          WHEN 'circle' THEN AOI.[geography].STContains(AOI.[geography].STBuffer(AOI.radius)) END

          and AOI.id =  {AOI}
          --and AOI.DateLicensed is null
          and ATOMIZER.LAT is not null
          and ATOMIZER.LONG is not null
</code>```

I have also simplified the query to this in an attempt to troubleshoot.

```<code>select top 10
          ATOMIZER.[ATOMIZER_ID]
          ,ATOMIZER.LAT
          ,ATOMIZER.LONG
          from db..ATOMIZER join db..[AOI]
          on ATOMIZER.ZIP = Cast(AOI.[zip] AS varchar)
  where AOI.id =  9198
  and ATTOM.LAT is not null
  and ATTOM.LONG is not null
  and AOI.geography.STContains(geography::Point(ATOMIZER.LAT, ATOMIZER.LONG, 4326)) = 1
</code>```

The Atomizer Table looks like this:

```<code>CREATE TABLE db.dbo.ATOMIZER (
    ATOMIZER_ID bigint NULL,
    ADDRESS varchar(140) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    CITY varchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    STATE varchar(8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    ZIP varchar(14) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    LAT float NULL,
    LONG float NULL,
    GEOCODE_DT date NULL,
    Geocodio_Address varchar(156) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Geocodio_City varchar(56) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Geocodio_State varchar(8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Geocodio_Zip varchar(14) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Geocodio_Lat float NULL,
    Geocodio_Lng float NULL,
    Geocodio_GEOID varchar(26) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Geocodio_POINT geography NULL
);
</code>```

The AOI table looks like this:

```<code>CREATE TABLE db.dbo.AOI (
    ID int IDENTITY(1,1) NOT NULL,
    name varchar(500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [type] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [geography] geography
);
 CREATE NONCLUSTERED INDEX NonClusteredIndex-20221206-185336 ON dbo.AOI (  zip ASC  )
     WITH (  PAD_INDEX = OFF ,FILLFACTOR = 100  ,SORT_IN_TEMPDB = OFF , IGNORE_DUP_KEY = OFF , STATISTICS_NORECOMPUTE = OFF , ONLINE = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON  )
     ON [PRIMARY ] ;
</code>```

In the main query, I'm looking at AOI 9198  The polygon in the polygon in the AOI appear like this:

```<code>[(27.334412613029517, -82.48118404236736),
 (27.334488859974545, -82.4711418518156),
 (27.329456449106882, -82.47105602112713),
 (27.330218950286305, -82.48109821167888),
 (27.334412613029517, -82.48118404236736)]
</code>```

However, the results for that AOI returns ATOMIZER points outside the polygon:

```<code>[(243854600, 27.049499, -82.139568),
 (243844656, 27.072806, -82.093464),
 (250735272, 27.299072, -82.456513),
 (145991001, 27.299082, -82.47212),
 (145943693, 27.299085, -82.47242),
 (25251051, 27.299086, -82.47049),
 (16653415, 27.29909, -82.467433),
 (10864549, 27.299091, -82.46352),
 (163778547, 27.299092, -82.465079),
 (49735501, 27.299093, -82.457673)]
</code>```

These points lie outside the geography.
What am I missing here?

Thank you.

Body:
I am trying to get points from a Microsoft SQL Server table that are inside a polygon from another table.  The current query results in points outside the definition of the polygon.

The main query I have is this:

select top 10
          ATOMIZER.[ATOMIZER_ID]
          ,ATOMIZER.LAT
          ,ATOMIZER.LONG
          from db..ATOMIZER join db..[AOI]
          on ATOMIZER.ZIP = Cast(AOI.[zip] AS varchar)
          where 1 = CASE AOI.TYPE
          WHEN 'polygon' THEN AOI.[geography].STContains(geography::Point(ATOMIZER.LAT, ATOMIZER.LONG, 4326))
          WHEN 'rectangle' THEN AOI.[geography].STContains(geography::Point(ATOMIZER.LAT, ATOMIZER.LONG, 4326))
          WHEN 'circle' THEN AOI.[geography].STContains(AOI.[geography].STBuffer(AOI.radius)) END

          and AOI.id =  {AOI}
          --and AOI.DateLicensed is null
          and ATOMIZER.LAT is not null
          and ATOMIZER.LONG is not null

I have also simplified the query to this in an attempt to troubleshoot.

select top 10
          ATOMIZER.[ATOMIZER_ID]
          ,ATOMIZER.LAT
          ,ATOMIZER.LONG
          from db..ATOMIZER join db..[AOI]
          on ATOMIZER.ZIP = Cast(AOI.[zip] AS varchar)
  where AOI.id =  9198
  and ATTOM.LAT is not null
  and ATTOM.LONG is not null
  and AOI.geography.STContains(geography::Point(ATOMIZER.LAT, ATOMIZER.LONG, 4326)) = 1

The Atomizer Table looks like this:

CREATE TABLE db.dbo.ATOMIZER (
    ATOMIZER_ID bigint NULL,
    ADDRESS varchar(140) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    CITY varchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    STATE varchar(8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    ZIP varchar(14) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    LAT float NULL,
    LONG float NULL,
    GEOCODE_DT date NULL,
    Geocodio_Address varchar(156) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Geocodio_City varchar(56) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Geocodio_State varchar(8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Geocodio_Zip varchar(14) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Geocodio_Lat float NULL,
    Geocodio_Lng float NULL,
    Geocodio_GEOID varchar(26) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    Geocodio_POINT geography NULL
);

The AOI table looks like this:

CREATE TABLE db.dbo.AOI (
    ID int IDENTITY(1,1) NOT NULL,
    name varchar(500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [type] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [geography] geography
);
 CREATE NONCLUSTERED INDEX NonClusteredIndex-20221206-185336 ON dbo.AOI (  zip ASC  )
     WITH (  PAD_INDEX = OFF ,FILLFACTOR = 100  ,SORT_IN_TEMPDB = OFF , IGNORE_DUP_KEY = OFF , STATISTICS_NORECOMPUTE = OFF , ONLINE = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON  )
     ON [PRIMARY ] ;

In the main query, I'm looking at AOI 9198  The polygon in the polygon in the AOI appear like this:

[(27.334412613029517, -82.48118404236736),
 (27.334488859974545, -82.4711418518156),
 (27.329456449106882, -82.47105602112713),
 (27.330218950286305, -82.48109821167888),
 (27.334412613029517, -82.48118404236736)]

However, the results for that AOI returns ATOMIZER points outside the polygon:

[(243854600, 27.049499, -82.139568),
 (243844656, 27.072806, -82.093464),
 (250735272, 27.299072, -82.456513),
 (145991001, 27.299082, -82.47212),
 (145943693, 27.299085, -82.47242),
 (25251051, 27.299086, -82.47049),
 (16653415, 27.29909, -82.467433),
 (10864549, 27.299091, -82.46352),
 (163778547, 27.299092, -82.465079),
 (49735501, 27.299093, -82.457673)]

These points lie outside the geography.
What am I missing here?

Thank you.


问:
How can I keep the URL constant even if the user tries navigating to a section that doesn't exist?
I have a 404 page that the user gets redirected to if the URI doesn't exist for my app.  The problem is that if I type in something like http://127.0.0.1:8000/sdfoijifoifs, the URL remains http://127.0.0.1:8000/gallery in the browser's search bar (even though the 404 page is displayed) instead of http://127.0.0.1:8000/sdfoijifoifs (the incorrect URL).

This is happening due to the logic happening in useEffect() but can't seem to figure out a way to rectify it.  How can I fix it so that the correct URI remains when the user tries to go to a page that doesn't exist?

App. js

```<code>let { push } = useHistory();
let authToken = localStorage.getItem('token');

useEffect(() => {
  if (authToken !== null) {
    return push('/gallery');
  }

  return push('/');
}, [authToken]);

return (
  <>
    {/*https://stackoverflow.com/a/63597919*/}
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/gallery" component={Grid} />
        <Route path="/support" component={Support} />
        <Route path='/faq' component={FaqComp} />
        <Route path='/prizes' component={Prizes} />
        <Route path='/past-winners' component={PastWinners} />
        <Route path="/*" component={PageNotFound} />
      </Switch>
    </Router>
  </>
);
</code>```

PageNotFound.js

```<code>return (
  <>
    <div className="pageNotFoundBody">
      <div className="containerPageNotFound">
        <h2 className="pageNotFound">404</h2>
        <h3 className="oopsPageNotFound">
          Oops, looks like the page you've navigated to cannot be found!
        </h3>
        <Link to={localStorage.getItem('token') ? "/gallery" : "/"}>
          <button className="btn mt-4">Go Home</button>
        </Link>
      </div>
    </div>
  </>
);
</code>```

Body:
I have a 404 page that the user gets redirected to if the URI doesn't exist for my app.  The problem is that if I type in something like http://127.0.0.1:8000/sdfoijifoifs, the URL remains http://127.0.0.1:8000/gallery in the browser's search bar (even though the 404 page is displayed) instead of http://127.0.0.1:8000/sdfoijifoifs (the incorrect URL).

This is happening due to the logic happening in useEffect() but can't seem to figure out a way to rectify it.  How can I fix it so that the correct URI remains when the user tries to go to a page that doesn't exist?

App. js

let { push } = useHistory();
let authToken = localStorage.getItem('token');

useEffect(() => {
  if (authToken !== null) {
    return push('/gallery');
  }

  return push('/');
}, [authToken]);

return (
  <>
    {/*https://stackoverflow.com/a/63597919*/}
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/gallery" component={Grid} />
        <Route path="/support" component={Support} />
        <Route path='/faq' component={FaqComp} />
        <Route path='/prizes' component={Prizes} />
        <Route path='/past-winners' component={PastWinners} />
        <Route path="/*" component={PageNotFound} />
      </Switch>
    </Router>
  </>
);

PageNotFound.js

return (
  <>

404

          Oops, looks like the page you've navigated to cannot be found!

        <Link to={localStorage.getItem('token') ? "/gallery" : "/"}>
          <button className="btn mt-4">Go Home</button>
        </Link>

  </>
);


问:
How can I composite two alpha channels using a "max" operation?
Suppose I draw two overlapping translucent shapes in a canvas:

```<code>context.fillStyle = "rgba(0, 0, 0, 0.25)";
context.globalCompositeOperation = "copy";
context.fillRect(50, 50, 200, 200);
context.globalCompositeOperation = "??????";
context.fillRect(150, 150, 200, 200);
</code>```

After this, I want the RGB values of each pixel to be (0, 0, 0) and for the alpha to be the maximum of the alpha channels of the two shapes. In other words, what I should get is that if a pixel is in either of the two squares it has alpha 0.25, otherwise it's blank. So the entire drawn region should be a uniform color.

I can't find any blending operation that does this. If I use things like "lighter" or "darker", I get a darker region where the two squares overlap.

Body:
Suppose I draw two overlapping translucent shapes in a canvas:

context.fillStyle = "rgba(0, 0, 0, 0.25)";
context.globalCompositeOperation = "copy";
context.fillRect(50, 50, 200, 200);
context.globalCompositeOperation = "??????";
context.fillRect(150, 150, 200, 200);

After this, I want the RGB values of each pixel to be (0, 0, 0) and for the alpha to be the maximum of the alpha channels of the two shapes. In other words, what I should get is that if a pixel is in either of the two squares it has alpha 0.25, otherwise it's blank. So the entire drawn region should be a uniform color.

I can't find any blending operation that does this. If I use things like "lighter" or "darker", I get a darker region where the two squares overlap.


问:
I am having trouble uploading my web app on vercel
When in the build process these errors throw up

```<code>Cloning github.com/AshuwinB/Portfolio (Branch: main, Commit: 8c65d43)
Previous build cache not available
Cloning completed: 7.280s
Running "vercel build"
Vercel CLI 28.10.0
Installing dependencies...
npm WARN deprecated w3c-hr-time@1.0.2: Use your platform's native performance.now() and performance.timeOrigin.
npm WARN deprecated stable@0.1.8: Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility
npm WARN deprecated rollup-plugin-terser@7.0.2: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-terser
npm WARN deprecated sourcemap-codec@1.4.8: Please use @jridgewell/sourcemap-codec instead
npm WARN deprecated svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x.
npm ERR! code 1
npm ERR! path /vercel/path0/node_modules/core-js
npm ERR! command failed
npm ERR! command sh -c -- node -e "try{require('./postinstall')}catch(e){}"
npm ERR! node: /lib64/libm.so.6: version `GLIBC_2.27' not found (required by node)
npm ERR! node: /lib64/libc.so.6: version `GLIBC_2.28' not found (required by node)
npm ERR! A complete log of this run can be found in:
npm ERR!     /vercel/.npm/_logs/2022-12-24T20_27_39_115Z-debug-0.log
Error: Command "npm install" exited with 1
</code>```

I am trying to upload the web app via github

I was expecting a smooth deploy with no errors

Body:
When in the build process these errors throw up

Cloning github.com/AshuwinB/Portfolio (Branch: main, Commit: 8c65d43)
Previous build cache not available
Cloning completed: 7.280s
Running "vercel build"
Vercel CLI 28.10.0
Installing dependencies...
npm WARN deprecated w3c-hr-time@1.0.2: Use your platform's native performance.now() and performance.timeOrigin.
npm WARN deprecated stable@0.1.8: Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility
npm WARN deprecated rollup-plugin-terser@7.0.2: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-terser
npm WARN deprecated sourcemap-codec@1.4.8: Please use @jridgewell/sourcemap-codec instead
npm WARN deprecated svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x.
npm ERR! code 1
npm ERR! path /vercel/path0/node_modules/core-js
npm ERR! command failed
npm ERR! command sh -c -- node -e "try{require('./postinstall')}catch(e){}"
npm ERR! node: /lib64/libm.so.6: version `GLIBC_2.27' not found (required by node)
npm ERR! node: /lib64/libc.so.6: version `GLIBC_2.28' not found (required by node)
npm ERR! A complete log of this run can be found in:
npm ERR!     /vercel/.npm/_logs/2022-12-24T20_27_39_115Z-debug-0.log
Error: Command "npm install" exited with 1

I am trying to upload the web app via github

I was expecting a smooth deploy with no errors


问:
Victory.js change fontSize of data of VictoryLegend, not the title but the data
```<code><VictoryLegend
        x={100}
        y={10}
        title="Legend"
        centerTitle
        orientation='horizontal'
        gutter={20}
        style={{title: {fontSize: 30}}}
        data={legendData}
        labels={<legendLabel/>}
      />
const legendLabel = (props) => {
    return (
      <text
        fontSize={24}
        textAnchor="middle"
        dominantBaseline="central"
        {...props}
      >
        {props.text}
      </text>
    );
  };
 const legendData= [
    {name: "Difficulty", symbol: {fill: "green", type: "square", size: 14}},
    {name: "Enjoyment", symbol: {fill: "blue", type: "square", size: 14}}
  ]
</code>```

So it seems that the component legendLabel doesn't get recognized, what am I doing wrong here? As it says in the title, I'm looking to change the fontSize or size of the data in the legend, not the title, I already did that.

Body:
<VictoryLegend
        x={100}
        y={10}
        title="Legend"
        centerTitle
        orientation='horizontal'
        gutter={20}
        style={{title: {fontSize: 30}}}
        data={legendData}
        labels={<legendLabel/>}
      />
const legendLabel = (props) => {
    return (
      <text
        fontSize={24}
        textAnchor="middle"
        dominantBaseline="central"
        {...props}
      >
        {props.text}
      </text>
    );
  };
 const legendData= [
    {name: "Difficulty", symbol: {fill: "green", type: "square", size: 14}},
    {name: "Enjoyment", symbol: {fill: "blue", type: "square", size: 14}}
  ]

So it seems that the component legendLabel doesn't get recognized, what am I doing wrong here? As it says in the title, I'm looking to change the fontSize or size of the data in the legend, not the title, I already did that.


问:
How do you scale decrementing money with strong consistency?
Imagine you have a number of accounts that record a number or money and you want to process very large numbers of operations deducting and adding to this number.

But the number of transactions is more than a single machine can handle. The list of ALL accounts and an integer fits on a single machine.

So we shard the accounts and each machine remembers a different partition of the account integer. The SUM(all machines of account X) = the overall balance

If there is a deduct operation and the account integer is greater or equal to the deduction amount, then this operation can be processed locally by that machine without coordination communication.
If a machine tries to deduct more than that machine has, the machine must communicate and coordinate with other machines.

I am thinking of a recursive DNS architecture where if a machine doesn't have enough of the integer, it would need to broadcast the deduction amount to other machines. Then the machine and that machine would have to coordinate an update to the new amount for each machine after the operation. This is expensive in terms of round trip time and adds latency.

How would you implement strongly consistent reads in this design?


问:
Can't connect to X11 window server using ':0' error when building Docker image on EC2
I'm attempting to build a Docker image to provision this software: https://fragpipe.nesvilab.org/docs/tutorial_setup_fragpipe.html

This is my Dockerfile in its current state:

```<code>FROM amazonlinux:2022
ENV DISPLAY=:0
ENV JAVA_HOME=/usr/lib/jvm/java-17-amazon-corretto.x86_64
COPY FragPipe-19.0.zip .
COPY MSFragger-20171106.zip .
RUN yum update -y \
&& yum upgrade -y \
&& yum install -y unzip java-17-amazon-corretto
RUN rpmkeys --import "http://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF" \
&& curl https://download.mono-project.com/repo/centos8-stable.repo | tee /etc/yum.repos.d/mono-centos8-stable.repo \
&& yum install -y mono-devel
RUN unzip MSFragger-20171106.zip \
&& rm MSFragger-20171106.zip
RUN unzip FragPipe-19.0.zip \
&& rm FragPipe-19.0.zip
RUN fragpipe/bin/fragpipe
</code>```

However, for hours now I've run into errors like this:

```<code>Exception in thread "main" java.awt.AWTError: Can't connect to X11 window server using ':0' as the value of the DISPLAY variable.
</code>```

I've tried multiple fixes, including using the official AWS corretto Docker image amazoncorretto:17-al2022-RC-headful, and manually installing the Java system dependencies. However, I continue to get this error.

Before I spend any more time troubleshooting this, I'm curious if the fact that I'm running this on EC2 has any effect on whether or not X11 will work?

Body:
I'm attempting to build a Docker image to provision this software: https://fragpipe.nesvilab.org/docs/tutorial_setup_fragpipe.html

This is my Dockerfile in its current state:

FROM amazonlinux:2022
ENV DISPLAY=:0
ENV JAVA_HOME=/usr/lib/jvm/java-17-amazon-corretto.x86_64
COPY FragPipe-19.0.zip .
COPY MSFragger-20171106.zip .
RUN yum update -y \
&& yum upgrade -y \
&& yum install -y unzip java-17-amazon-corretto
RUN rpmkeys --import "http://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF" \
&& curl https://download.mono-project.com/repo/centos8-stable.repo | tee /etc/yum.repos.d/mono-centos8-stable.repo \
&& yum install -y mono-devel
RUN unzip MSFragger-20171106.zip \
&& rm MSFragger-20171106.zip
RUN unzip FragPipe-19.0.zip \
&& rm FragPipe-19.0.zip
RUN fragpipe/bin/fragpipe

However, for hours now I've run into errors like this:

Exception in thread "main" java.awt.AWTError: Can't connect to X11 window server using ':0' as the value of the DISPLAY variable.

I've tried multiple fixes, including using the official AWS corretto Docker image amazoncorretto:17-al2022-RC-headful, and manually installing the Java system dependencies. However, I continue to get this error.

Before I spend any more time troubleshooting this, I'm curious if the fact that I'm running this on EC2 has any effect on whether or not X11 will work?


问:
Trying to connect from a docker container to docker host running Django in development mode gets connection refused
I'm running a django development server in my Debian GNU/Linux host machine with python manage.py runserver.

After running a Debian docker container with

$ docker run -it --add-host=host.docker.internal:host-gateway debian bash

I expected I could make a curl in http://localhost:8000 with

curl http://host.docker.internal:8000

but I get

Failed to connect to host.docker.internal port 8000: Connection refused

Is it something related to running Django with python manage.py runserver?


问:
Implementation of an algorithm for simultaneous diagonalization
I am trying to write an implementation of an algorithm for the simultaneous diagonalization of two matrices (which are assumed to be simultaneously diagonalizable). However, the algorithm does not seem to converge. The algorithm is described in SIAM J. Matrix Anal. Appl. 14, 927 (1993).

Here is the first part of my code to set up a test case:

```<code>import numpy as np
import numpy.linalg as lin
from scipy.optimize import minimize

N = 3
# Unitary example matrix
X = np.array([
    [-0.54717736-0.43779416j,  0.26046313+0.11082439j, 0.56151027-0.33692186j],
    [-0.33452046-0.37890784j, -0.40907097-0.70730291j, -0.15344477+0.23100467j],
    [-0.31253864-0.39468687j,  0.05342909+0.49940543j, -0.70062586+0.05835082j]
])
# Generate eigenvalues
LA = np.diag(np.arange(0, N))
LB = np.diag(np.arange(N, 2*N))
# Generate simultaneously diagonalizable matrices
A = X @ LA @ np.conj(X).T
B = X @ LB @ np.conj(X).T
</code>```

This should generate two 3x3 matrices which are simultaneously diagonalizable, since they are constructed this way via X. The following code block then defines a few helper functions:

```<code>def off2(A, B):
    """Defines the distance from the matrices from
    their diagonal form.
    """
    C = np.abs(A) ** 2 + np.abs(B) ** 2
    diag_idx = np.diag_indices(N)
    C[diag_idx] = 0
    return np.sum(C)

def Rijcs(i, j, c, s):
    """Function R(i, j, c, s) from the paper, see
    Eq. (1) therein. Used for plane rotations in
    the plane ij.
    """
    res = np.eye(N, dtype=complex)
    res[i, i] = c
    res[i, j] = -np.conj(s)
    res[j, i] = s
    res[j, j] = np.conj(c)
    return res

def cs(theta, phi):
    """Parametrization for c and s."""
    c = np.cos(theta)
    s = np.exp(1j * phi) * np.sin(theta)
    return c, s
</code>```

With these definitions, the algorithm can be implemented:

```<code>tol = 1e-10

Q = np.eye(N, dtype=complex)

while True:
    off = off2(A, B)
    # Print statement for debugging purposes
    print(off)

    # Terminate if the result is converged
    if off <= tol * (lin.norm(A, "fro") + lin.norm(B, "fro")):
        break

    for i in range(N):
        for j in range(i + 1, N):

            def fij(c, s):
                aij = A[i, j]
                aji = A[j, i]
                aii = A[i, i]
                ajj = A[j, j]

                bij = B[i, j]
                bji = B[j, i]
                bii = B[i, i]
                bjj = B[j, j]

                x = np.array(
                    [
                        [np.conj(aij), np.conj(aii - ajj), -np.conj(aji)],
                        [aji,                 (aii - ajj), -aij         ],
                        [np.conj(bij), np.conj(bii - bjj), -np.conj(bji)],
                        [bji,                 (bii - bjj), -bij         ]
                    ]
                )
                y = np.array(
                    [
                        [c ** 2],
                        [c * s],
                        [s ** 2]
                    ]
                )

                return lin.norm(x @ y, 2)

            # 5
            result = minimize(
                lambda x: fij(*cs(x[0], x[1])),
                x0=(0, 0),
                bounds=(
                    (-0.25 * np.pi, 0.25 * np.pi),
                    (-np.pi, np.pi)
                ),
            )
            theta, phi = result['x']
            c, s = cs(theta, phi)

            # 6
            R = Rijcs(i, j, c, s)

            # 7
            Q = Q @ R
            A = np.conj(R).T @ A @ R
            B = np.conj(R).T @ B @ R
</code>```

As you can observe from the print statement, the "distance" of A and B from diagonal form does not really converge. Instead, the values printed range from 0.5 up to 3 and oscillate up and down. Is there a bug in this code and if so, where exactly is it?

Body:
I am trying to write an implementation of an algorithm for the simultaneous diagonalization of two matrices (which are assumed to be simultaneously diagonalizable). However, the algorithm does not seem to converge. The algorithm is described in SIAM J. Matrix Anal. Appl. 14, 927 (1993).

Here is the first part of my code to set up a test case:

import numpy as np
import numpy.linalg as lin
from scipy.optimize import minimize

N = 3
# Unitary example matrix
X = np.array([
    [-0.54717736-0.43779416j,  0.26046313+0.11082439j, 0.56151027-0.33692186j],
    [-0.33452046-0.37890784j, -0.40907097-0.70730291j, -0.15344477+0.23100467j],
    [-0.31253864-0.39468687j,  0.05342909+0.49940543j, -0.70062586+0.05835082j]
])
# Generate eigenvalues
LA = np.diag(np.arange(0, N))
LB = np.diag(np.arange(N, 2*N))
# Generate simultaneously diagonalizable matrices
A = X @ LA @ np.conj(X).T
B = X @ LB @ np.conj(X).T

This should generate two 3x3 matrices which are simultaneously diagonalizable, since they are constructed this way via X. The following code block then defines a few helper functions:

def off2(A, B):
    """Defines the distance from the matrices from
    their diagonal form.
    """
    C = np.abs(A) ** 2 + np.abs(B) ** 2
    diag_idx = np.diag_indices(N)
    C[diag_idx] = 0
    return np.sum(C)

def Rijcs(i, j, c, s):
    """Function R(i, j, c, s) from the paper, see
    Eq. (1) therein. Used for plane rotations in
    the plane ij.
    """
    res = np.eye(N, dtype=complex)
    res[i, i] = c
    res[i, j] = -np.conj(s)
    res[j, i] = s
    res[j, j] = np.conj(c)
    return res

def cs(theta, phi):
    """Parametrization for c and s."""
    c = np.cos(theta)
    s = np.exp(1j * phi) * np.sin(theta)
    return c, s

With these definitions, the algorithm can be implemented:

tol = 1e-10

Q = np.eye(N, dtype=complex)

while True:
    off = off2(A, B)
    # Print statement for debugging purposes
    print(off)

    # Terminate if the result is converged
    if off <= tol * (lin.norm(A, "fro") + lin.norm(B, "fro")):
        break

    for i in range(N):
        for j in range(i + 1, N):

            def fij(c, s):
                aij = A[i, j]
                aji = A[j, i]
                aii = A[i, i]
                ajj = A[j, j]

                bij = B[i, j]
                bji = B[j, i]
                bii = B[i, i]
                bjj = B[j, j]

                x = np.array(
                    [
                        [np.conj(aij), np.conj(aii - ajj), -np.conj(aji)],
                        [aji,                 (aii - ajj), -aij         ],
                        [np.conj(bij), np.conj(bii - bjj), -np.conj(bji)],
                        [bji,                 (bii - bjj), -bij         ]
                    ]
                )
                y = np.array(
                    [
                        [c ** 2],
                        [c * s],
                        [s ** 2]
                    ]
                )

                return lin.norm(x @ y, 2)

            # 5
            result = minimize(
                lambda x: fij(*cs(x[0], x[1])),
                x0=(0, 0),
                bounds=(
                    (-0.25 * np.pi, 0.25 * np.pi),
                    (-np.pi, np.pi)
                ),
            )
            theta, phi = result['x']
            c, s = cs(theta, phi)

            # 6
            R = Rijcs(i, j, c, s)

            # 7
            Q = Q @ R
            A = np.conj(R).T @ A @ R
            B = np.conj(R).T @ B @ R

As you can observe from the print statement, the "distance" of A and B from diagonal form does not really converge. Instead, the values printed range from 0.5 up to 3 and oscillate up and down. Is there a bug in this code and if so, where exactly is it?


问:
Issue with RANK.AVG with Dynamic Array in Excel 365
I am doing some analysis of Wordle answers, and want to generate a single-cell analysis. First part is this, which works fine, to show the distribution of letters in the word list, and the distribution first letters in the word list:

```<code>=LET(
    wordList, Words,
    letters, CHAR(SEQUENCE(26, , CODE(C2))),
    counts, BYROW(letters, LAMBDA(l, REDUCE(0, wordList, LAMBDA(c, w, c + wordLetterCount(w, l))))),
    starts, BYROW(letters, LAMBDA(l, REDUCE(0, wordList, LAMBDA(c, w, IF(LEFT(w, 1) = l, c + 1, c))))),
    header, {"Letter", "Counts", "First"},
    data, HSTACK(letters, counts, starts),
    VSTACK(header, data)
)
</code>```

The result is a table like this...

Letters
Counts
First

a
975
140

b
280
173

...
...
...

I now want to add a column that shows the rank of letters in the counts columns... so I try to add a row like this into the LET:

```<code>    rank_counts, BYROW(counts, LAMBDA(c, RANK.AVG(c, counts))),
</code>```

This line on its own doesn't cause an error, but as soon as I try to do something with rank_counts I get #CALC! error.. even just trying to show it on its own:

```<code>=LET(
    wordList, Words,
    letters, CHAR(SEQUENCE(26, , CODE(C2))),
    counts, BYROW(letters, LAMBDA(l, REDUCE(0, wordList, LAMBDA(c, w, c + wordLetterCount(w, l))))),
    rank_counts, BYROW(counts, LAMBDA(c, RANK.AVG(c, counts))),
    starts, BYROW(letters, LAMBDA(l, REDUCE(0, wordList, LAMBDA(c, w, IF(LEFT(w, 1) = l, c + 1, c))))),
    rank_counts
)
</code>```

Feel like I must be doing something stupid here, because the error occurs when I try to use the array, not when I try to calculate it.

Any help please? Tx.

Body:
I am doing some analysis of Wordle answers, and want to generate a single-cell analysis. First part is this, which works fine, to show the distribution of letters in the word list, and the distribution first letters in the word list:

=LET(
    wordList, Words,
    letters, CHAR(SEQUENCE(26, , CODE(C2))),
    counts, BYROW(letters, LAMBDA(l, REDUCE(0, wordList, LAMBDA(c, w, c + wordLetterCount(w, l))))),
    starts, BYROW(letters, LAMBDA(l, REDUCE(0, wordList, LAMBDA(c, w, IF(LEFT(w, 1) = l, c + 1, c))))),
    header, {"Letter", "Counts", "First"},
    data, HSTACK(letters, counts, starts),
    VSTACK(header, data)
)

The result is a table like this...

Letters
Counts
First

a
975
140

b
280
173

...
...
...

I now want to add a column that shows the rank of letters in the counts columns... so I try to add a row like this into the LET:

    rank_counts, BYROW(counts, LAMBDA(c, RANK.AVG(c, counts))),

This line on its own doesn't cause an error, but as soon as I try to do something with rank_counts I get #CALC! error.. even just trying to show it on its own:

=LET(
    wordList, Words,
    letters, CHAR(SEQUENCE(26, , CODE(C2))),
    counts, BYROW(letters, LAMBDA(l, REDUCE(0, wordList, LAMBDA(c, w, c + wordLetterCount(w, l))))),
    rank_counts, BYROW(counts, LAMBDA(c, RANK.AVG(c, counts))),
    starts, BYROW(letters, LAMBDA(l, REDUCE(0, wordList, LAMBDA(c, w, IF(LEFT(w, 1) = l, c + 1, c))))),
    rank_counts
)

Feel like I must be doing something stupid here, because the error occurs when I try to use the array, not when I try to calculate it.

Any help please? Tx.


问:
ApolloServer (NodeJS): Return string response
I have an ApolloServer with default settings such as:

```<code>class AuditRemoteGraphQLDataSource extends RemoteGraphQLDataSource {
   ...
}
const gateway = new ApolloGateway({
    serviceList,
    buildService: ({url}) => new AuditRemoteGraphQLDataSource({url})
});

const server = new ApolloServer({
    debug: false,
    gateway,
    context: async ({req}) => {
    .........
}
</code>```

Upon making a request (query/mutation), we expect:
{
"data": {
"something": "somevalue"
}
}

This works fine. The challenge I am having is that for a specific GET request, I want to return a string as is. I tried to extend:

```<code> async didReceiveResponse(response, req, context) {
        const body = await super.didReceiveResponse(response, req, context);
        body.data = "someString";
        return body;
    }
</code>```

But it did not help.

Body:
I have an ApolloServer with default settings such as:

class AuditRemoteGraphQLDataSource extends RemoteGraphQLDataSource {
   ...
}
const gateway = new ApolloGateway({
    serviceList,
    buildService: ({url}) => new AuditRemoteGraphQLDataSource({url})
});

const server = new ApolloServer({
    debug: false,
    gateway,
    context: async ({req}) => {
    .........
}

Upon making a request (query/mutation), we expect:
{
"data": {
"something": "somevalue"
}
}

This works fine. The challenge I am having is that for a specific GET request, I want to return a string as is. I tried to extend:

 async didReceiveResponse(response, req, context) {
        const body = await super.didReceiveResponse(response, req, context);
        body.data = "someString";
        return body;
    }

But it did not help.


问:
Pandas Array memory
everybody. We are building a book recommendation system. We have several columns. We have added these columns together. After stacking the columns, calculating their cosine similarity. At this point there are about 100,000 x 100,000 rows and columns, and python throws an out-of-memory error (unable to allocate due to out-of-memory). We want to insert it into the pandas array. It showed insufficient 100+ gb for allocation. Need advice from those who have helped and solved this problem. Thanks in advance.</p>

Title: Pandas Array memory


问:
Is it possible to connect SDL2_net client to Node.js server using WebSockets?
When I start the client:

    const char *host = "ws://localhost";
    IPaddress ip;
    if(SDLNet_ResolveHost(&ip, host, 3000) == -1)
    {
        std::cout << "ER: SDLNet_ResolveHost: " <<
            SDLNet_GetError() << std::endl;
    }
```
<p>I see this messsage:</p>
<blockquote>
<p>ER: SDLNet_ResolveHost:</p>
</blockquote>
<p>Is it possible to connect SDL2_net client to Node.js server using WebSockets?</p>
<p>Server:</p>
<p>app.js</p>
<pre class="lang-js prettyprint-override"><code>const express = require("express");
const http = require("http");
const ws = require("ws");
const path = require("path");

const app = express();
const httpServer = http.createServer(app);

const wss = new ws.Server(
{
    server: httpServer
});

const port = process.env.PORT || 3000;
httpServer.listen(port, () => console.log("Listening at port: " + port));

wss.on("connection", socket =>
{
    console.log("client was connected");
});
</code>```

Body:
When I start the client:

    const char *host = "ws://localhost";
    IPaddress ip;
    if(SDLNet_ResolveHost(&ip, host, 3000) == -1)
    {
        std::cout << "ER: SDLNet_ResolveHost: " <<
            SDLNet_GetError() << std::endl;
    }

I see this messsage:

ER: SDLNet_ResolveHost:

Is it possible to connect SDL2_net client to Node.js server using WebSockets?

Server:

app.js

const express = require("express");
const http = require("http");
const ws = require("ws");
const path = require("path");

const app = express();
const httpServer = http.createServer(app);

const wss = new ws.Server(
{
    server: httpServer
});

const port = process.env.PORT || 3000;
httpServer.listen(port, () => console.log("Listening at port: " + port));

wss.on("connection", socket =>
{
    console.log("client was connected");
});