问:
Why do my arrays display missing values when identifying a bandwidth? (geopandas)
I'm trying to identify a suitable bandwidth to use for a geographically weighted regression but every time I search for the bandwidth it displays that there are missing (NaN) values within the arrays of the dataset. Although, each row features all values.

```<code>g_y = df_ct2008xy['2008 HP'].values.reshape((-1,1))
g_X = df_ct2008xy[['2008 AF', '2008 MI', '2008 MP', '2008 EB']].values
u = df_ct2008xy['X']
v = df_ct2008xy['Y']

g_coords = list(zip(u,v))

g_X = (g_X - g_X.mean(axis=0)) / g_X.std(axis=0)
g_y = g_y.reshape((-1,1))
g_y = (g_y - g_y.mean(axis=0)) / g_y.std(axis=0)

bw = mgwr.sel_bw.Sel_BW(g_coords,
                  g_y, # Independent variable
                  g_X, # Dependent variable
                  fixed=True, # True for fixed bandwidth and false for adaptive bandwidth
                  spherical=True) # Spherical coordinates (long-lat) or projected coordinates
</code>```

I searched using numpy to identify if these were individual values using

```<code>np.isnan(g_y).any()
</code>```

and

```<code>np.isnan(g_X)
</code>```

but apparently every value is 'missing' and returning 'True'

Body:
I'm trying to identify a suitable bandwidth to use for a geographically weighted regression but every time I search for the bandwidth it displays that there are missing (NaN) values within the arrays of the dataset. Although, each row features all values.

g_y = df_ct2008xy['2008 HP'].values.reshape((-1,1))
g_X = df_ct2008xy[['2008 AF', '2008 MI', '2008 MP', '2008 EB']].values
u = df_ct2008xy['X']
v = df_ct2008xy['Y']

g_coords = list(zip(u,v))

g_X = (g_X - g_X.mean(axis=0)) / g_X.std(axis=0)
g_y = g_y.reshape((-1,1))
g_y = (g_y - g_y.mean(axis=0)) / g_y.std(axis=0)

bw = mgwr.sel_bw.Sel_BW(g_coords,
                  g_y, # Independent variable
                  g_X, # Dependent variable
                  fixed=True, # True for fixed bandwidth and false for adaptive bandwidth
                  spherical=True) # Spherical coordinates (long-lat) or projected coordinates

I searched using numpy to identify if these were individual values using

np.isnan(g_y).any()

and

np.isnan(g_X)

but apparently every value is 'missing' and returning 'True'


来源: stackexchange

问:
Having trouble with external javascript
I am having a very especific and strange problem: some things are working on the internal javascript, but not working on the external file. The source is ok, i can console.log things and use functions called by buttons etc. but the code here doesn't work on the external, only on the internal

html

```<code><!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rock-Scissor-Paper</title>
<script src="rock-paper-scissors.js"></script>
</head>
<body>
    <h1>Rock-Paper-Scissors</h1>

<div class="you-area">

<div> <br><br><br></br>
    <span class="btn">rock</span>
    <span class="btn">paper</span>
    <span class="btn">scissors</span>
</div>

</div>
</body>
</html>
<style>
    body{text-align: center;}

    .btn
    {color: red;
    padding-right: 5rem;}

    .btn:hover
    {
        cursor: pointer;
    }
</style>
</code>```

external js file:

```<code>const btns = document.querySelectorAll('.btn');

btns.forEach((item) =>{
    item.addEventListener("click", (event) =>{
        console.log('is it working?');

    })})
</code>```

i tested the source, i don't have no extension installd except for Live Server. I use vscode and vanilla javascript.

ContentLicense: CC BY-SA 4.0

Title: Having trouble with external javascript

Body:
I am having a very especific and strange problem: some things are working on the internal javascript, but not working on the external file. The source is ok, i can console.log things and use functions called by buttons etc. but the code here doesn't work on the external, only on the internal

html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rock-Scissor-Paper</title>

Rock-Paper-Scissors

    rock
    paper
    scissors

external js file:

const btns = document.querySelectorAll('.btn');

btns.forEach((item) =>{
    item.addEventListener("click", (event) =>{
        console.log('is it working?');

    })})

i tested the source, i don't have no extension installd except for Live Server. I use vscode and vanilla javascript.


问:
RangeError (index): Invalid value: Valid value range is empty: 4
im in learning process of flutter so im created tic-tac-toe. i wanna use provider class to learn it better but im facing some problem. i runed my app when it was in one screen and it worked just fine but when im using provider the datas are not transforming. can anyone please help me how to send that data? also can someone please tell me where to improve my programming skills?

checkwinner() is  the function i wanna pass to layout widget.

```<code>class GameProvider with ChangeNotifier {
  List displayXO = ['', '', '', '', '', '', '', '', ''];
  String resultDetection = '';
  int oScores = 0;
  int xScores = 0;
  int filledSquares = 0;
  bool oTrue = true;
  bool playing = true;

  void tapped(int tap) {
    if (oTrue && displayXO[tap] == '') {
      displayXO[tap] = 'O';
      oTrue = false;
    } else if (!oTrue && displayXO[tap] == '') {
      displayXO[tap] = 'X';
      oTrue = true;
    }
    checkWinner();
  }

  checkWinner() {
    // checking 1 row
    if ((displayXO[0] == displayXO[1]) &&
        (displayXO[0] == displayXO[2]) &&
        displayXO[0] != '') {
      resultDetection = 'player ' + displayXO[0] + ' wins';
    }
    // checking 2 row
    if ((displayXO[3] == displayXO[4]) &&
        (displayXO[3] == displayXO[5]) &&
        (displayXO[3] != '')) {
      resultDetection = 'player ' + displayXO[3] + ' wins';
    }
    // checking 3 row
    if ((displayXO[6] == displayXO[7]) &&
        (displayXO[6] == displayXO[8]) &&
        (displayXO[6] != '')) {
      resultDetection = 'player ' + displayXO[6] + ' wins';
    }
    // checking 1 column
    if ((displayXO[0] == displayXO[3]) &&
        (displayXO[0] == displayXO[6]) &&
        (displayXO[0] != '')) {
      resultDetection = 'player ' + displayXO[0] + ' wins';
    }
    // checking 2 column
    if ((displayXO[1] == displayXO[4]) &&
        (displayXO[1] == displayXO[7]) &&
        (displayXO[1] != '')) {
      resultDetection = 'player ' + displayXO[1] + ' wins';
    }
    // checking 3 column
    if ((displayXO[2] == displayXO[5]) &&
        (displayXO[2] == displayXO[8]) &&
        (displayXO[2] != '')) {
      resultDetection = 'player ' + displayXO[2] + ' wins';
    }
    // checking 1 axis
    if ((displayXO[6] == displayXO[4]) &&
        (displayXO[6] == displayXO[2]) &&
        (displayXO[6] != '')) {
      resultDetection = 'player ' + displayXO[6] + ' wins';
    }
    // checking 2 axis
    if ((displayXO[0] == displayXO[4]) &&
        (displayXO[0] == displayXO[8]) &&
        (displayXO[0] != '')) {
      resultDetection = 'player ' + displayXO[0] + ' wins';
    }
    notifyListeners();
  }

  void upgrateScores(String winner) {
    if (winner == 'O') {
      oScores++;
    } else if (winner == 'X') {
      xScores++;
    }
  }

  // retry
  void newgame() {
    for (int i = 0; i < 9; i++) {
      displayXO[i] = '';
    }
    resultDetection = '';
    filledSquares = 0;
  }

  get winnerfunction => checkWinner();
  get result => resultDetection;
  get filled => filledSquares;
}
</code>```

and this is my layout widget where I wanned the function to work in

```<code>class Layout extends StatefulWidget {
  const Layout({super.key});

  @override
  State<Layout> createState() => _LayoutState();
}

class _LayoutState extends State<Layout> {
  bool oTrue = true;
  List displayXO = ['', '', '', '', '', '', '', '', ''];
  String resultDetection = '';

  // @override
  // void initState() {
  //   super.initState();
  //   GameProvider provider = Provider.of<GameProvider>(context, listen: false);
  //   setState(() {
  //     provider.tapp;
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    void _tap() {}
    return GridView.builder(
        itemCount: 9,
        gridDelegate:
            const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
        itemBuilder: ((context, index) {
          return GestureDetector(
            onTap: () {
              // tapped(index);
            },
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15),
                border: Border.all(width: 5, color: Colors.red),
                color: Colors.yellow,
              ),
              child: Center(
                child: Text(
                  displayXO[index],
                  style: GoogleFonts.coiny(fontSize: 64, color: Colors.red),
                ),
              ),
            ),
          );
        }));
  }

  void tapped(int tap) {
    setState(() {
      GameProvider provider = Provider.of(context, listen: false);
      num filled = provider.filled;
      if (oTrue && displayXO[tap] == '') {
        displayXO[tap] = 'O';
        oTrue = false;
        filled++;
      } else if (!oTrue && displayXO[tap] == '') {
        displayXO[tap] = 'X';
        oTrue = true;
        filled++;
      }
      // checkWinner();
    });
  }
}
</code>```

im trying to pass the function to another function in widget ive tried using getter but i wasn't useful

Body:
im in learning process of flutter so im created tic-tac-toe. i wanna use provider class to learn it better but im facing some problem. i runed my app when it was in one screen and it worked just fine but when im using provider the datas are not transforming. can anyone please help me how to send that data? also can someone please tell me where to improve my programming skills?

checkwinner() is  the function i wanna pass to layout widget.

class GameProvider with ChangeNotifier {
  List displayXO = ['', '', '', '', '', '', '', '', ''];
  String resultDetection = '';
  int oScores = 0;
  int xScores = 0;
  int filledSquares = 0;
  bool oTrue = true;
  bool playing = true;

  void tapped(int tap) {
    if (oTrue && displayXO[tap] == '') {
      displayXO[tap] = 'O';
      oTrue = false;
    } else if (!oTrue && displayXO[tap] == '') {
      displayXO[tap] = 'X';
      oTrue = true;
    }
    checkWinner();
  }

  checkWinner() {
    // checking 1 row
    if ((displayXO[0] == displayXO[1]) &&
        (displayXO[0] == displayXO[2]) &&
        displayXO[0] != '') {
      resultDetection = 'player ' + displayXO[0] + ' wins';
    }
    // checking 2 row
    if ((displayXO[3] == displayXO[4]) &&
        (displayXO[3] == displayXO[5]) &&
        (displayXO[3] != '')) {
      resultDetection = 'player ' + displayXO[3] + ' wins';
    }
    // checking 3 row
    if ((displayXO[6] == displayXO[7]) &&
        (displayXO[6] == displayXO[8]) &&
        (displayXO[6] != '')) {
      resultDetection = 'player ' + displayXO[6] + ' wins';
    }
    // checking 1 column
    if ((displayXO[0] == displayXO[3]) &&
        (displayXO[0] == displayXO[6]) &&
        (displayXO[0] != '')) {
      resultDetection = 'player ' + displayXO[0] + ' wins';
    }
    // checking 2 column
    if ((displayXO[1] == displayXO[4]) &&
        (displayXO[1] == displayXO[7]) &&
        (displayXO[1] != '')) {
      resultDetection = 'player ' + displayXO[1] + ' wins';
    }
    // checking 3 column
    if ((displayXO[2] == displayXO[5]) &&
        (displayXO[2] == displayXO[8]) &&
        (displayXO[2] != '')) {
      resultDetection = 'player ' + displayXO[2] + ' wins';
    }
    // checking 1 axis
    if ((displayXO[6] == displayXO[4]) &&
        (displayXO[6] == displayXO[2]) &&
        (displayXO[6] != '')) {
      resultDetection = 'player ' + displayXO[6] + ' wins';
    }
    // checking 2 axis
    if ((displayXO[0] == displayXO[4]) &&
        (displayXO[0] == displayXO[8]) &&
        (displayXO[0] != '')) {
      resultDetection = 'player ' + displayXO[0] + ' wins';
    }
    notifyListeners();
  }

  void upgrateScores(String winner) {
    if (winner == 'O') {
      oScores++;
    } else if (winner == 'X') {
      xScores++;
    }
  }

  // retry
  void newgame() {
    for (int i = 0; i < 9; i++) {
      displayXO[i] = '';
    }
    resultDetection = '';
    filledSquares = 0;
  }

  get winnerfunction => checkWinner();
  get result => resultDetection;
  get filled => filledSquares;
}

and this is my layout widget where I wanned the function to work in

class Layout extends StatefulWidget {
  const Layout({super.key});

  @override
  State<Layout> createState() => _LayoutState();
}

class _LayoutState extends State<Layout> {
  bool oTrue = true;
  List displayXO = ['', '', '', '', '', '', '', '', ''];
  String resultDetection = '';

  // @override
  // void initState() {
  //   super.initState();
  //   GameProvider provider = Provider.of<GameProvider>(context, listen: false);
  //   setState(() {
  //     provider.tapp;
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    void _tap() {}
    return GridView.builder(
        itemCount: 9,
        gridDelegate:
            const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
        itemBuilder: ((context, index) {
          return GestureDetector(
            onTap: () {
              // tapped(index);
            },
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15),
                border: Border.all(width: 5, color: Colors.red),
                color: Colors.yellow,
              ),
              child: Center(
                child: Text(
                  displayXO[index],
                  style: GoogleFonts.coiny(fontSize: 64, color: Colors.red),
                ),
              ),
            ),
          );
        }));
  }

  void tapped(int tap) {
    setState(() {
      GameProvider provider = Provider.of(context, listen: false);
      num filled = provider.filled;
      if (oTrue && displayXO[tap] == '') {
        displayXO[tap] = 'O';
        oTrue = false;
        filled++;
      } else if (!oTrue && displayXO[tap] == '') {
        displayXO[tap] = 'X';
        oTrue = true;
        filled++;
      }
      // checkWinner();
    });
  }
}

im trying to pass the function to another function in widget ive tried using getter but i wasn't useful


问:
how to make yoast seo read text from custom fields in custom post type
I have a WordPress website, in the website I am using a theme that defines a custom post called Recipe that used to add data for Food Recipe like steps and description for each stem and show it in a friendly UI/UX

currently, I am trying to enhance The SEO of my food recipes and I am using Yoast SEO for this purpose

```<code>Text length: The text contains 0 words. This is far below the recommended minimum of 300 words. Add more content.
</code>```

it does not read data from my custom post fields, I have searched a lot and tried a lot of plugins but all my attempts has failed

is there any way to make Yoast SEO analysis to read the text from my custom fields?

Body:
I have a WordPress website, in the website I am using a theme that defines a custom post called Recipe that used to add data for Food Recipe like steps and description for each stem and show it in a friendly UI/UX

currently, I am trying to enhance The SEO of my food recipes and I am using Yoast SEO for this purpose

Text length: The text contains 0 words. This is far below the recommended minimum of 300 words. Add more content.

it does not read data from my custom post fields, I have searched a lot and tried a lot of plugins but all my attempts has failed

is there any way to make Yoast SEO analysis to read the text from my custom fields?


问:
Blackberry swipe left/right gesture

Possible Duplicate:

  How may I use touch gestures to scroll through a series of pictures?

I want to display array of images one after another by using swipe left or swipe right gesture.Can anybody give me some idea as how to this.A simple example will be really useful.

ContentLicense: CC BY-SA 3.0

Title: Blackberry swipe left/right gesture


问:
"ValueError: setting an array element with a sequence" when trying to train model for CarRacing-v2 with OpenAI Gym
I'm trying to train RL-agent to play Car Racing environment with OpenAI Gym and been using following code:

```<code>import gym
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import VecFrameStack
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.evaluation import evaluate_policy
import os

environment_name = "CarRacing-v2"
env = gym.make(environment_name)
</code>```

used this for testing de environment

```<code>episodes = 5
for episode in range(1, episodes+1):
    state = env.reset()
    done = False
    truncated = False
    score = 0

    while not done and not truncated:
        env.render()
        action = env.action_space.sample()
        observation, reward, done, truncated, info = env.step(action)
        print(done)
        score+=reward
    print('Episode:{} Score:{}'.format(episode, score))
env.close()
</code>```

Then Trying to Train a model like so:

```<code>env = gym.make(environment_name)
env = DummyVecEnv([lambda: env])

log_path = os.path.join('Training', 'Logs')

model = PPO("CnnPolicy", env, verbose=1, tensorboard_log=log_path)
model.learn(total_timesteps=3000000)
</code>```

Im getting this error after the last line of code where I'm trying to get the model to learn:

```<code>model.learn(total_timesteps=3000000)
model.learn(total_timesteps=3000000)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-59-262f6d03e40c> in <module>
----> 1 model.learn(total_timesteps=3000000)

~\anaconda3\lib\site-packages\stable_baselines3\ppo\ppo.py in learn(self, total_timesteps, callback, log_interval, eval_env, eval_freq, n_eval_episodes, tb_log_name, eval_log_path, reset_num_timesteps, progress_bar)
    315     ) -> PPOSelf:
    316
--> 317         return super().learn(
    318             total_timesteps=total_timesteps,
    319             callback=callback,

~\anaconda3\lib\site-packages\stable_baselines3\common\on_policy_algorithm.py in learn(self, total_timesteps, callback, log_interval, eval_env, eval_freq, n_eval_episodes, tb_log_name, eval_log_path, reset_num_timesteps, progress_bar)
    244         iteration = 0
    245
--> 246         total_timesteps, callback = self._setup_learn(
    247             total_timesteps,
    248             eval_env,

~\anaconda3\lib\site-packages\stable_baselines3\common\base_class.py in _setup_learn(self, total_timesteps, eval_env, callback, eval_freq, n_eval_episodes, log_path, reset_num_timesteps, tb_log_name, progress_bar)
    487         # Avoid resetting the environment when calling ``.learn()`` consecutive times
    488         if reset_num_timesteps or self._last_obs is None:
--> 489             self._last_obs = self.env.reset()  # pytype: disable=annotation-type-mismatch
    490             self._last_episode_starts = np.ones((self.env.num_envs,), dtype=bool)
    491             # Retrieve unnormalized observation for saving into the buffer

~\anaconda3\lib\site-packages\stable_baselines3\common\vec_env\vec_transpose.py in reset(self)
    108         Reset all environments
    109         """
--> 110         return self.transpose_observations(self.venv.reset())
    111
    112     def close(self) -> None:

~\anaconda3\lib\site-packages\stable_baselines3\common\vec_env\dummy_vec_env.py in reset(self)
     62         for env_idx in range(self.num_envs):
     63             obs = self.envs[env_idx].reset()
---> 64             self._save_obs(env_idx, obs)
     65         return self._obs_from_buf()
     66

~\anaconda3\lib\site-packages\stable_baselines3\common\vec_env\dummy_vec_env.py in _save_obs(self, env_idx, obs)
     92         for key in self.keys:
     93             if key is None:
---> 94                 self.buf_obs[key][env_idx] = obs
     95             else:
     96                 self.buf_obs[key][env_idx] = obs[key]

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.
</code>```

Does anyone know how I can get around this?

OBS1:
I found that it has to do with the reset method on the env. When I run

```<code>env.reset()
</code>```

I'm getting the same error

Body:
I'm trying to train RL-agent to play Car Racing environment with OpenAI Gym and been using following code:

import gym
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import VecFrameStack
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.evaluation import evaluate_policy
import os

environment_name = "CarRacing-v2"
env = gym.make(environment_name)

used this for testing de environment

episodes = 5
for episode in range(1, episodes+1):
    state = env.reset()
    done = False
    truncated = False
    score = 0

    while not done and not truncated:
        env.render()
        action = env.action_space.sample()
        observation, reward, done, truncated, info = env.step(action)
        print(done)
        score+=reward
    print('Episode:{} Score:{}'.format(episode, score))
env.close()

Then Trying to Train a model like so:

env = gym.make(environment_name)
env = DummyVecEnv([lambda: env])

log_path = os.path.join('Training', 'Logs')

model = PPO("CnnPolicy", env, verbose=1, tensorboard_log=log_path)
model.learn(total_timesteps=3000000)

Im getting this error after the last line of code where I'm trying to get the model to learn:

model.learn(total_timesteps=3000000)
model.learn(total_timesteps=3000000)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-59-262f6d03e40c> in <module>
----> 1 model.learn(total_timesteps=3000000)

~\anaconda3\lib\site-packages\stable_baselines3\ppo\ppo.py in learn(self, total_timesteps, callback, log_interval, eval_env, eval_freq, n_eval_episodes, tb_log_name, eval_log_path, reset_num_timesteps, progress_bar)
    315     ) -> PPOSelf:
    316
--> 317         return super().learn(
    318             total_timesteps=total_timesteps,
    319             callback=callback,

~\anaconda3\lib\site-packages\stable_baselines3\common\on_policy_algorithm.py in learn(self, total_timesteps, callback, log_interval, eval_env, eval_freq, n_eval_episodes, tb_log_name, eval_log_path, reset_num_timesteps, progress_bar)
    244         iteration = 0
    245
--> 246         total_timesteps, callback = self._setup_learn(
    247             total_timesteps,
    248             eval_env,

~\anaconda3\lib\site-packages\stable_baselines3\common\base_class.py in _setup_learn(self, total_timesteps, eval_env, callback, eval_freq, n_eval_episodes, log_path, reset_num_timesteps, tb_log_name, progress_bar)
    487         # Avoid resetting the environment when calling ``.learn()`` consecutive times
    488         if reset_num_timesteps or self._last_obs is None:
--> 489             self._last_obs = self.env.reset()  # pytype: disable=annotation-type-mismatch
    490             self._last_episode_starts = np.ones((self.env.num_envs,), dtype=bool)
    491             # Retrieve unnormalized observation for saving into the buffer

~\anaconda3\lib\site-packages\stable_baselines3\common\vec_env\vec_transpose.py in reset(self)
    108         Reset all environments
    109         """
--> 110         return self.transpose_observations(self.venv.reset())
    111
    112     def close(self) -> None:

~\anaconda3\lib\site-packages\stable_baselines3\common\vec_env\dummy_vec_env.py in reset(self)
     62         for env_idx in range(self.num_envs):
     63             obs = self.envs[env_idx].reset()
---> 64             self._save_obs(env_idx, obs)
     65         return self._obs_from_buf()
     66

~\anaconda3\lib\site-packages\stable_baselines3\common\vec_env\dummy_vec_env.py in _save_obs(self, env_idx, obs)
     92         for key in self.keys:
     93             if key is None:
---> 94                 self.buf_obs[key][env_idx] = obs
     95             else:
     96                 self.buf_obs[key][env_idx] = obs[key]

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.

Does anyone know how I can get around this?

OBS1:
I found that it has to do with the reset method on the env. When I run

env.reset()

I'm getting the same error


问:
Order of execution of .sh files through group policy in linux
I have Redhat linux systems which are added to Windows domain and 2 group policy is pushing 2 executable files (.sh). The files are not being executed in the order of the group policy applied. Could someone please help if there is a special way RHEL or GPO handles the order of execution of .sh files in case multiple files are being pushed through GPO.

The executable files should have been run in the same precedence of the GPO from which they were pushed.


问:
Mapbox Maps SDK for iOS - Maps won't display anymore (or gets cut off)
Maps (from MapBox API) were working just fine in our app, but about a month they stopped displaying on a swiftui view. BUT the tricky thing is that the maps in some phones still work (or works partially but being cut off), and they still show the annotations/pins (see screenshot).

We have the MapBox Maps SDK for iOS installed as cocoapods into Xcode.

It's a simple app, it just detects a vehicle trip and add event points to the map (eg. point A as trip start, and point B as trip end).

Versions:
Xcode: 13.2.1
pod 'Mapbox-iOS-SDK', '~> 6.4.1'

pod 'MapboxNavigation', '~> 1.4.2'

Basically, the following is our main code to show the map.

Note: It also adds speeding, hard brake and rapid accelaration annotations to the map.

Does someone have any idea why the map is not showing properly?
Thanks much in advance.

```<code>
import SwiftUI
import Mapbox
import MapboxDirections
import Polyline

struct TestMapDriveView: View {
    var selectedTrip: VehicleTripData // The selected trip that needs to be shown
    @Binding var speedingCount: Int? // the number of speeding events in the selected trip
    @Binding var showCallouts: Bool // Whether to show callout when a point annotation is selected
    @Binding var showInfoSheet: Bool // whether show the event details view or not (show the details when the user tap on a specific marker on the map)
    @Binding var isFullScreen: Bool // whether show full screen map or not
    @Binding var selectedEncodedPolyline: String // The encoded polyline for the trip

    @State var alreadyClean: Bool = false
    @State var changed: Bool = false
    @State var showSpecificPoint = false // Whether focues on a specific trip point or not

    let action: () -> () //  Used to toggle the full screen state variable

    var body: some View {

        VStack {
            NavigationLink(destination: EmptyView(), label: {EmptyView()})
            NavigationLink(destination: EventDetails(tripPoint: selectedTripPoint, selectedTrip: selectedTrip, typeInfo: .constant(selectedTypeInfo))
                           , isActive: $showInfoSheet, label: {EmptyView()}).navigationTitle("").navigationBarTitle("").navigationBarHidden(true)

            MapboxMap(selectedTrip: selectedTrip, speedingCount: $speedingCount, showCallouts: $showCallouts, showInfoSheet: $showInfoSheet, isFullScreen: $isFullScreen, selectedEncodedPolyline: $selectedEncodedPolyline, alreadyClean: $alreadyClean, changed: $changed, showSpecificPoint: $showSpecificPoint)
                .onAppear {
                    showDetails = false
                    // The reason for adding a timer here is that since showDetails is a global variable,
                    // and it is not a state variable, we canot trigger its value
                    // We need a timer so that we can check the value of the showDetails every 0.1 second
                    Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
                        showInfoSheet = showDetails
                        if showInfoSheet {
                            isFullScreen = false
                            findTripPoint()
                            timer.invalidate()
                        }
                    }
                }
        }
    }
}

// MARK: - New Map Provided by MapBox
// MARK: - Since MapBox is designed to be implemented with the UIView, for SwiftUI, we need to transfer the UIView to View
struct MapboxMap: UIViewRepresentable {
    var selectedTrip: VehicleTripData
    @Binding var speedingCount: Int?
    @Binding var showCallouts: Bool
    @Binding var showInfoSheet: Bool
    @Binding var isFullScreen: Bool
    @Binding var selectedEncodedPolyline: String
    @Binding var alreadyClean: Bool
    @Binding var changed: Bool
    @Binding var showSpecificPoint: Bool

    private let mapView: MGLMapView = MGLMapView(frame: .zero, styleURL: MGLStyle.streetsStyleURL)

    class Coordinator: NSObject, MGLMapViewDelegate {
        var showCallouts: Bool

        init(showcallouts: Bool) {
            self.showCallouts = showcallouts
        }

        func mapView(_ mapView: MGLMapView, shapeAnnotationIsEnabled annotation: MGLShape) -> Bool {
            return annotation.title != nil && annotation.title != "Speeding"
        }

        // When you tap on a point on the map, whether show the callout or not
        func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
            if let title = annotation.title {
                return (!(title == "Speeding") && showCallouts)
            }
            else {
                return false
            }
        }

        // MARK: - This function is used to replace the default marker icon with our icons for specific events
        func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
            guard annotation is MGLPointAnnotation else {
                return nil
            }

            guard annotation.title != nil else {return nil}
            guard annotation.title! != nil else {return nil}

            if annotation.title != ""{

                let identifier = annotation.title!!
                print("error \(annotation.title)")
                var image = UIImage()
                if identifier.hasPrefix("Speeding") {
                    image = UIImage(named: "Speeding Marker")!
                } else if identifier.hasPrefix("Hard"){
                    image = UIImage(named: "Hard Brake Pin")!
                } else if identifier.hasPrefix("Rapid") {
                    image = UIImage(named: "Rapid Accel Pin")!
                } else {
                    image = UIImage(named: identifier)!
                }

                var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

                if annotationView == nil {
                    annotationView = MGLAnnotationView(annotation: annotation, reuseIdentifier: identifier as! String)
                    let imageView = UIImageView(image: image)
                    annotationView!.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
                    annotationView?.addSubview(imageView)
                    annotationView?.centerOffset = CGVector(dx: 0, dy: -image.size.height / 2.0)
                }

                return annotationView
            }
            return nil
        }

        // MARK: - This function is executed when the user taps on "View Details"
        // In fact, we should set showInfoSheet to be true in order to show the EventDetailView
        // However, since we are using a coordinator here, we cannnot change showInfoSheet directly
        // Therefore, we change the global variable "showDetails" to be true
        @objc func labelAction(_ sender: UITapGestureRecognizer) {
            showDetails = true
        }

        // MARK: - Add the "View Details" Label in the Callout View
        // MARK: - We should use UIButtion, however, if we use UIButtion, it will never be shown. Need further tests
        func mapView(_ mapView: MGLMapView, leftCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? {

            guard let title = annotation.title else {return nil}

            if title != nil {
                if title!.hasPrefix("Speeding:") {
                    selectedTypeInfo = "speeding"
                } else if title!.hasPrefix("Hard") {
                    selectedTypeInfo = "hardBrake"
                } else if title!.hasPrefix("Rapid") {
                    selectedTypeInfo = "rapidAccel"
                } else {
                    return nil
                }
                let labelTap = UITapGestureRecognizer(target: self, action: #selector(labelAction(_:)))
                labelTap.numberOfTapsRequired = 1
                // Callout height is fixed; width expands to fit its content.
                let label = UILabel(frame: CGRect(x: 0, y: 0, width: 60, height: 50))
                label.textAlignment = .center
                label.textColor = UIColor(named: "Blue")
                label.text = "View Details"
                label.numberOfLines = 2
                label.font = UIFont(name: "NotoSans-Regular", size: 12)
                label.isUserInteractionEnabled = true
                label.addGestureRecognizer(labelTap)
                selectedCoor = annotation.coordinate
                return label
            }
            return nil
        }

        // MARK: - This function is used to change the color of the polyline based on the event name
        func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> UIColor {
            guard let title = annotation.title else {return UIColor(named: "Blue")!}
            if title.hasPrefix("Speeding") {
                return UIColor(named: "MapRed")!
            } else {
                return UIColor(named: "Blue")!
            }
        }
    }

    func makeCoordinator() -> MapboxMap.Coordinator {
        return Coordinator(showcallouts: showCallouts)
    }

    // MARK: - Initialize the MapView
    func makeUIView(context: Context) -> MGLMapView {
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.setCenter(CLLocationCoordinate2D(latitude: selectedTrip.startedLatitude!, longitude: selectedTrip.startedLongitude!), animated: true)
        mapView.delegate = context.coordinator

        return mapView
    }

    func updateUIView(_ uiView: MGLMapView, context: Context) {
        if (uiView.annotations ?? []).count == 0 {
            mapViewDidFinishLoadingMap(uiView, didFinishLoading: MGLStyle())
        }
    }

    func mapViewDidFinishLoadingMap(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) {
        mapView.isRotateEnabled = false

        // MARK: - Get the result from the encoded polyline string
        let result = Polyline.init(encodedPolyline: selectedEncodedPolyline, encodedLevels: .none)

        // MARK: - Get the coordinates in the polyline for the trip
        let coordinates = result.coordinates

        guard let tripPoints = coordinates else {return}

        // MARK: - Get the start and end point
        let startPoint: CLLocationCoordinate2D = coordinates?.first ?? CLLocationCoordinate2D(latitude: 0, longitude: 0)
        let endPoint: CLLocationCoordinate2D = coordinates?.last ?? CLLocationCoordinate2D(latitude: 0, longitude: 0)

        var startTripPoint = MGLPointAnnotation()
        var endTripPoint = MGLPointAnnotation()

        startTripPoint.title = "Starting Point"
        startTripPoint.coordinate = startPoint
        endTripPoint.title = "End Point"
        endTripPoint.coordinate = endPoint
        mapView.addAnnotation(startTripPoint)
        mapView.addAnnotation(endTripPoint)

        let tryLine = MGLPolyline(coordinates: coordinates!, count: UInt(coordinates!.count))
        mapView.addAnnotation(tryLine)

        var speedingArray = [[TripPoint]]()

        DispatchQueue.global(qos: .background).async {
            // MARK: - Deal with the speeding events in the trip
            // MARK: - The speeding icon will be placed at the point which has the maximum speed for each speeding polyline
            var ctr = 0

            while ctr < selectedTrip.speedingPoints!.count{
                var speedPath = [TripPoint]()
                speedPath.append(selectedTrip.speedingPoints![ctr])
                while ctr + 1 < selectedTrip.speedingPoints!.count && selectedTrip.speedingPoints![ctr + 1].timeStamp!.timeIntervalSince1970 - selectedTrip.speedingPoints![ctr].timeStamp!.timeIntervalSince1970 < 10{
                    speedPath.append(selectedTrip.speedingPoints![ctr+1])
                    ctr += 1
                }
                speedingArray.append(speedPath)
                ctr += 1
            }

            for speedingLine in speedingArray {
                var maxDelta = 0.0
                var maxDeltaPoint:TripPoint? = nil
                var path: [CLLocationCoordinate2D] = []
                for speedingPoint in speedingLine{
                    path.append(CLLocationCoordinate2D(latitude: speedingPoint.latitude!, longitude: speedingPoint.longitude!))
                    if speedingPoint.speed_limit_delta! > maxDelta{
                        maxDelta = speedingPoint.speed_limit_delta!
                        maxDeltaPoint = speedingPoint

                    }
                }

                if let markerPoint = maxDeltaPoint{
                    tripPointsArray.append(markerPoint)
                    var speedMarker = MGLPointAnnotation()
                    speedMarker.coordinate = CLLocationCoordinate2D(latitude: markerPoint.latitude!, longitude: markerPoint.longitude!)
                    speedMarker.title = "Speeding: \(Int(markerPoint.speed!)) " + markerPoint.speedUnit!
                    let speedLimitBR = Double(markerPoint.speed!) - markerPoint.speed_limit_delta! //before rounding
                    var speedLimit = 10 * Int((speedLimitBR / 10.0).rounded())//round to nearest 10
                    speedMarker.subtitle = "Speed Limit: ~ \(speedLimit) " + markerPoint.speedUnit!

                    DispatchQueue.main.async {
                        mapView.addAnnotation(speedMarker)
                    }
                }

                let speedingPolyline = MGLPolyline(coordinates: path, count: UInt(path.count))
                speedingPolyline.title = "Speeding"
                DispatchQueue.main.async {
                    mapView.addAnnotation(speedingPolyline)
                }

            }
            speedingCount = speedingArray.count

            // MARK: - Deal with hard brakes in the trip
            for hardBrakePoint in selectedTrip.hardBrakePoints!{
                tripPointsArray.append(hardBrakePoint)
                let hardBrakeMarker = MGLPointAnnotation()
                hardBrakeMarker.coordinate = CLLocationCoordinate2D(latitude: hardBrakePoint.latitude!, longitude: hardBrakePoint.longitude!)
                hardBrakeMarker.title = "Hard Brake"
                hardBrakeMarker.subtitle = "Acceleration: \(String(format: "%.1f", hardBrakePoint.acceleration! * 3.6)) " + "km/h/s"
                DispatchQueue.main.async {
                    mapView.addAnnotation(hardBrakeMarker)
                }
            }

            // MARK: - Deal with rapid accel in the trip
            for rapidAccelPoint in selectedTrip.rapidAccelPoints!{
                tripPointsArray.append(rapidAccelPoint)
                let rapidAccelMarker = MGLPointAnnotation()
                rapidAccelMarker.coordinate = CLLocationCoordinate2D(latitude: rapidAccelPoint.latitude!, longitude: rapidAccelPoint.longitude!)
                rapidAccelMarker.title = "Rapid Accel"
                rapidAccelMarker.subtitle = "Acceleration: \(String(format: "%.1f", rapidAccelPoint.acceleration! * 3.6)) " + "km/h/s"
                DispatchQueue.main.async {
                    mapView.addAnnotation(rapidAccelMarker)
                }
            }
        }

        // MARK: - If we are not in EventDetailView, then the mapView.showAnnotations will help us to zoom the map to the proper level so that all the markers and annotations in the map will be shown
        if !showSpecificPoint {
            Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { timer in
                guard let annotations = mapView.annotations else {return}
                mapView.showAnnotations(annotations, edgePadding: .init(top: 60, left: 40, bottom: 10, right: 40), animated: true, completionHandler: nil)
            }

        } else {
            // MARK: - If we need to zoom into a specific point, we need to find which point it is among all the trip points and zoom into that specific point
            var alreadyAdded = false
            var point = MGLPointAnnotation()

            point.coordinate = CLLocationCoordinate2D(latitude: selectedTripPoint.latitude ?? 0, longitude: selectedTripPoint.longitude ?? 0)

            for hardBrakePoint in selectedTrip.hardBrakePoints! {
                if hardBrakePoint.latitude == selectedTripPoint.latitude && hardBrakePoint.longitude == selectedTripPoint.longitude {
                    point.title = "Hard Brake"
                    point.subtitle = "Acceleration: \(String(format: "%.1f", hardBrakePoint.acceleration! * 3.6)) " + "km/h/s"
                    mapView.addAnnotation(point)
                    alreadyAdded = true
                    break
                }
            }

            if !alreadyAdded {
                for rapidAccelPoint in selectedTrip.rapidAccelPoints!{

                    if rapidAccelPoint.latitude == selectedTripPoint.latitude && rapidAccelPoint.longitude == selectedTripPoint.longitude {
                        point.title = "Rapid Accel"
                        point.title! += "Acceleration: \(String(format: "%.1f", rapidAccelPoint.acceleration! * 3.6)) " + "km/h/s"
                        mapView.addAnnotation(point)
                        alreadyAdded = true
                        break
                    }
                }
            }

            if !alreadyAdded {
                var presentPolyLine: MGLPolyline = MGLPolyline()
                for speedingLine in speedingArray{
                    var maxDelta = 0.0
                    var maxDeltaPoint:TripPoint? = nil
                    var path: [CLLocationCoordinate2D] = []
                    for speedingPoint in speedingLine{
                        path.append(CLLocationCoordinate2D(latitude: speedingPoint.latitude!, longitude: speedingPoint.longitude!))
                        if speedingPoint.speed_limit_delta! > maxDelta{
                            maxDelta = speedingPoint.speed_limit_delta!
                            maxDeltaPoint = speedingPoint
                        }
                    }

                    if let markerPoint = maxDeltaPoint{
                        if selectedTripPoint.latitude == markerPoint.latitude && selectedTripPoint.longitude == markerPoint.longitude {
                            let specificMarker = MGLPointAnnotation()
                            specificMarker.coordinate = CLLocationCoordinate2D(latitude: markerPoint.latitude ?? 0, longitude: markerPoint.longitude ?? 0)
                            var speedMarker = MGLPointAnnotation()
                            speedMarker.coordinate = CLLocationCoordinate2D(latitude: markerPoint.latitude!, longitude: markerPoint.longitude!)
                            speedMarker.title = "Speeding: \(Int(markerPoint.speed!)) " + markerPoint.speedUnit!
                            let speedLimitBR = Double(markerPoint.speed!) - markerPoint.speed_limit_delta! //before rounding
                            var speedLimit = 10 * Int((speedLimitBR / 10.0).rounded())//round to nearest 10
                            speedMarker.subtitle = "Speed Limit: ~ \(speedLimit) " + markerPoint.speedUnit!
                            point = speedMarker
                            DispatchQueue.main.async {
                                let speedingPolyline = MGLPolyline(coordinates: path, count: UInt(path.count))
                                speedingPolyline.title = "Speeding"
                                presentPolyLine = speedingPolyline
                            }
                            break
                        } else {
                            path.removeAll()
                        }
                    }
                }

                mapView.showAnnotations([point], edgePadding: .init(top: 60, left: 40, bottom: 10, right: 40), animated: true, completionHandler: nil)
            } else {
                mapView.showAnnotations([point], edgePadding: .init(top: -10, left: -10, bottom: -10, right: -10), animated: true, completionHandler: nil)
            }
        }
    }
}
</code>```

I tried updating the pods from 6.3 to 6.4.1 but it didn't work.

I know MapBox has a new framework as of v6.4.1 called v10, but I haven't installed yet cause that would change the whole code.
I am expecting to see the map as it was displaying before this new bug. eg. see screenshot

Body:
Maps (from MapBox API) were working just fine in our app, but about a month they stopped displaying on a swiftui view. BUT the tricky thing is that the maps in some phones still work (or works partially but being cut off), and they still show the annotations/pins (see screenshot).

We have the MapBox Maps SDK for iOS installed as cocoapods into Xcode.

It's a simple app, it just detects a vehicle trip and add event points to the map (eg. point A as trip start, and point B as trip end).

Versions:
Xcode: 13.2.1
pod 'Mapbox-iOS-SDK', '~> 6.4.1'

pod 'MapboxNavigation', '~> 1.4.2'

Basically, the following is our main code to show the map.

Note: It also adds speeding, hard brake and rapid accelaration annotations to the map.

Does someone have any idea why the map is not showing properly?
Thanks much in advance.

import SwiftUI
import Mapbox
import MapboxDirections
import Polyline

struct TestMapDriveView: View {
    var selectedTrip: VehicleTripData // The selected trip that needs to be shown
    @Binding var speedingCount: Int? // the number of speeding events in the selected trip
    @Binding var showCallouts: Bool // Whether to show callout when a point annotation is selected
    @Binding var showInfoSheet: Bool // whether show the event details view or not (show the details when the user tap on a specific marker on the map)
    @Binding var isFullScreen: Bool // whether show full screen map or not
    @Binding var selectedEncodedPolyline: String // The encoded polyline for the trip

    @State var alreadyClean: Bool = false
    @State var changed: Bool = false
    @State var showSpecificPoint = false // Whether focues on a specific trip point or not

    let action: () -> () //  Used to toggle the full screen state variable

    var body: some View {

        VStack {
            NavigationLink(destination: EmptyView(), label: {EmptyView()})
            NavigationLink(destination: EventDetails(tripPoint: selectedTripPoint, selectedTrip: selectedTrip, typeInfo: .constant(selectedTypeInfo))
                           , isActive: $showInfoSheet, label: {EmptyView()}).navigationTitle("").navigationBarTitle("").navigationBarHidden(true)

            MapboxMap(selectedTrip: selectedTrip, speedingCount: $speedingCount, showCallouts: $showCallouts, showInfoSheet: $showInfoSheet, isFullScreen: $isFullScreen, selectedEncodedPolyline: $selectedEncodedPolyline, alreadyClean: $alreadyClean, changed: $changed, showSpecificPoint: $showSpecificPoint)
                .onAppear {
                    showDetails = false
                    // The reason for adding a timer here is that since showDetails is a global variable,
                    // and it is not a state variable, we canot trigger its value
                    // We need a timer so that we can check the value of the showDetails every 0.1 second
                    Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
                        showInfoSheet = showDetails
                        if showInfoSheet {
                            isFullScreen = false
                            findTripPoint()
                            timer.invalidate()
                        }
                    }
                }
        }
    }
}

// MARK: - New Map Provided by MapBox
// MARK: - Since MapBox is designed to be implemented with the UIView, for SwiftUI, we need to transfer the UIView to View
struct MapboxMap: UIViewRepresentable {
    var selectedTrip: VehicleTripData
    @Binding var speedingCount: Int?
    @Binding var showCallouts: Bool
    @Binding var showInfoSheet: Bool
    @Binding var isFullScreen: Bool
    @Binding var selectedEncodedPolyline: String
    @Binding var alreadyClean: Bool
    @Binding var changed: Bool
    @Binding var showSpecificPoint: Bool

    private let mapView: MGLMapView = MGLMapView(frame: .zero, styleURL: MGLStyle.streetsStyleURL)

    class Coordinator: NSObject, MGLMapViewDelegate {
        var showCallouts: Bool

        init(showcallouts: Bool) {
            self.showCallouts = showcallouts
        }

        func mapView(_ mapView: MGLMapView, shapeAnnotationIsEnabled annotation: MGLShape) -> Bool {
            return annotation.title != nil && annotation.title != "Speeding"
        }

        // When you tap on a point on the map, whether show the callout or not
        func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
            if let title = annotation.title {
                return (!(title == "Speeding") && showCallouts)
            }
            else {
                return false
            }
        }

        // MARK: - This function is used to replace the default marker icon with our icons for specific events
        func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
            guard annotation is MGLPointAnnotation else {
                return nil
            }

            guard annotation.title != nil else {return nil}
            guard annotation.title! != nil else {return nil}

            if annotation.title != ""{

                let identifier = annotation.title!!
                print("error \(annotation.title)")
                var image = UIImage()
                if identifier.hasPrefix("Speeding") {
                    image = UIImage(named: "Speeding Marker")!
                } else if identifier.hasPrefix("Hard"){
                    image = UIImage(named: "Hard Brake Pin")!
                } else if identifier.hasPrefix("Rapid") {
                    image = UIImage(named: "Rapid Accel Pin")!
                } else {
                    image = UIImage(named: identifier)!
                }

                var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

                if annotationView == nil {
                    annotationView = MGLAnnotationView(annotation: annotation, reuseIdentifier: identifier as! String)
                    let imageView = UIImageView(image: image)
                    annotationView!.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
                    annotationView?.addSubview(imageView)
                    annotationView?.centerOffset = CGVector(dx: 0, dy: -image.size.height / 2.0)
                }

                return annotationView
            }
            return nil
        }

        // MARK: - This function is executed when the user taps on "View Details"
        // In fact, we should set showInfoSheet to be true in order to show the EventDetailView
        // However, since we are using a coordinator here, we cannnot change showInfoSheet directly
        // Therefore, we change the global variable "showDetails" to be true
        @objc func labelAction(_ sender: UITapGestureRecognizer) {
            showDetails = true
        }

        // MARK: - Add the "View Details" Label in the Callout View
        // MARK: - We should use UIButtion, however, if we use UIButtion, it will never be shown. Need further tests
        func mapView(_ mapView: MGLMapView, leftCalloutAccessoryViewFor annotation: MGLAnnotation) -> UIView? {

            guard let title = annotation.title else {return nil}

            if title != nil {
                if title!.hasPrefix("Speeding:") {
                    selectedTypeInfo = "speeding"
                } else if title!.hasPrefix("Hard") {
                    selectedTypeInfo = "hardBrake"
                } else if title!.hasPrefix("Rapid") {
                    selectedTypeInfo = "rapidAccel"
                } else {
                    return nil
                }
                let labelTap = UITapGestureRecognizer(target: self, action: #selector(labelAction(_:)))
                labelTap.numberOfTapsRequired = 1
                // Callout height is fixed; width expands to fit its content.
                let label = UILabel(frame: CGRect(x: 0, y: 0, width: 60, height: 50))
                label.textAlignment = .center
                label.textColor = UIColor(named: "Blue")
                label.text = "View Details"
                label.numberOfLines = 2
                label.font = UIFont(name: "NotoSans-Regular", size: 12)
                label.isUserInteractionEnabled = true
                label.addGestureRecognizer(labelTap)
                selectedCoor = annotation.coordinate
                return label
            }
            return nil
        }

        // MARK: - This function is used to change the color of the polyline based on the event name
        func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> UIColor {
            guard let title = annotation.title else {return UIColor(named: "Blue")!}
            if title.hasPrefix("Speeding") {
                return UIColor(named: "MapRed")!
            } else {
                return UIColor(named: "Blue")!
            }
        }
    }

    func makeCoordinator() -> MapboxMap.Coordinator {
        return Coordinator(showcallouts: showCallouts)
    }

    // MARK: - Initialize the MapView
    func makeUIView(context: Context) -> MGLMapView {
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.setCenter(CLLocationCoordinate2D(latitude: selectedTrip.startedLatitude!, longitude: selectedTrip.startedLongitude!), animated: true)
        mapView.delegate = context.coordinator

        return mapView
    }

    func updateUIView(_ uiView: MGLMapView, context: Context) {
        if (uiView.annotations ?? []).count == 0 {
            mapViewDidFinishLoadingMap(uiView, didFinishLoading: MGLStyle())
        }
    }

    func mapViewDidFinishLoadingMap(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) {
        mapView.isRotateEnabled = false

        // MARK: - Get the result from the encoded polyline string
        let result = Polyline.init(encodedPolyline: selectedEncodedPolyline, encodedLevels: .none)

        // MARK: - Get the coordinates in the polyline for the trip
        let coordinates = result.coordinates

        guard let tripPoints = coordinates else {return}

        // MARK: - Get the start and end point
        let startPoint: CLLocationCoordinate2D = coordinates?.first ?? CLLocationCoordinate2D(latitude: 0, longitude: 0)
        let endPoint: CLLocationCoordinate2D = coordinates?.last ?? CLLocationCoordinate2D(latitude: 0, longitude: 0)

        var startTripPoint = MGLPointAnnotation()
        var endTripPoint = MGLPointAnnotation()

        startTripPoint.title = "Starting Point"
        startTripPoint.coordinate = startPoint
        endTripPoint.title = "End Point"
        endTripPoint.coordinate = endPoint
        mapView.addAnnotation(startTripPoint)
        mapView.addAnnotation(endTripPoint)

        let tryLine = MGLPolyline(coordinates: coordinates!, count: UInt(coordinates!.count))
        mapView.addAnnotation(tryLine)

        var speedingArray = [[TripPoint]]()

        DispatchQueue.global(qos: .background).async {
            // MARK: - Deal with the speeding events in the trip
            // MARK: - The speeding icon will be placed at the point which has the maximum speed for each speeding polyline
            var ctr = 0

            while ctr < selectedTrip.speedingPoints!.count{
                var speedPath = [TripPoint]()
                speedPath.append(selectedTrip.speedingPoints![ctr])
                while ctr + 1 < selectedTrip.speedingPoints!.count && selectedTrip.speedingPoints![ctr + 1].timeStamp!.timeIntervalSince1970 - selectedTrip.speedingPoints![ctr].timeStamp!.timeIntervalSince1970 < 10{
                    speedPath.append(selectedTrip.speedingPoints![ctr+1])
                    ctr += 1
                }
                speedingArray.append(speedPath)
                ctr += 1
            }

            for speedingLine in speedingArray {
                var maxDelta = 0.0
                var maxDeltaPoint:TripPoint? = nil
                var path: [CLLocationCoordinate2D] = []
                for speedingPoint in speedingLine{
                    path.append(CLLocationCoordinate2D(latitude: speedingPoint.latitude!, longitude: speedingPoint.longitude!))
                    if speedingPoint.speed_limit_delta! > maxDelta{
                        maxDelta = speedingPoint.speed_limit_delta!
                        maxDeltaPoint = speedingPoint

                    }
                }

                if let markerPoint = maxDeltaPoint{
                    tripPointsArray.append(markerPoint)
                    var speedMarker = MGLPointAnnotation()
                    speedMarker.coordinate = CLLocationCoordinate2D(latitude: markerPoint.latitude!, longitude: markerPoint.longitude!)
                    speedMarker.title = "Speeding: \(Int(markerPoint.speed!)) " + markerPoint.speedUnit!
                    let speedLimitBR = Double(markerPoint.speed!) - markerPoint.speed_limit_delta! //before rounding
                    var speedLimit = 10 * Int((speedLimitBR / 10.0).rounded())//round to nearest 10
                    speedMarker.subtitle = "Speed Limit: ~ \(speedLimit) " + markerPoint.speedUnit!

                    DispatchQueue.main.async {
                        mapView.addAnnotation(speedMarker)
                    }
                }

                let speedingPolyline = MGLPolyline(coordinates: path, count: UInt(path.count))
                speedingPolyline.title = "Speeding"
                DispatchQueue.main.async {
                    mapView.addAnnotation(speedingPolyline)
                }

            }
            speedingCount = speedingArray.count

            // MARK: - Deal with hard brakes in the trip
            for hardBrakePoint in selectedTrip.hardBrakePoints!{
                tripPointsArray.append(hardBrakePoint)
                let hardBrakeMarker = MGLPointAnnotation()
                hardBrakeMarker.coordinate = CLLocationCoordinate2D(latitude: hardBrakePoint.latitude!, longitude: hardBrakePoint.longitude!)
                hardBrakeMarker.title = "Hard Brake"
                hardBrakeMarker.subtitle = "Acceleration: \(String(format: "%.1f", hardBrakePoint.acceleration! * 3.6)) " + "km/h/s"
                DispatchQueue.main.async {
                    mapView.addAnnotation(hardBrakeMarker)
                }
            }

            // MARK: - Deal with rapid accel in the trip
            for rapidAccelPoint in selectedTrip.rapidAccelPoints!{
                tripPointsArray.append(rapidAccelPoint)
                let rapidAccelMarker = MGLPointAnnotation()
                rapidAccelMarker.coordinate = CLLocationCoordinate2D(latitude: rapidAccelPoint.latitude!, longitude: rapidAccelPoint.longitude!)
                rapidAccelMarker.title = "Rapid Accel"
                rapidAccelMarker.subtitle = "Acceleration: \(String(format: "%.1f", rapidAccelPoint.acceleration! * 3.6)) " + "km/h/s"
                DispatchQueue.main.async {
                    mapView.addAnnotation(rapidAccelMarker)
                }
            }
        }

        // MARK: - If we are not in EventDetailView, then the mapView.showAnnotations will help us to zoom the map to the proper level so that all the markers and annotations in the map will be shown
        if !showSpecificPoint {
            Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { timer in
                guard let annotations = mapView.annotations else {return}
                mapView.showAnnotations(annotations, edgePadding: .init(top: 60, left: 40, bottom: 10, right: 40), animated: true, completionHandler: nil)
            }

        } else {
            // MARK: - If we need to zoom into a specific point, we need to find which point it is among all the trip points and zoom into that specific point
            var alreadyAdded = false
            var point = MGLPointAnnotation()

            point.coordinate = CLLocationCoordinate2D(latitude: selectedTripPoint.latitude ?? 0, longitude: selectedTripPoint.longitude ?? 0)

            for hardBrakePoint in selectedTrip.hardBrakePoints! {
                if hardBrakePoint.latitude == selectedTripPoint.latitude && hardBrakePoint.longitude == selectedTripPoint.longitude {
                    point.title = "Hard Brake"
                    point.subtitle = "Acceleration: \(String(format: "%.1f", hardBrakePoint.acceleration! * 3.6)) " + "km/h/s"
                    mapView.addAnnotation(point)
                    alreadyAdded = true
                    break
                }
            }

            if !alreadyAdded {
                for rapidAccelPoint in selectedTrip.rapidAccelPoints!{

                    if rapidAccelPoint.latitude == selectedTripPoint.latitude && rapidAccelPoint.longitude == selectedTripPoint.longitude {
                        point.title = "Rapid Accel"
                        point.title! += "Acceleration: \(String(format: "%.1f", rapidAccelPoint.acceleration! * 3.6)) " + "km/h/s"
                        mapView.addAnnotation(point)
                        alreadyAdded = true
                        break
                    }
                }
            }

            if !alreadyAdded {
                var presentPolyLine: MGLPolyline = MGLPolyline()
                for speedingLine in speedingArray{
                    var maxDelta = 0.0
                    var maxDeltaPoint:TripPoint? = nil
                    var path: [CLLocationCoordinate2D] = []
                    for speedingPoint in speedingLine{
                        path.append(CLLocationCoordinate2D(latitude: speedingPoint.latitude!, longitude: speedingPoint.longitude!))
                        if speedingPoint.speed_limit_delta! > maxDelta{
                            maxDelta = speedingPoint.speed_limit_delta!
                            maxDeltaPoint = speedingPoint
                        }
                    }

                    if let markerPoint = maxDeltaPoint{
                        if selectedTripPoint.latitude == markerPoint.latitude && selectedTripPoint.longitude == markerPoint.longitude {
                            let specificMarker = MGLPointAnnotation()
                            specificMarker.coordinate = CLLocationCoordinate2D(latitude: markerPoint.latitude ?? 0, longitude: markerPoint.longitude ?? 0)
                            var speedMarker = MGLPointAnnotation()
                            speedMarker.coordinate = CLLocationCoordinate2D(latitude: markerPoint.latitude!, longitude: markerPoint.longitude!)
                            speedMarker.title = "Speeding: \(Int(markerPoint.speed!)) " + markerPoint.speedUnit!
                            let speedLimitBR = Double(markerPoint.speed!) - markerPoint.speed_limit_delta! //before rounding
                            var speedLimit = 10 * Int((speedLimitBR / 10.0).rounded())//round to nearest 10
                            speedMarker.subtitle = "Speed Limit: ~ \(speedLimit) " + markerPoint.speedUnit!
                            point = speedMarker
                            DispatchQueue.main.async {
                                let speedingPolyline = MGLPolyline(coordinates: path, count: UInt(path.count))
                                speedingPolyline.title = "Speeding"
                                presentPolyLine = speedingPolyline
                            }
                            break
                        } else {
                            path.removeAll()
                        }
                    }
                }

                mapView.showAnnotations([point], edgePadding: .init(top: 60, left: 40, bottom: 10, right: 40), animated: true, completionHandler: nil)
            } else {
                mapView.showAnnotations([point], edgePadding: .init(top: -10, left: -10, bottom: -10, right: -10), animated: true, completionHandler: nil)
            }
        }
    }
}

I tried updating the pods from 6.3 to 6.4.1 but it didn't work.

I know MapBox has a new framework as of v6.4.1 called v10, but I haven't installed yet cause that would change the whole code.
I am expecting to see the map as it was displaying before this new bug. eg. see screenshot


问:
Tensorflow LSTM input shape not functioning properly
I am trying to build a LSTM model and I cannot get the input_shape parameter to work properly.
My data is set up so every row is a timestep and each column is an input_dim.
It is always the wrong shape, either missing the timestep, or adding an extra value in to the parameter:

ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 5592, 9), found shape=(None, 9)

Or

ValueError: Input 0 of layer "lstm" is incompatible with the layer: expected ndim=3, found ndim=4. Full shape received: (None, 14, 5592, 9)

Here is the relevant snippet of code:

```<code>tdf = pd.read_csv(train_csv)
tdf2 = pd.read_csv(train_csv2)
df = pd.read_csv(test_csv)

# Split the data into training and testing sets
train_x = []
train_y = []
for i in range(len(tdf_list)):
    train_x.append(tdf_list[i])
    train_y.append(tdf_list[i]["Close"].shift(-1).dropna())

    train_x[i] = tdf_list[i].drop(index=tdf_list[i].index[-1]).drop(columns=["Close"])

test_x = df
test_y = df["Close"].shift(-1).dropna()

test_x = df.drop(index=df.index[-1]).drop(columns=["Close"])
test_x = test_x.values.reshape(-1, test_x.shape[1], 1)

print(train_x[0].shape)

def run_model(g):
    # Define the LSTM model
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.LSTM(neurons, return_sequences=True, input_shape=(train_x[g].shape[0],train_x[g].shape[1])))
    model.add(tf.keras.layers.BatchNormalization())
    model.add(tf.keras.layers.Dropout(rate=0.2))
    model.add(tf.keras.layers.LSTM(neurons, return_sequences=False))
    model.add(tf.keras.layers.Dense(32))
    model.add(tf.keras.layers.Activation('tanh'))
    model.add(tf.keras.layers.Dense(32))
    model.add(tf.keras.layers.Dense(1))
</code>```

I have tried manually entering input shape integers, and even when hardcoded I cannot get it to work properly. I have also tried every permutation of reshaping train_x[0] to get it to fit properly. The only way I can get the code to execute is if I set

```<code>input_shape=(train_x[g].shape[1], 1)
</code>```

But then it is using the data columns as timesteps...

Body:
I am trying to build a LSTM model and I cannot get the input_shape parameter to work properly.
My data is set up so every row is a timestep and each column is an input_dim.
It is always the wrong shape, either missing the timestep, or adding an extra value in to the parameter:

ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 5592, 9), found shape=(None, 9)

Or

ValueError: Input 0 of layer "lstm" is incompatible with the layer: expected ndim=3, found ndim=4. Full shape received: (None, 14, 5592, 9)

Here is the relevant snippet of code:

tdf = pd.read_csv(train_csv)
tdf2 = pd.read_csv(train_csv2)
df = pd.read_csv(test_csv)

# Split the data into training and testing sets
train_x = []
train_y = []
for i in range(len(tdf_list)):
    train_x.append(tdf_list[i])
    train_y.append(tdf_list[i]["Close"].shift(-1).dropna())

    train_x[i] = tdf_list[i].drop(index=tdf_list[i].index[-1]).drop(columns=["Close"])

test_x = df
test_y = df["Close"].shift(-1).dropna()

test_x = df.drop(index=df.index[-1]).drop(columns=["Close"])
test_x = test_x.values.reshape(-1, test_x.shape[1], 1)

print(train_x[0].shape)

def run_model(g):
    # Define the LSTM model
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.LSTM(neurons, return_sequences=True, input_shape=(train_x[g].shape[0],train_x[g].shape[1])))
    model.add(tf.keras.layers.BatchNormalization())
    model.add(tf.keras.layers.Dropout(rate=0.2))
    model.add(tf.keras.layers.LSTM(neurons, return_sequences=False))
    model.add(tf.keras.layers.Dense(32))
    model.add(tf.keras.layers.Activation('tanh'))
    model.add(tf.keras.layers.Dense(32))
    model.add(tf.keras.layers.Dense(1))

I have tried manually entering input shape integers, and even when hardcoded I cannot get it to work properly. I have also tried every permutation of reshaping train_x[0] to get it to fit properly. The only way I can get the code to execute is if I set

input_shape=(train_x[g].shape[1], 1)

But then it is using the data columns as timesteps...


问:
Why does the sequence of the output of an dictionary change with the number of entries in the dictionary?
I have to use "Python 2.7.3" for this script and an upgrade to an newer version is not possible.

If I put in an dictionary 4 enties (key:value) and print it everything works as aspected.
The sequence of the entries will be printed from the first until the last enty:

`parameters = {"ifname": None, "speed": "auto", "bcast_unit": "kps", "max_bcast": "300"}
print(parameters)

C:\Python27\python.exe C:/myscripts/Python/Projects/comware/get_arguments.py
{'ifname': None, 'speed': 'auto', 'bcast_unit': 'kps', 'max_bcast': '300'}`

==

If I put more than 4 entries (key:value) into this dictionary, things are getting strange;
The sequence change now and the last key:value will be printed first.

`parameters = {"ifname": None, "speed": "auto", "bcast_unit": "kps", "max_bcast": "300"}
print(parameters)

C:\Python27\python.exe C:/myscripts/Python/Projects/comware/get_arguments.py
{'ifname': None, 'speed': 'auto', 'bcast_unit': 'kps', 'max_bcast': '300'}`

What I'm doing wrong here? Or is it a limitation of this old Python version?

I used an dictionary with 4 enties and print this dict. The output had the aspected sequence of the entries.
With more than 4 entries (Python 2.7.3) prints the elements in different sequence.

Under Python 3.9.2 the dictionary with more than 4 entries will be printed in the correct and aspected sequence.


问:
Configure Many-To-Many EF Relationship Between Separate Aggregates Without Using Navigation Lists
I have two entities from separate aggregate groups that have a many-to-many relationship:

```<code>public class ClientNotificationMethod
    {
        public int ID { get; private set; }
        private ICollection<int> _personIDs;
        //public virtual ICollection<Person> _contactPersonnel { get; set; } //AVOID THIS
    }
</code>```

The ClientNotificationMethod has a collection of Person IDs, and the Person has a collection of ClientNotificationMethod IDs:

```<code>public class Person
    {
        public int ID { get; private set; }
        private ICollection<int> _clientNotificationMethodIDs;
        //public virtual ICollection<ClientNotificationMethod> _clientNotificationMethods { get; set; } //AVOID THIS
    }

</code>```

From both classes, I commented-out the public virtual ICollection navigation properties, because I'm trying to follow the DDD principle of avoiding overlap between aggregate groups. I also want to prevent eager/lazy-loading lists of entire class objects (I only want the IDs).

When a Person is added/removed from a ClientNotificationMethod, I want EF to update the ICollection<int> properties in each class.

I haven't found any examples of this in my searches. So far, it seems that EF requires navigation properties in both classes to configure a many-to-many relationship. From my understanding of DDD, navigation properties should only be used in this way when the many-to-many relationship is between two objects in the same aggregate group.

Is the many-to-many relationship that I'm aiming for configurable in EF using fluent API?

At one point, I tried configuring a HasMany-WithMany relationship like this:

```<code>private void ConfigureClientNotificationMethod(EntityTypeBuilder<ClientNotificationMethod> builder)
{

            builder.ToTable("ClientNotificationMethod");

            builder.HasKey("ID");

            builder.Property("ID")
                .IsRequired();

            builder.HasMany<Person>().WithMany().UsingEntity<Dictionary<string, object>>("ClientNotificationMethodPersons",
                c => c.HasOne<Person>().WithMany(),
                c => c.HasOne<ClientNotificationMethod>().WithMany());

            builder.Property("_personIDs").HasConversion(new JsonValueConverter<ICollection<int>>())
                .HasColumnName("PersonIDs").IsRequired(false);
}
</code>```

This created a join table, but EF couldn't populate it because I wasn't using any Person or ClientNotificationMethod navigation objects in the classes.

Body:
I have two entities from separate aggregate groups that have a many-to-many relationship:

public class ClientNotificationMethod
    {
        public int ID { get; private set; }
        private ICollection<int> _personIDs;
        //public virtual ICollection<Person> _contactPersonnel { get; set; } //AVOID THIS
    }

The ClientNotificationMethod has a collection of Person IDs, and the Person has a collection of ClientNotificationMethod IDs:

public class Person
    {
        public int ID { get; private set; }
        private ICollection<int> _clientNotificationMethodIDs;
        //public virtual ICollection<ClientNotificationMethod> _clientNotificationMethods { get; set; } //AVOID THIS
    }

From both classes, I commented-out the public virtual ICollection navigation properties, because I'm trying to follow the DDD principle of avoiding overlap between aggregate groups. I also want to prevent eager/lazy-loading lists of entire class objects (I only want the IDs).

When a Person is added/removed from a ClientNotificationMethod, I want EF to update the ICollection<int> properties in each class.

I haven't found any examples of this in my searches. So far, it seems that EF requires navigation properties in both classes to configure a many-to-many relationship. From my understanding of DDD, navigation properties should only be used in this way when the many-to-many relationship is between two objects in the same aggregate group.

Is the many-to-many relationship that I'm aiming for configurable in EF using fluent API?

At one point, I tried configuring a HasMany-WithMany relationship like this:

private void ConfigureClientNotificationMethod(EntityTypeBuilder<ClientNotificationMethod> builder)
{

            builder.ToTable("ClientNotificationMethod");

            builder.HasKey("ID");

            builder.Property("ID")
                .IsRequired();

            builder.HasMany<Person>().WithMany().UsingEntity<Dictionary<string, object>>("ClientNotificationMethodPersons",
                c => c.HasOne<Person>().WithMany(),
                c => c.HasOne<ClientNotificationMethod>().WithMany());

            builder.Property("_personIDs").HasConversion(new JsonValueConverter<ICollection<int>>())
                .HasColumnName("PersonIDs").IsRequired(false);
}

This created a join table, but EF couldn't populate it because I wasn't using any Person or ClientNotificationMethod navigation objects in the classes.


问:
Calling java native method from Kotlin
I am trying to create an instance of a rocksDB cache from Kotlin.

```<code>val cache = org.rocksdb.LRUCache(500L * 1024L * 1024L)
</code>```

But I am getting an exception

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: 'long org.rocksdb.LRUCache.newLRUCache(long, int, boolean, double)'
    at org.rocksdb.LRUCache.newLRUCache(Native Method)
    at org.rocksdb.LRUCache.<init>(LRUCache.java:74)
    at org.rocksdb.LRUCache.<init>(LRUCache.java:19)
    at application.CustomRocksDbConfigSetter.<clinit>(RocksDb.kt:41)
    at application.RocksDbKt.configureRocksDb(RocksDb.kt:15)
    at application.StreamsStarter.configureProperties(StreamsStarter.kt:30)
    at application.StreamsStarter.execute(StreamsStarter.kt:19)
    at main.ModulesKt.mainModule(Modules.kt:18)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at kotlin.reflect.jvm.internal.calls.CallerImpl$Method.callMethod(CallerImpl.kt:97)
    at kotlin.reflect.jvm.internal.calls.CallerImpl$Method$Static.call(CallerImpl.kt:106)
    at kotlin.reflect.jvm.internal.KCallableImpl.call(KCallableImpl.kt:108)
    at kotlin.reflect.jvm.internal.KCallableImpl.callDefaultMethod$kotlin_reflection(KCallableImpl.kt:159)
    at kotlin.reflect.jvm.internal.KCallableImpl.callBy(KCallableImpl.kt:112)
    at io.ktor.server.engine.internal.CallableUtilsKt.callFunctionWithInjection(CallableUtils.kt:119)
    at io.ktor.server.engine.internal.CallableUtilsKt.executeModuleFunction(CallableUtils.kt:36)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$launchModuleByName$1.invoke(ApplicationEngineEnvironmentReloading.kt:331)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$launchModuleByName$1.invoke(ApplicationEngineEnvironmentReloading.kt:330)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.avoidingDoubleStartupFor(ApplicationEngineEnvironmentReloading.kt:355)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.launchModuleByName(ApplicationEngineEnvironmentReloading.kt:330)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.access$launchModuleByName(ApplicationEngineEnvironmentReloading.kt:32)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1.invoke(ApplicationEngineEnvironmentReloading.kt:311)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1.invoke(ApplicationEngineEnvironmentReloading.kt:309)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.avoidingDoubleStartup(ApplicationEngineEnvironmentReloading.kt:337)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.instantiateAndConfigureApplication(ApplicationEngineEnvironmentReloading.kt:309)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createApplication(ApplicationEngineEnvironmentReloading.kt:150)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.start(ApplicationEngineEnvironmentReloading.kt:276)
    at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:212)
    at io.ktor.server.netty.EngineMain.main(EngineMain.kt:32)
</code>```

I see the cache internal code and it invokes this function:

```<code>private native static long newLRUCache(final long capacity,
      final int numShardBits, final boolean strictCapacityLimit,
      final double highPriPoolRatio);
</code>```

Is this not supposed to work when invoked from Kotlin?

Title: Calling java native method from Kotlin

Body:
I am trying to create an instance of a rocksDB cache from Kotlin.

val cache = org.rocksdb.LRUCache(500L * 1024L * 1024L)

But I am getting an exception

Exception in thread "main" java.lang.UnsatisfiedLinkError: 'long org.rocksdb.LRUCache.newLRUCache(long, int, boolean, double)'
    at org.rocksdb.LRUCache.newLRUCache(Native Method)
    at org.rocksdb.LRUCache.<init>(LRUCache.java:74)
    at org.rocksdb.LRUCache.<init>(LRUCache.java:19)
    at application.CustomRocksDbConfigSetter.<clinit>(RocksDb.kt:41)
    at application.RocksDbKt.configureRocksDb(RocksDb.kt:15)
    at application.StreamsStarter.configureProperties(StreamsStarter.kt:30)
    at application.StreamsStarter.execute(StreamsStarter.kt:19)
    at main.ModulesKt.mainModule(Modules.kt:18)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at kotlin.reflect.jvm.internal.calls.CallerImpl$Method.callMethod(CallerImpl.kt:97)
    at kotlin.reflect.jvm.internal.calls.CallerImpl$Method$Static.call(CallerImpl.kt:106)
    at kotlin.reflect.jvm.internal.KCallableImpl.call(KCallableImpl.kt:108)
    at kotlin.reflect.jvm.internal.KCallableImpl.callDefaultMethod$kotlin_reflection(KCallableImpl.kt:159)
    at kotlin.reflect.jvm.internal.KCallableImpl.callBy(KCallableImpl.kt:112)
    at io.ktor.server.engine.internal.CallableUtilsKt.callFunctionWithInjection(CallableUtils.kt:119)
    at io.ktor.server.engine.internal.CallableUtilsKt.executeModuleFunction(CallableUtils.kt:36)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$launchModuleByName$1.invoke(ApplicationEngineEnvironmentReloading.kt:331)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$launchModuleByName$1.invoke(ApplicationEngineEnvironmentReloading.kt:330)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.avoidingDoubleStartupFor(ApplicationEngineEnvironmentReloading.kt:355)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.launchModuleByName(ApplicationEngineEnvironmentReloading.kt:330)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.access$launchModuleByName(ApplicationEngineEnvironmentReloading.kt:32)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1.invoke(ApplicationEngineEnvironmentReloading.kt:311)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading$instantiateAndConfigureApplication$1.invoke(ApplicationEngineEnvironmentReloading.kt:309)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.avoidingDoubleStartup(ApplicationEngineEnvironmentReloading.kt:337)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.instantiateAndConfigureApplication(ApplicationEngineEnvironmentReloading.kt:309)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.createApplication(ApplicationEngineEnvironmentReloading.kt:150)
    at io.ktor.server.engine.ApplicationEngineEnvironmentReloading.start(ApplicationEngineEnvironmentReloading.kt:276)
    at io.ktor.server.netty.NettyApplicationEngine.start(NettyApplicationEngine.kt:212)
    at io.ktor.server.netty.EngineMain.main(EngineMain.kt:32)

I see the cache internal code and it invokes this function:

private native static long newLRUCache(final long capacity,
      final int numShardBits, final boolean strictCapacityLimit,
      final double highPriPoolRatio);

Is this not supposed to work when invoked from Kotlin?


问:
How do I loop through array elements infinitely, whilst making the current array element visible?
I wish to create a text animation where words are being displayed, one after another and with moderate speed. First I tried achieving this with an onClick event.

```<code>const arrayOfWords = ["Acerbity", "Anomalous", "Asymetrical", "Analytical", "Arbritrary"];
const targetOfDisplay = document.querySelector("h1#heading");
const clickElement = document.querySelector("button");
targetOfDisplay.innerHTML = arrayOfWords[0];
let i = 0;

function changeWord(){
    if(i < arrayOfWords.length-1) {
      i++;
    }
    else{
      i=0;
    }
  return targetOfDisplay.innerText = arrayOfWords[i];
}
clickElement.onclick = changeWord;
</code>```

Then I thought about making animation out of it.

I tried working with a timer, but I just can't figure it out.

```<code>const arrayOfWords = ["Acerbity", "Anomalous", "Asymetrical", "Analytical", "Arbritrary"];
const targetDisplay = document.querySelector("h1#heading");
let i = 0;
targetDisplay.innerHTML = arrayOfWords[0];

function animateWords(){
    if(i < arrayOfWords.length-1) {
      i++;
    }
    else{
      i=0;
    }
  return targetDisplay.innerText = arrayOfWords[i];
}

const currentWord = 0;
const timer = setInterval(onTick,50);

function onTick(){
  const change = targetOfDisplay.innerText[currentWord];
  currentWord++
  if(current === arrayOfWords.length){
    complete();
    return;
  }
}
function complete(){
  clearInterval(timer);
  timer = null;

</code>```

Body:
I wish to create a text animation where words are being displayed, one after another and with moderate speed. First I tried achieving this with an onClick event.

const arrayOfWords = ["Acerbity", "Anomalous", "Asymetrical", "Analytical", "Arbritrary"];
const targetOfDisplay = document.querySelector("h1#heading");
const clickElement = document.querySelector("button");
targetOfDisplay.innerHTML = arrayOfWords[0];
let i = 0;

function changeWord(){
    if(i < arrayOfWords.length-1) {
      i++;
    }
    else{
      i=0;
    }
  return targetOfDisplay.innerText = arrayOfWords[i];
}
clickElement.onclick = changeWord;

Then I thought about making animation out of it.

I tried working with a timer, but I just can't figure it out.

const arrayOfWords = ["Acerbity", "Anomalous", "Asymetrical", "Analytical", "Arbritrary"];
const targetDisplay = document.querySelector("h1#heading");
let i = 0;
targetDisplay.innerHTML = arrayOfWords[0];

function animateWords(){
    if(i < arrayOfWords.length-1) {
      i++;
    }
    else{
      i=0;
    }
  return targetDisplay.innerText = arrayOfWords[i];
}

const currentWord = 0;
const timer = setInterval(onTick,50);

function onTick(){
  const change = targetOfDisplay.innerText[currentWord];
  currentWord++
  if(current === arrayOfWords.length){
    complete();
    return;
  }
}
function complete(){
  clearInterval(timer);
  timer = null;


问:
How to keep matched groups of pattern recursion in regex?
I have this problem where i'm trying to validate an input using regex. the input should correspond to a specific programmation-like norm, that consist on function, variables (2 types) and strings.

Here's some examples :

```<code>&foo
$foo(&bar)
$foo(&bar+$baz)
$foo($bar "baz" qux+$quux(&corge "grault") &garply)
</code>```

Types that exists:

$bar - variable

&foo - variable (second type)

"baz" - string

qux - litteral string

$quux(...) - function

The main problem here is that I've written a regex, with recusion of course. But, I need to validate the fact that, in the final match itself or within its recursions, there is at least one variable of the second type - which isn't actually the case. Obviously, my regex should fullmatch the input.

So here's my regex (it uses PCRE2), followed by its explanation, and a suit of tests for you to try it:

Regex

```<code>(?:\$\w+(?:\((?<arg>(?R)|(?:\"[^\"]*\")|(?:[^\$\"\&\s\(\)][^\s\(\)]*))(?:(?:\+| )(?&arg))*\))?)|(?<var>\&\w+)
</code>```

Explanations

```<code>(?:                           # function or variable and its arguments
  \$\w+                         # function or variable prefix + name (ex: $test)
  (?:                           # arguments if it's a function
    \(                            # opening parenthesis
    (?<arg>                       # first argument
      (?R)                          # function or variable
      |
      (?:\"[^\"]*\")                # string
      |
      (?:[^\$\"\&\s\(\)][^\s\(\)]*) # string literal
    )
    (?:                           # other arguments if any
      (?:\+| )                      # separator
      (?&arg)                       # argument
    )*
    \)                            # closing parenthesis
  )?
)
|
(?<var>\&\w+)                 # variable prefix + name (ex: &test)
</code>```

Human-readable translation

```<code>(                         # function or variable and its arguments
  \$\w+                     # function or variable prefix + name (ex: $test)
  MAYBE (                   # arguments if it's a function
    \(                        # opening parenthesis
    GROUP <arg> (             # first argument
      RECURSIVE                 # function or variable
      OR
      \"[^\"]*\"                # string
      OR
      [^\$\"\&\s\(\)][^\s\(\)]* # string literal
    )
    MAYBE MULTIPLE (          # other arguments if any
      \+ OR SPACE               # separator
      GROUP arg                 # argument
    )
    \)                        # closing parenthesis
  )
)
OR
GROUP <var> (\&\w+)       # variable prefix + name (ex: &test)
</code>```

The goal is to transform it the verify that the group var is present at least once, within the regex or its recursions.

The best solution would be that (?R) kept the group matched within recursion and pass them to his parent pattern, I would be able to check if the group var matched at least once with (?(var)(*ACCEPT)|(*FAIL)).

Here's a simplified version of what I'm thinking about: (?:\w(?R)|(\d))(?(1)(*ACCEPT)|(*FAIL)). This regex only matches 1 digit, but with "recursion matches-keeping", it whould match any chain of letters followed by a digit.

However, it seems that it's not possible at all. I didn't found a flag nor a token for this.

Test/Examples

```<code>$test($test(test &var1 $var2) $test(jean) jean) # should full-match
$test($test(test $var1 $var2) $test(foo) bar)   # should not full-match
$test("&test")                                  # should not full-match
$test("foo&test")                               # should not full-match
$test("&test" &test)                            # should full-match
&test                                           # should full-match
$test(" &test")                                 # should not full-match
$test                                           # should not full-match
&test(foo)                                      # should not full-match
&test(&foo $bar())                              # should not full-match
$test((&test))                                  # should not full-match
$foo(bar(&baz))                                 # should not full match
$test(&test  &test)                             # should not full match
$test( &test)                                   # should not full match
$test(&test )                                   # should not full match
</code>```

Here's a link to my regex101 tests for you to try and test it.

Body:
I have this problem where i'm trying to validate an input using regex. the input should correspond to a specific programmation-like norm, that consist on function, variables (2 types) and strings.

Here's some examples :

&foo
$foo(&bar)
$foo(&bar+$baz)
$foo($bar "baz" qux+$quux(&corge "grault") &garply)

Types that exists:

$bar - variable

&foo - variable (second type)

"baz" - string

qux - litteral string

$quux(...) - function

The main problem here is that I've written a regex, with recusion of course. But, I need to validate the fact that, in the final match itself or within its recursions, there is at least one variable of the second type - which isn't actually the case. Obviously, my regex should fullmatch the input.

So here's my regex (it uses PCRE2), followed by its explanation, and a suit of tests for you to try it:

Regex

(?:\$\w+(?:\((?<arg>(?R)|(?:\"[^\"]*\")|(?:[^\$\"\&\s\(\)][^\s\(\)]*))(?:(?:\+| )(?&arg))*\))?)|(?<var>\&\w+)

Explanations

(?:                           # function or variable and its arguments
  \$\w+                         # function or variable prefix + name (ex: $test)
  (?:                           # arguments if it's a function
    \(                            # opening parenthesis
    (?<arg>                       # first argument
      (?R)                          # function or variable
      |
      (?:\"[^\"]*\")                # string
      |
      (?:[^\$\"\&\s\(\)][^\s\(\)]*) # string literal
    )
    (?:                           # other arguments if any
      (?:\+| )                      # separator
      (?&arg)                       # argument
    )*
    \)                            # closing parenthesis
  )?
)
|
(?<var>\&\w+)                 # variable prefix + name (ex: &test)

Human-readable translation

(                         # function or variable and its arguments
  \$\w+                     # function or variable prefix + name (ex: $test)
  MAYBE (                   # arguments if it's a function
    \(                        # opening parenthesis
    GROUP <arg> (             # first argument
      RECURSIVE                 # function or variable
      OR
      \"[^\"]*\"                # string
      OR
      [^\$\"\&\s\(\)][^\s\(\)]* # string literal
    )
    MAYBE MULTIPLE (          # other arguments if any
      \+ OR SPACE               # separator
      GROUP arg                 # argument
    )
    \)                        # closing parenthesis
  )
)
OR
GROUP <var> (\&\w+)       # variable prefix + name (ex: &test)

The goal is to transform it the verify that the group var is present at least once, within the regex or its recursions.

The best solution would be that (?R) kept the group matched within recursion and pass them to his parent pattern, I would be able to check if the group var matched at least once with (?(var)(*ACCEPT)|(*FAIL)).

Here's a simplified version of what I'm thinking about: (?:\w(?R)|(\d))(?(1)(*ACCEPT)|(*FAIL)). This regex only matches 1 digit, but with "recursion matches-keeping", it whould match any chain of letters followed by a digit.

However, it seems that it's not possible at all. I didn't found a flag nor a token for this.

Test/Examples

$test($test(test &var1 $var2) $test(jean) jean) # should full-match
$test($test(test $var1 $var2) $test(foo) bar)   # should not full-match
$test("&test")                                  # should not full-match
$test("foo&test")                               # should not full-match
$test("&test" &test)                            # should full-match
&test                                           # should full-match
$test(" &test")                                 # should not full-match
$test                                           # should not full-match
&test(foo)                                      # should not full-match
&test(&foo $bar())                              # should not full-match
$test((&test))                                  # should not full-match
$foo(bar(&baz))                                 # should not full match
$test(&test  &test)                             # should not full match
$test( &test)                                   # should not full match
$test(&test )                                   # should not full match

Here's a link to my regex101 tests for you to try and test it.


问:
Social Media using Files in Python returning Errno2
So I am working on a mockup social media using file management, and I keep running into this error when attempting to get a user's feed:

```<code>def getFeed(users=[]):
  global returnVal
  returnVal = []
  for i in range(10):
    with open("database/users/"+str(users[i])+"/posts/"+str(i+1)+".lzs", "r") as f:
      if f.read() == "":
        pass
      else:
        returnVal.append(f.read())
</code>```

this is where the function is being used:

```<code>while session != None:
  os.system('clear')
  print("LolzSocial\n--------------------")
  print("> 1. View Feed")
  print("> 2. Search User")
  print("> 3. Create Post")
  print("> 4. Logout\n--------------------")
  option = input("What would you like to do?\n> ")
  os.system('clear')
  if option == "1":
    following = "" #none yet
    with open(f"{db_url}/users/{logged}/following.lzs", "r") as f:
      following = f.read()
      if following != "":
        following = following.split(";")
        getFeed(following)
  elif option == "3":
    createPost(input("Write something awesome!\n>"))
</code>```

and this is the exact error:

```<code>Traceback (most recent call last):
  File "main.py", line 121, in <module>
    getFeed(following)
  File "main.py", line 60, in getFeed
    with open("database/users/"+str(users[i])+"/posts/"+str(i+1)+".lzs", "r") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'database/users//posts/2.lzs'
</code>```

Attempted to get user feed, ran into error, and keeps attempting to find a user that does not exist.

Body:
So I am working on a mockup social media using file management, and I keep running into this error when attempting to get a user's feed:

def getFeed(users=[]):
  global returnVal
  returnVal = []
  for i in range(10):
    with open("database/users/"+str(users[i])+"/posts/"+str(i+1)+".lzs", "r") as f:
      if f.read() == "":
        pass
      else:
        returnVal.append(f.read())

this is where the function is being used:

while session != None:
  os.system('clear')
  print("LolzSocial\n--------------------")
  print("> 1. View Feed")
  print("> 2. Search User")
  print("> 3. Create Post")
  print("> 4. Logout\n--------------------")
  option = input("What would you like to do?\n> ")
  os.system('clear')
  if option == "1":
    following = "" #none yet
    with open(f"{db_url}/users/{logged}/following.lzs", "r") as f:
      following = f.read()
      if following != "":
        following = following.split(";")
        getFeed(following)
  elif option == "3":
    createPost(input("Write something awesome!\n>"))

and this is the exact error:

Traceback (most recent call last):
  File "main.py", line 121, in <module>
    getFeed(following)
  File "main.py", line 60, in getFeed
    with open("database/users/"+str(users[i])+"/posts/"+str(i+1)+".lzs", "r") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'database/users//posts/2.lzs'

Attempted to get user feed, ran into error, and keeps attempting to find a user that does not exist.