问:
How to completely remove yum installed packages
When I use yum remove <package_name> -y, it removes the package, but I was able to find the package anyway with the which <package_name> command, and cannot be found when remove again

# yum list  | grep pssh
mpssh.x86_64                            1.3.3-2.el7                  epel
pssh.noarch                             2.3.1-5.el7                  epel
pssh.x86_64                             3.4.1-1                      xxx-base
# yum remove pssh -y
Loaded plugins: fastestmirror, langpacks
No Match for argument: pssh
No Packages marked for removal
# which pssh
/usr/bin/pssh
```
<p>What can I do to completely remove the packages installed by <code>yum install</code>?</p>
<p>And I was able to <code>install pssh again</code>, I intercepted the <code>list</code> results before and after the installation and removal</p>
<pre class="lang-bash prettyprint-override"><code># after yum install pssh -y
# yum list | grep pssh
pssh.x86_64                             3.4.1-1                      @xxx-base
mpssh.x86_64                            1.3.3-2.el7                  epel
pssh.noarch                             2.3.1-5.el7                  epel

# after yum remove pssh -y
# yum list | grep pssh
mpssh.x86_64                            1.3.3-2.el7                  epel
pssh.noarch                             2.3.1-5.el7                  epel
pssh.x86_64                             3.4.1-1                      xxx-base
</code>```

PS: OS is Centos7

Body:
When I use yum remove <package_name> -y, it removes the package, but I was able to find the package anyway with the which <package_name> command, and cannot be found when remove again

# yum list  | grep pssh
mpssh.x86_64                            1.3.3-2.el7                  epel
pssh.noarch                             2.3.1-5.el7                  epel
pssh.x86_64                             3.4.1-1                      xxx-base
# yum remove pssh -y
Loaded plugins: fastestmirror, langpacks
No Match for argument: pssh
No Packages marked for removal
# which pssh
/usr/bin/pssh

What can I do to completely remove the packages installed by yum install?

And I was able to install pssh again, I intercepted the list results before and after the installation and removal

# after yum install pssh -y
# yum list | grep pssh
pssh.x86_64                             3.4.1-1                      @xxx-base
mpssh.x86_64                            1.3.3-2.el7                  epel
pssh.noarch                             2.3.1-5.el7                  epel

# after yum remove pssh -y
# yum list | grep pssh
mpssh.x86_64                            1.3.3-2.el7                  epel
pssh.noarch                             2.3.1-5.el7                  epel
pssh.x86_64                             3.4.1-1                      xxx-base

PS: OS is Centos7


来源: stackexchange

问:
How can I run an async task before react app starts
I'm looking for a handle that would allow me to run async code in the RN runtime before my React Native app executes.

I tried something like this

```<code>// index.js
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

asyncTask.then(() => {
  AppRegistry.registerComponent(appName, () => App);
});
</code>```

but the code crashes with

ERROR  Invariant Violation: Module AppRegistry is not a registered
callable module (calling runApplication). A frequent cause of the
error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.

Isn't there a provided way to run async tasks before the app starts ?

In my case I need this to do required updates on AsyncStorage

ContentLicense: CC BY-SA 4.0

Body:
I'm looking for a handle that would allow me to run async code in the RN runtime before my React Native app executes.

I tried something like this

// index.js
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

asyncTask.then(() => {
  AppRegistry.registerComponent(appName, () => App);
});

but the code crashes with

ERROR  Invariant Violation: Module AppRegistry is not a registered
callable module (calling runApplication). A frequent cause of the
error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.

Isn't there a provided way to run async tasks before the app starts ?

In my case I need this to do required updates on AsyncStorage


问:
How to display column of bootstrap conditionally applying map function
while iterating the loop I am getting exact no of column for each row

I want to display 8 col 4 col in first row , 4 4 4 col in second row and 8 col 4 col in third row while applying loop

```<code> <div className="row">
        {popularDestinations?.map((trip, index) => (
          <div className= "col-lg-4 col-md-4 col-4" >
            <div className="image-box">
              <div className="name-desc hover-1 image-box rounded">
                <img className="w-100" src={trip.image} alt="" />
                <div className="hover-1-content p-2">
                  <div className="title text-left">
                    {trip.country} - {trip.price} {trip.currency}
                  </div>
                  <p className="hover-1-description mb-0">
                    <Link to="/country-page">
                      <strong>Click to Book</strong>{" "}
                      <i class="fa fa-angle-double-right"></i>{" "}
                    </Link>
                  </p>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
</code>```

Body:
while iterating the loop I am getting exact no of column for each row

I want to display 8 col 4 col in first row , 4 4 4 col in second row and 8 col 4 col in third row while applying loop

        {popularDestinations?.map((trip, index) => (

                    {trip.country} - {trip.price} {trip.currency}

                    <Link to="/country-page">
                      Click to Book{" "}
                      {" "}
                    </Link>

        ))}


问:
Horizontal scroll when using table responsive with Bootstrap 5
I have a table with lots of headers and data, I need to make it responsive

As mentioned in the documentation, I wrapped the  inside a  and gave the div table-responsive class.

The issue is that the table takes up a lot of space which alters the parent's width and I'm left with a horizontal scroll on my main page as well as inside the table. (At least table-responsive is working.)

Below is my code where div is a parent element and table is a child element.

```<code><div class="table-responsive">
  <table class="table">
    <thead>
    <tbody>
    etc...
  </table>
</div>
</code>```
```<code><div
          className={`mt-4 w-100 table-responsive ${styles?.tableHeight}`}
        >
          <table className="table w-100">
            <thead className="">
              <tr>
                <th className="gap-2 text-left" style={{ width: "50px" }}>
                  <div className=" fw-700 ps-4">ID</div>
                </th>
                <th
                  className="gap-2 text-center"
                  style={{ width: "120px" }}
                >
                  <div className=" fw-700">Business</div>
                </th>
                <th
                  className="gap-2 text-center"
                  style={{ width: "100px" }}
                >
                  <div className=" fw-700">Owner Name</div>
                </th>
                <th
                  className="gap-2 text-center"
                  style={{ width: "150px" }}
                >
                  <div className=" fw-700">Owner Email</div>
                </th>
                <th
                  className="gap-2 text-center"
                  style={{ width: "120px" }}
                >
                  <div className=" fw-700">Business Email</div>
                </th>
                <th className="gap-2 text-left " style={{ width: "100px" }}>
                  <div className=" fw-700 ms-4">Business Mobile</div>
                </th>
                <th className="gap-2 text-left " style={{ width: "100px" }}>
                  <div className=" fw-700 ms-4">Last update</div>
                </th>
                <th className="gap-2 text-left " style={{ width: "80px" }}>
                  <div className=" fw-700 ms-4">Status</div>
                </th>
                <th className="gap-2 text-left " style={{ width: "100px" }}>
                  <div className=" fw-700 ms-4">Subscription</div>
                </th>
                <th className="gap-2 text-left " style={{ width: "100px" }}>
                  <div className=" fw-700 ms-4">Expiry Date</div>
                </th>
                <th className="gap-2 text-left " style={{ width: "80px" }}>
                  <div className=" fw-700 ms-4">Action</div>
                </th>
              </tr>
            </thead>
            <tbody>
              {tableData?.length > 0 &&
                tableData?.map((data, index) => {
                  return (
                    <tr key={index}>
                      <td>{data?.id}</td>
                      <td>{data?.business}</td>
                      <td>{data?.owner}</td>
                      <td>{data?.ownerEmail}</td>
                      <td>{data?.businessEmail}</td>
                      <td>{data?.ownerMobile}</td>
                      <td>{data?.businessMobile}</td>
                      <td>{data?.update}</td>
                      <td>{data?.status}</td>
                      <td>{data?.subscription}</td>
                      <td>{data?.expDate}</td>
                      <td>
                        <div>
                          <button>Edit</button>
                          <button>Delete</button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
            </tbody>
          </table>
        </div>
</code>```

Body:
I have a table with lots of headers and data, I need to make it responsive

As mentioned in the documentation, I wrapped the  inside a  and gave the div table-responsive class.

The issue is that the table takes up a lot of space which alters the parent's width and I'm left with a horizontal scroll on my main page as well as inside the table. (At least table-responsive is working.)

Below is my code where div is a parent element and table is a child element.

    etc...

<div
          className={`mt-4 w-100 table-responsive ${styles?.tableHeight}`}
        >

ID

Business

Owner Name

Owner Email

Business Email

Business Mobile

Last update

Status

Subscription

Expiry Date

Action

              {tableData?.length > 0 &&
                tableData?.map((data, index) => {
                  return (

                      {data?.id}
                      {data?.business}
                      {data?.owner}
                      {data?.ownerEmail}
                      {data?.businessEmail}
                      {data?.ownerMobile}
                      {data?.businessMobile}
                      {data?.update}
                      {data?.status}
                      {data?.subscription}
                      {data?.expDate}

                          <button>Edit</button>
                          <button>Delete</button>

                  );
                })}


问:
Why onDurationChanged is not called in Flutter ios?
I'm using  audioplayers: 1.1.0 library to play audio from url

I use the onDurationChanged method to get the audio file length. This is working perfectly on android but in iOS the onDurationChanged is not getting called.
I tried all solutions available in the internet. Noting helps as expected. Your help wil save my day.

Note: If I use

```<code> player.play(UrlSource('theme_01.mp3'));
</code>```

Now works fine. But If I use

```<code> player.play(UrlSource('https://www.kozco.com/tech/LRMonoPhase4.mp3');
</code>```

onDurationChanged is not working

```<code>import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'dart:async';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Audio Player'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final player = AudioPlayer();
  bool isPlaying = false;
  Duration duration = Duration.zero;
  Duration position = Duration.zero;

  String formatTime(int seconds) {
    return '${(Duration(seconds: seconds))}'.split('.')[0].padLeft(8, '0');
  }

  final AudioContext audioContext = AudioContext(
    iOS: AudioContextIOS(
      defaultToSpeaker: true,
      category: AVAudioSessionCategory.ambient,
      options: [
        AVAudioSessionOptions.defaultToSpeaker,
        AVAudioSessionOptions.mixWithOthers,
      ],
    ),
    android: AudioContextAndroid(
      isSpeakerphoneOn: true,
      stayAwake: true,
      contentType: AndroidContentType.sonification,
      usageType: AndroidUsageType.assistanceSonification,
      audioFocus: AndroidAudioFocus.none,
    ),
  );

  @override
  void initState() {
    super.initState();
    AudioPlayer.global.setGlobalAudioContext(audioContext);

    player.onPlayerStateChanged.listen((state) {
      setState(() {
        isPlaying = state == PlayerState.playing;
      });
    });

    player.onDurationChanged.listen((newDuration) {
      setState(() {
        duration = newDuration;
      });
    });

    player.onPositionChanged.listen((newPosition) {
      setState(() {
        position = newPosition;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Slider(
              min: 0,
              max: duration.inSeconds.toDouble(),
              value: position.inSeconds.toDouble(),
              onChanged: (value) {
                final position = Duration(seconds: value.toInt());
                player.seek(position);
                player.resume();
              },
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircleAvatar(
                  radius: 25,
                  child: IconButton(
                    icon: Icon(
                      isPlaying ? Icons.pause : Icons.play_arrow,
                    ),
                    onPressed: () {
                      if (isPlaying) {
                        player.pause();
                      } else {
                         // player.play(UrlSource('theme_01.mp3'));
// If I use local audio works fine. But If I use the below audio url onDurationChanged is not called.

                        player.play(UrlSource('https://www.kozco.com/tech/LRMonoPhase4.mp3'));
                      }
                    },
                  ),
                ),
                SizedBox(
                  width: 20,
                ),
                CircleAvatar(
                  radius: 25,
                  child: IconButton(
                    icon: const Icon(Icons.stop),
                    onPressed: () {
                      player.stop();
                    },
                  ),
                ),
              ],
            ),
            Container(
              padding: const EdgeInsets.all(20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(formatTime(position.inSeconds)),
                  Text(formatTime((duration - position).inSeconds)),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
I'm using  audioplayers: 1.1.0 library to play audio from url

I use the onDurationChanged method to get the audio file length. This is working perfectly on android but in iOS the onDurationChanged is not getting called.
I tried all solutions available in the internet. Noting helps as expected. Your help wil save my day.

Note: If I use

 player.play(UrlSource('theme_01.mp3'));

Now works fine. But If I use

 player.play(UrlSource('https://www.kozco.com/tech/LRMonoPhase4.mp3');

onDurationChanged is not working

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'dart:async';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Audio Player'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final player = AudioPlayer();
  bool isPlaying = false;
  Duration duration = Duration.zero;
  Duration position = Duration.zero;

  String formatTime(int seconds) {
    return '${(Duration(seconds: seconds))}'.split('.')[0].padLeft(8, '0');
  }

  final AudioContext audioContext = AudioContext(
    iOS: AudioContextIOS(
      defaultToSpeaker: true,
      category: AVAudioSessionCategory.ambient,
      options: [
        AVAudioSessionOptions.defaultToSpeaker,
        AVAudioSessionOptions.mixWithOthers,
      ],
    ),
    android: AudioContextAndroid(
      isSpeakerphoneOn: true,
      stayAwake: true,
      contentType: AndroidContentType.sonification,
      usageType: AndroidUsageType.assistanceSonification,
      audioFocus: AndroidAudioFocus.none,
    ),
  );

  @override
  void initState() {
    super.initState();
    AudioPlayer.global.setGlobalAudioContext(audioContext);

    player.onPlayerStateChanged.listen((state) {
      setState(() {
        isPlaying = state == PlayerState.playing;
      });
    });

    player.onDurationChanged.listen((newDuration) {
      setState(() {
        duration = newDuration;
      });
    });

    player.onPositionChanged.listen((newPosition) {
      setState(() {
        position = newPosition;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Slider(
              min: 0,
              max: duration.inSeconds.toDouble(),
              value: position.inSeconds.toDouble(),
              onChanged: (value) {
                final position = Duration(seconds: value.toInt());
                player.seek(position);
                player.resume();
              },
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircleAvatar(
                  radius: 25,
                  child: IconButton(
                    icon: Icon(
                      isPlaying ? Icons.pause : Icons.play_arrow,
                    ),
                    onPressed: () {
                      if (isPlaying) {
                        player.pause();
                      } else {
                         // player.play(UrlSource('theme_01.mp3'));
// If I use local audio works fine. But If I use the below audio url onDurationChanged is not called.

                        player.play(UrlSource('https://www.kozco.com/tech/LRMonoPhase4.mp3'));
                      }
                    },
                  ),
                ),
                SizedBox(
                  width: 20,
                ),
                CircleAvatar(
                  radius: 25,
                  child: IconButton(
                    icon: const Icon(Icons.stop),
                    onPressed: () {
                      player.stop();
                    },
                  ),
                ),
              ],
            ),
            Container(
              padding: const EdgeInsets.all(20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(formatTime(position.inSeconds)),
                  Text(formatTime((duration - position).inSeconds)),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}


问:
How to have multiple trendlines on one plot in R?
I have run two models on a dataset I have and got the predictions for them. I combined the predictions from two models and observations into one dataframe and used melt to so I would be able to plot them all together on one plot. Here is the summary of my data:

```<code> dbhclass              series       value
 2.5    : 3   pDead.year     :39   Min.   :0.000000
 5      : 3   pDead.year.glm1:39   1st Qu.:0.000000
 7.5    : 3   pDead.year.glm2:39   Median :0.008626
 10     : 3                        Mean   :0.011524
 12.5   : 3                        3rd Qu.:0.019542
 15     : 3                        Max.   :0.052297
 (Other):99
</code>```

I plot it using this code:

```<code>ggplot(df1, aes(dbhclass,value, col = series))+
  geom_point()+
  geom_smooth(method = "glm")
</code>```

And then get this graph, and as you can see there are no trendlines visible, and I would like to have the trend lines for the observed and two predictions for easier comparison.

Body:
I have run two models on a dataset I have and got the predictions for them. I combined the predictions from two models and observations into one dataframe and used melt to so I would be able to plot them all together on one plot. Here is the summary of my data:

 dbhclass              series       value
 2.5    : 3   pDead.year     :39   Min.   :0.000000
 5      : 3   pDead.year.glm1:39   1st Qu.:0.000000
 7.5    : 3   pDead.year.glm2:39   Median :0.008626
 10     : 3                        Mean   :0.011524
 12.5   : 3                        3rd Qu.:0.019542
 15     : 3                        Max.   :0.052297
 (Other):99

I plot it using this code:

ggplot(df1, aes(dbhclass,value, col = series))+
  geom_point()+
  geom_smooth(method = "glm")

And then get this graph, and as you can see there are no trendlines visible, and I would like to have the trend lines for the observed and two predictions for easier comparison.


问:
NextCloud: how to upload a large file via a shared link
I am trying to find a way to enable large file uploads (>> 1GB) on shared upload-enabled links. Direct uploading of small files via Webdav works here, when one takes the last path of the link as http user name.

However, the file size is too large to do this within a single chunk (and our admin will not increase the maximum upload size).

I found two ways to do chunked uploads programmatically:

the OwnCloud one:

use a specific file name <path/filename>-chunking-<transferid>-<chunkcount>-<index> for each path

the NextCloud one:

manually create a directory within the url <server>/remote.php/dav/uploads/<userid> (http MKCOL request)

upload the chunks there with http PUT to that directory

moving/concatenating the contents with MOVE of a special file .file in that directory

However, these two chunked methods don't work with shared links. So, is there any way to upload large files to a NextCloud server via shared links?

I want to do this on the shell, i.e. with curl or Python or so.


问:
window.history.go(-1) not working for Mobile
I have this function in site. This works well for Desktop
but it doesn't work for mobile device.

self.BackToPreviousPage = function () { var backStepNumber = window.location.hash || window.location.href.indexOf("#") != -1 ? 2 : 1; window.history.go(-backStepNumber); };

somewhere I heard that there is a new technique for writing code for window.history.go() but I did not find information about it anywhere.
Anyone have an idea ?

p.s. e.preventDefault() didn't help me


问:
How can I use XlsxWriter or other external libraries with PythonKit?
I've been trying to use my XlsxWriter based python script in my swift app with PythonKit.

At first I tried installing XlsxWriter by running:

pip3 install XlsxWriter

It installed with no errors and the code runs fine in PyCharm when I import the library into the project. This however is broken in Swift.

My swift is:

```<code>import Foundation
import PythonKit

let dirPath = "/Users/johnson/Desktop/"

func runPythonCode(){
    let sys = Python.import("sys")
    sys.path.append(dirPath)
    let example = Python.import("sample")
    let response = example.hello()
    print(response)
}

runPythonCode()
</code>```

My python is:

```<code>import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('A1', 'Heyeyeye')

workbook.close()
</code>```

Xcode returns the following error when I try to run:

```<code>PythonKit/Python.swift:706: Fatal error: 'try!' expression unexpectedly raised an error: Python exception: No module named 'xlsxwriter'
Traceback:
  File "/Users/johnson/Desktop/sample.py", line 1, in <module>
    import xlsxwriter

2022-12-08 11:09:52.812915+0200 Python-Test[21898:534512] PythonKit/Python.swift:706: Fatal error: 'try!' expression unexpectedly raised an error: Python exception: No module named 'xlsxwriter'
Traceback:
  File "/Users/johnson/Desktop/sample.py", line 1, in <module>
    import xlsxwriter
</code>```

Partial solution:

Running:

```<code>pip install XlsxWriter
</code>```

instead of:

```<code>pip3 install XlsxWriter
</code>```

fixes this within Xcode.

Remaining issue:

When I export my executable via:

Xcode>Product>Archive>Distribute Content>Built Products

The executable runs the swift code fine, manages to import the python file but returns the following error:

```<code>PythonKit/Python.swift:706: Fatal error: 'try!' expression unexpectedly raised an error: Python exception: No module named 'xlsxwriter'
</code>```

The code runs fine within Xcode, no problems with xlsxwriter, but the standalone executable running the same python script fails. What could be causing this?

Body:
I've been trying to use my XlsxWriter based python script in my swift app with PythonKit.

At first I tried installing XlsxWriter by running:

pip3 install XlsxWriter

It installed with no errors and the code runs fine in PyCharm when I import the library into the project. This however is broken in Swift.

My swift is:

import Foundation
import PythonKit

let dirPath = "/Users/johnson/Desktop/"

func runPythonCode(){
    let sys = Python.import("sys")
    sys.path.append(dirPath)
    let example = Python.import("sample")
    let response = example.hello()
    print(response)
}

runPythonCode()

My python is:

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('A1', 'Heyeyeye')

workbook.close()

Xcode returns the following error when I try to run:

PythonKit/Python.swift:706: Fatal error: 'try!' expression unexpectedly raised an error: Python exception: No module named 'xlsxwriter'
Traceback:
  File "/Users/johnson/Desktop/sample.py", line 1, in <module>
    import xlsxwriter

2022-12-08 11:09:52.812915+0200 Python-Test[21898:534512] PythonKit/Python.swift:706: Fatal error: 'try!' expression unexpectedly raised an error: Python exception: No module named 'xlsxwriter'
Traceback:
  File "/Users/johnson/Desktop/sample.py", line 1, in <module>
    import xlsxwriter

Partial solution:

Running:

pip install XlsxWriter

instead of:

pip3 install XlsxWriter

fixes this within Xcode.

Remaining issue:

When I export my executable via:

Xcode>Product>Archive>Distribute Content>Built Products

The executable runs the swift code fine, manages to import the python file but returns the following error:

PythonKit/Python.swift:706: Fatal error: 'try!' expression unexpectedly raised an error: Python exception: No module named 'xlsxwriter'

The code runs fine within Xcode, no problems with xlsxwriter, but the standalone executable running the same python script fails. What could be causing this?


问:
How to parameterize/dynamically change branch parameter for AWSCodePipeline?
I am looking for a solution to support multi branch based AWSCodePipeline for a pipeline project using console. As per study, there is one solution available which is using CloudFormation only.

But, in my case the requirement is to setup the same using AWS console. If a pipeline configured for a project, then how can we utilize same pipeline for other branches like Test, Pre-Prod & Master.

enter image description here

I can move the artifacts from one branch to others, but in my case some environment-based variable has be there with other branches for their specific infrastructure.

Now, looking for the way to dynamically change the branches for the same Pipeline.


问:
cannot as mutable more than once at a time error when chaning values in a map
The following code works properly:

let mut results = HashMap::new();

let a = results.entry("a".to_string()).or_insert("1".to_string());
*a = "11".to_string();
let b = results.entry("b".to_string()).or_insert("2".to_string());
*b = "22".to_string();
```
<p>However, if changes the code order to:</p>
<pre class="lang-rust prettyprint-override"><code>let mut results = HashMap::new();

let a = results.entry("a".to_string()).or_insert("1".to_string());
let b = results.entry("b".to_string()).or_insert("2".to_string());
*a = "11".to_string();
*b = "22".to_string();
</code>```

there occurs a compile error said:

```<code>cannot borrow `results` as mutable more than once at a time

let a = results.entry("a".to_string()).or_insert("1".to_string());
        ------------------------------ first mutable borrow occurs here
let b = results.entry("b".to_string()).or_insert("2".to_string());
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
*a = "11".to_string();
-- first borrow later used here
</code>```

In my view, I just borrowd a and b which are totally different variables. May I know what the real differences between the two code segments are please?

Body:
The following code works properly:

let mut results = HashMap::new();

let a = results.entry("a".to_string()).or_insert("1".to_string());
*a = "11".to_string();
let b = results.entry("b".to_string()).or_insert("2".to_string());
*b = "22".to_string();

However, if changes the code order to:

let mut results = HashMap::new();

let a = results.entry("a".to_string()).or_insert("1".to_string());
let b = results.entry("b".to_string()).or_insert("2".to_string());
*a = "11".to_string();
*b = "22".to_string();

there occurs a compile error said:

cannot borrow `results` as mutable more than once at a time

let a = results.entry("a".to_string()).or_insert("1".to_string());
        ------------------------------ first mutable borrow occurs here
let b = results.entry("b".to_string()).or_insert("2".to_string());
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
*a = "11".to_string();
-- first borrow later used here

In my view, I just borrowd a and b which are totally different variables. May I know what the real differences between the two code segments are please?


问:
SOAPEnvelope class replacement after WSE 3.0 decomission
I ran into an issue recently when in an existing Console Application project we're forced to remove a reference to WSE 3.0. When I tried to remove it from references (because I could not find where it's used) it turned out there is only one place and it's using the SoapEnvelope class.

A little bit about the application: it's a console application that connects to an Exchange Server and listens to incoming emails, around 2-3k emails daily.

The SoapEnvelope class is used to read and parse the email body:

```<code>    /// <summary>
    /// Reads content of received HTTP request.
    /// </summary>
    /// <param name="client">The specified client.</param>
    /// <returns>The watermark string if the read is successful; otherwise the last watermark.</returns>
    public string Read(TcpClient client)
    {
        try
        {
            _myReadBuffer = new byte[client.ReceiveBufferSize];

            using (var networkStream = client.GetStream())
            {
                var httpRequest = new MailboxHttpRequest(networkStream);

                if (httpRequest.HasBody)
                {
                    var httpResponse = new MailboxHttpResponse(_mailbox);

                    httpResponse.ParseBody(httpRequest.Body);
                    httpResponse.Send(networkStream, httpRequest.Body);
                }

                return httpRequest.Watermark;
            }
        }
        catch (Exception ex)
        {
            Logger.WriteErrorLine("[EventsCollector] Error calling Read in MailboxNotificationManager", ex);

            return _mailbox.LastWatermark;
        }
        finally
        {
            _myReadBuffer = null;
        }
    }
</code>```

And the ParseBody methods looks like this:

```<code>        /// <summary>
        /// Parses the XML body content of receive notification and initialized email processing, if new message was received.
        /// </summary>
        /// <param name="body">XML content of received notification.</param>
        public void ParseBody(string body)
        {
            var soapEnvelope = new SoapEnvelope() { InnerXml = body };

            var serializer = new XmlSerializer(typeof(SendNotificationResponseType));

            using (var reader = new XmlNodeReader(soapEnvelope.Body.FirstChild))
            {
                var notificationResponse = (SendNotificationResponseType)serializer.Deserialize(reader);

                if (notificationResponse.ResponseMessages != null)  // Process notification, if request contains response message
                {
                    _result = processNotification(notificationResponse);
                }
            }
        }
</code>```

As you can see, it creates a SoapEnvelope class to access the body`s first child.

MailboxHttpRequest class

```<code>private class MailboxHttpRequest
        {
            private readonly Regex _httpRequestBodyLengthPattern = new Regex(@"Content-Length: (?<BodyLength>\d*)", RegexOptions.Compiled);
            private readonly Regex _httpRequestBodyPattern = new Regex(@"<\?xml .*", RegexOptions.Compiled);
            private readonly Regex _httpRequestWatermarkPattern = new Regex(@"<t:Watermark>(?<Watermark>.*?)<\/t:Watermark>", RegexOptions.Compiled);

            private const int _bufferSize = 8192;

            public bool HasBody
            {
                get { return !String.IsNullOrEmpty(Body); }
            }

            public string Body { get; private set; }

            public string Watermark { get; private set; }

            /// <summary>
            /// Initializes a new instance of the <see cref="MailboxHttpRequest"/> class and reads incoming messages
            /// </summary>
            /// <param name="networkStream">The network stream.</param>
            public MailboxHttpRequest(NetworkStream networkStream)
            {
                var completeRequest = new StringBuilder();
                var readBuffer = new byte[_bufferSize];

                do  // Read incoming message that might consist of many parts
                {
                    var newDataLength = networkStream.Read(readBuffer, 0, readBuffer.Length);
                    completeRequest.Append(Encoding.ASCII.GetString(readBuffer, 0, newDataLength));
                }
                while (networkStream.DataAvailable || !requestWasFullyReceived(completeRequest.ToString()));

                Body = _httpRequestBodyPattern.Match(completeRequest.ToString())
                                                                    .Value;
                Watermark = _httpRequestWatermarkPattern.Match(Body).Groups["Watermark"].Value;
            }
}
</code>```

The downside is that I`m not able test this part of code since I cant listen to same mailbox so I cant check what and how does the passed string look like.

If anybody has any suggestion on how to replace the SoapEnvelope class, would be greatly appreciate it.

Cosmin

Body:
I ran into an issue recently when in an existing Console Application project we're forced to remove a reference to WSE 3.0. When I tried to remove it from references (because I could not find where it's used) it turned out there is only one place and it's using the SoapEnvelope class.

A little bit about the application: it's a console application that connects to an Exchange Server and listens to incoming emails, around 2-3k emails daily.

The SoapEnvelope class is used to read and parse the email body:

    ///
    /// Reads content of received HTTP request.
    ///
    /// <param name="client">The specified client.</param>
    /// <returns>The watermark string if the read is successful; otherwise the last watermark.</returns>
    public string Read(TcpClient client)
    {
        try
        {
            _myReadBuffer = new byte[client.ReceiveBufferSize];

            using (var networkStream = client.GetStream())
            {
                var httpRequest = new MailboxHttpRequest(networkStream);

                if (httpRequest.HasBody)
                {
                    var httpResponse = new MailboxHttpResponse(_mailbox);

                    httpResponse.ParseBody(httpRequest.Body);
                    httpResponse.Send(networkStream, httpRequest.Body);
                }

                return httpRequest.Watermark;
            }
        }
        catch (Exception ex)
        {
            Logger.WriteErrorLine("[EventsCollector] Error calling Read in MailboxNotificationManager", ex);

            return _mailbox.LastWatermark;
        }
        finally
        {
            _myReadBuffer = null;
        }
    }

And the ParseBody methods looks like this:

        ///
        /// Parses the XML body content of receive notification and initialized email processing, if new message was received.
        ///
        /// <param name="body">XML content of received notification.</param>
        public void ParseBody(string body)
        {
            var soapEnvelope = new SoapEnvelope() { InnerXml = body };

            var serializer = new XmlSerializer(typeof(SendNotificationResponseType));

            using (var reader = new XmlNodeReader(soapEnvelope.Body.FirstChild))
            {
                var notificationResponse = (SendNotificationResponseType)serializer.Deserialize(reader);

                if (notificationResponse.ResponseMessages != null)  // Process notification, if request contains response message
                {
                    _result = processNotification(notificationResponse);
                }
            }
        }

As you can see, it creates a SoapEnvelope class to access the body`s first child.

MailboxHttpRequest class

private class MailboxHttpRequest
        {
            private readonly Regex _httpRequestBodyLengthPattern = new Regex(@"Content-Length: (?<BodyLength>\d*)", RegexOptions.Compiled);
            private readonly Regex _httpRequestBodyPattern = new Regex(@"<\?xml .*", RegexOptions.Compiled);
            private readonly Regex _httpRequestWatermarkPattern = new Regex(@"<t:Watermark>(?<Watermark>.*?)<\/t:Watermark>", RegexOptions.Compiled);

            private const int _bufferSize = 8192;

            public bool HasBody
            {
                get { return !String.IsNullOrEmpty(Body); }
            }

            public string Body { get; private set; }

            public string Watermark { get; private set; }

            ///
            /// Initializes a new instance of the <see cref="MailboxHttpRequest"/> class and reads incoming messages
            ///
            /// <param name="networkStream">The network stream.</param>
            public MailboxHttpRequest(NetworkStream networkStream)
            {
                var completeRequest = new StringBuilder();
                var readBuffer = new byte[_bufferSize];

                do  // Read incoming message that might consist of many parts
                {
                    var newDataLength = networkStream.Read(readBuffer, 0, readBuffer.Length);
                    completeRequest.Append(Encoding.ASCII.GetString(readBuffer, 0, newDataLength));
                }
                while (networkStream.DataAvailable || !requestWasFullyReceived(completeRequest.ToString()));

                Body = _httpRequestBodyPattern.Match(completeRequest.ToString())
                                                                    .Value;
                Watermark = _httpRequestWatermarkPattern.Match(Body).Groups["Watermark"].Value;
            }
}

The downside is that I`m not able test this part of code since I cant listen to same mailbox so I cant check what and how does the passed string look like.

If anybody has any suggestion on how to replace the SoapEnvelope class, would be greatly appreciate it.

Cosmin


问:
'Supports Siri' on the AppStore not showing and my app supports Siri
Is there any trigger to enable the 'Supports Siri' item in the app store?

My app supports Siri and Siri shortcut works well. I have added Siri to my capabilities. I have my intents working fine, but on the AppStore page when checking my app it doesn't show that it "Supports Siri".
Any clue?


问:
Get Data from Excel Sheets to mastersheet and edit with doublecklick
i have an Workbook with 5 Sheets where you can add Data while Using a Userform. The Data begins in each Sheet in row 10, since i nead the rows above 10 for my interface. I have also an Mastersheet, where the Data from these specific Sheets should be copied and should be edited if needed by DoubleClick and an Unserform. I Managed to write the Code for Copying the Data from these Sheets, but I also need the Sheetname next to the Data in Column A, so it's clear where the Data is from. The Data begins also in Row 10 of the Mastersheet.

1.Problem: Can't get the Sheet names in Column A and the Data to start in Column A.
2. If one Sheet is empty it Copies the Headers into the Mastersheet
3. By Double Click in the Row my Userform doesn't appear.
When i write The Sheet Name in Column B of the Mastersheet, the Data gets edited. But The Mastersheet should refresh itself when the editing is done

I would really appreciate if someone could help me, since i just startet with vba and don't know What to do.

`

```<code>Private Sub Worksheet_Activate()
Dim Ws As Worksheet
Me.Rows("6:" & Rows.count).Clear
Me.Range("A9:Z9").Value = Array("Markt".... (And So on)

For Each Ws In ThisWorkbook.Worksheets
If Ws.Name <> "Summary" And Ws.Name <> "Startseite" And Ws.Name <> "Agenda" (And so on) Then
        Ws.Rows("10:" & Ws.Cells.Find("*", searchdirection:=xlPrevious).Row).Copy Me.Range("A" & Me.Cells.Find("*", searchdirection:=xlPrevious).Row + 1)
End If
Next Ws

End Sub
</code>```

```<code>Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Excel.Range, Cancel As Boolean)
Dim Sheet As String
Dim POS As Integer

Cancel = True

If Range(Target.Address).Row >= 10 Then
    Sheet = Cells(Target.Row, 2).Value 'Get The Sheet Name from Column B I could change that bu I need the Sheet name in a Column to do that
    If IsNumeric(Cells(Target.Row, 1).Value) Then
        POS = CInt(Cells(Target.Row, 1).Value)
    Else
        POS = 0
    End If
Else
    Exit Sub
End If

If POS = 0 Then
    Exit Sub
Else
    Sheets("Code").Range("G2") = Sheet
    Sheets("Code").Range("G3") = POS
End If

Edit.Show

End Sub
</code>```

`

I tried changing the code but it didn't work

Body:
i have an Workbook with 5 Sheets where you can add Data while Using a Userform. The Data begins in each Sheet in row 10, since i nead the rows above 10 for my interface. I have also an Mastersheet, where the Data from these specific Sheets should be copied and should be edited if needed by DoubleClick and an Unserform. I Managed to write the Code for Copying the Data from these Sheets, but I also need the Sheetname next to the Data in Column A, so it's clear where the Data is from. The Data begins also in Row 10 of the Mastersheet.

1.Problem: Can't get the Sheet names in Column A and the Data to start in Column A.
2. If one Sheet is empty it Copies the Headers into the Mastersheet
3. By Double Click in the Row my Userform doesn't appear.
When i write The Sheet Name in Column B of the Mastersheet, the Data gets edited. But The Mastersheet should refresh itself when the editing is done

I would really appreciate if someone could help me, since i just startet with vba and don't know What to do.

`

Private Sub Worksheet_Activate()
Dim Ws As Worksheet
Me.Rows("6:" & Rows.count).Clear
Me.Range("A9:Z9").Value = Array("Markt".... (And So on)

For Each Ws In ThisWorkbook.Worksheets
If Ws.Name <> "Summary" And Ws.Name <> "Startseite" And Ws.Name <> "Agenda" (And so on) Then
        Ws.Rows("10:" & Ws.Cells.Find("*", searchdirection:=xlPrevious).Row).Copy Me.Range("A" & Me.Cells.Find("*", searchdirection:=xlPrevious).Row + 1)
End If
Next Ws

End Sub

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Excel.Range, Cancel As Boolean)
Dim Sheet As String
Dim POS As Integer

Cancel = True

If Range(Target.Address).Row >= 10 Then
    Sheet = Cells(Target.Row, 2).Value 'Get The Sheet Name from Column B I could change that bu I need the Sheet name in a Column to do that
    If IsNumeric(Cells(Target.Row, 1).Value) Then
        POS = CInt(Cells(Target.Row, 1).Value)
    Else
        POS = 0
    End If
Else
    Exit Sub
End If

If POS = 0 Then
    Exit Sub
Else
    Sheets("Code").Range("G2") = Sheet
    Sheets("Code").Range("G3") = POS
End If

Edit.Show

End Sub

`

I tried changing the code but it didn't work


问:
ArcGIS initializing or loading error: unable to establish connection to https://www.arcgis.com
I've been having issues opening Arcgis pro for a few days. I've tried all the options provided by the ESRI help team and nothing has worked so far. I have set the TLS 1.2 requirement, the organization and group permissions, added it to trusted sites on my anti virus, etc. I have uninstalled and reinstalled ArcGIS pro and it didn't work. I uninstalled a few programs I though were redundant on my system and suspect that I may have touched once of its dependencies. I uninstalled a version of conda, visual studio, and I suspect a version of python too. This was all in a bid to get arcpy working on this system as the import arcpy command through python IDLE and Pycharm came back with errors. I still have other versions on the system but still can't load Arcgis pro. The help team reached out last 24 hours ago as this error is unusual.
Do you have any ideas on how to get my pro working again please?


问:
How to get refresh token in google
I'm getting an access token and that access token expiry time is 1 hour but after few event creation access token getting expired that's why i want's to store refresh token and using refresh token i can re-generate new access token but i'm unable to get refresh token.

Token Uri : "https://oauth2.googleapis.com/token"

Request data:

```<code>{
    "redirect_uri": "www.myapp.com",
    "grant_type": "authorization_code",
    "client_id": "873581********8******apps.google*****.com",
    "code": "{{code}}",
    "client_secret": "GOCSPX-r****ci_i8ii****iD",
    "access_type": "offline"
}
</code>```

Response:

```<code>{
  "access_token" : "HUGE_TOKEN_STRING",
  "token_type" : "Bearer",
  "expires_in" : 3600
}
</code>```

Title: How to get refresh token in google

Body:
I'm getting an access token and that access token expiry time is 1 hour but after few event creation access token getting expired that's why i want's to store refresh token and using refresh token i can re-generate new access token but i'm unable to get refresh token.

Token Uri : "https://oauth2.googleapis.com/token"

Request data:

{
    "redirect_uri": "www.myapp.com",
    "grant_type": "authorization_code",
    "client_id": "873581********8******apps.google*****.com",
    "code": "{{code}}",
    "client_secret": "GOCSPX-r****ci_i8ii****iD",
    "access_type": "offline"
}

Response:

{
  "access_token" : "HUGE_TOKEN_STRING",
  "token_type" : "Bearer",
  "expires_in" : 3600
}


问:
Can you continue a partial import after you have closed phpmyadmin?
What happens if you close phpmyadmin while it is uploading a dataset unto the database? Can you continue the upload the same as a partial upload because of a timeout or do you have to restart the process?

I'm importing a csv file of 170 mb unto my database with phpmyadmin, but it is taking very long to upload the entire file. I have already removed the time limit for the upload, because my first issue was that i hit the timeout after a very short time.


问:
Angular: Get ViewChildren inside of directive
I have a component called SomeComponent. This component contains some Elements like a paragraph which has a template reference variable attached to it. Here is an example of SomeComponent

```<code>
@Component({
  selector: "some-component",
  template: ` <p #isValid>Hello from Component</p> `
})
export class SomeComponent {
}

</code>```

I use SomeComponent in my AppComponent.
Now I want to have a Directive attached to SomeComponent that gets all Elements of SomeComponent that have the #isValid template reference variable.

My approach was using ViewChildren inside of the Directive for this. Here is an example of the directive.

```<code>@Directive({ selector: "[getIsValid]" })
export class GetIsValidDirective implements AfterViewInit{
  @ViewChildren("isValid") isValidChildren: QueryList<unknown>;

  ngAfterViewInit() {
    console.log("isValidChildren defined?", this.isValidChildren);

    this.isValidChildren?.changes.subscribe((next) =>
      console.log("isValidChildren changes", next)
    );
  }
}
</code>```

SomeComponent and GetIsValidDirective are used in the AppComponent like this:

```<code>@Component({
  selector: "app-root",
  template: ` <some-component getIsValid></some-component> `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {}
</code>```

I expected to get all Elements that hasl isValid attached to it inside the GetIsValidDirective. But this.isValidChildren is always undefined.

Am I missing something obvious here or is this just not possible because the directive has no access to the inner view of SomeComponent?

Body:
I have a component called SomeComponent. This component contains some Elements like a paragraph which has a template reference variable attached to it. Here is an example of SomeComponent

@Component({
  selector: "some-component",
  template: ` <p #isValid>Hello from Component</p> `
})
export class SomeComponent {
}

I use SomeComponent in my AppComponent.
Now I want to have a Directive attached to SomeComponent that gets all Elements of SomeComponent that have the #isValid template reference variable.

My approach was using ViewChildren inside of the Directive for this. Here is an example of the directive.

@Directive({ selector: "[getIsValid]" })
export class GetIsValidDirective implements AfterViewInit{
  @ViewChildren("isValid") isValidChildren: QueryList<unknown>;

  ngAfterViewInit() {
    console.log("isValidChildren defined?", this.isValidChildren);

    this.isValidChildren?.changes.subscribe((next) =>
      console.log("isValidChildren changes", next)
    );
  }
}

SomeComponent and GetIsValidDirective are used in the AppComponent like this:

@Component({
  selector: "app-root",
  template: ` <some-component getIsValid></some-component> `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {}

I expected to get all Elements that hasl isValid attached to it inside the GetIsValidDirective. But this.isValidChildren is always undefined.

Am I missing something obvious here or is this just not possible because the directive has no access to the inner view of SomeComponent?


问:
Using Spring Framework, How can I send stack traces to more than error-page?
webxml

```<code> <error-page>
    <error-code>405</error-code>
    <location>/support/405.jsp</location>
  </error-page>

<error-page>
    <error-code>500</error-code>
    <location>/support/500.jsp</location>
  </error-page>

  <error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/support/500.jsp</location>
  </error-page>

   <error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/support/500.jsp</location>
  </error-page>
</code>```

How do I do add excptions and throwables to more than one error page

```<code> <error-page>
    <error-code>405</error-code>
    <location>/support/405.jsp</location>
  </error-page>
</code>```

**

```<code><error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/support/405.jsp</location>
  </error-page>

   <error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/support/405.jsp</location>
  </error-page>
</code>```

**

```<code><error-page>
    <error-code>500</error-code>
    <location>/support/500.jsp</location>
  </error-page>

  <error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/support/500.jsp</location>
  </error-page>

   <error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/support/500.jsp</location>
  </error-page>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
webxml

 <error-page>
    <error-code>405</error-code>
    <location>/support/405.jsp</location>
  </error-page>

<error-page>
    <error-code>500</error-code>
    <location>/support/500.jsp</location>
  </error-page>

  <error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/support/500.jsp</location>
  </error-page>

   <error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/support/500.jsp</location>
  </error-page>

How do I do add excptions and throwables to more than one error page

 <error-page>
    <error-code>405</error-code>
    <location>/support/405.jsp</location>
  </error-page>

**

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/support/405.jsp</location>
  </error-page>

   <error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/support/405.jsp</location>
  </error-page>

**

<error-page>
    <error-code>500</error-code>
    <location>/support/500.jsp</location>
  </error-page>

  <error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/support/500.jsp</location>
  </error-page>

   <error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/support/500.jsp</location>
  </error-page>


问:
Is there an algorithm to work out the max number of small shapes you can tesselate inside a larger one?
Consider the following 4x4 grid and L-shaped tile (made up of squares the same size as those in the grid). It is obvious that the most number of L-shapes one can fit on the grid without overlapping is 5. Is there an algorithm that can find this number in general?


问:
Mosquitto can't edit config file because of error?
I completely installed everything fresh to a Raspberry Pi and installed Mosquitto. Many online instructions state that you should put listener 1883 and allow_anonymous true at the end of the config file /etc/mosquitto/mosquitto.conf to allow remote access etc.

But as soon as I put these two twos in the config file, Mosquitto won't start anymore? Somehow it also seems like no one else has the problem? I reinstalled everything and still nothing works. When I type sudo systemctl status mosquitto I get the following:

```<code>
Loaded: loaded (/lib/systemd/system/mosquitto.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Thu 2022-12-08 12:31:46 CET; 1min 50s ago
Docs: man:mosquitto.conf(5)
man:mosquitto(8)
Process: 630 ExecStartPre=/bin/mkdir -m 740 -p /var/log/mosquitto (code=exited, status=0/SUCCESS)
Process: 631 ExecStartPre=/bin/chown mosquitto /var/log/mosquitto (code=exited, status=0/SUCCESS)
Process: 632 ExecStartPre=/bin/mkdir -m 740 -p /run/mosquitto (code=exited, status=0/SUCCESS)
Process: 633 ExecStartPre=/bin/chown mosquitto /run/mosquitto (code=exited, status=0/SUCCESS)
Process: 634 ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf (code=exited, status=1/FAILURE)
Main PID: 634 (code=exited, status=1/FAILURE)
CPU: 91ms

Dec 08 12:31:46 MyPI systemd\[1\]: mosquitto.service: Scheduled restart job, restart counter is at 5.
Dec 08 12:31:46 MyPI systemd\[1\]: Stopped Mosquitto MQTT Broker.
Dec 08 12:31:46 MyPI systemd\[1\]: mosquitto.service: Start request repeated too quickly.
Dec 08 12:31:46 MyPI systemd\[1\]: mosquitto.service: Failed with result 'exit-code'.
Dec 08 12:31:46 MyPI systemd\[1\]: Failed to start Mosquitto MQTT Broker.
</code>```

Configuration file:

```<code># Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
pid_file /run/mosquitto/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d

listener 1883
allow_anonymous true
</code>```

EDIT: I now changed the listener to port 1884. And now it worked. Could it be maybe, that the Wi-Fi-Router does have some settings where it blocks every Port on 1883 or something?

Body:
I completely installed everything fresh to a Raspberry Pi and installed Mosquitto. Many online instructions state that you should put listener 1883 and allow_anonymous true at the end of the config file /etc/mosquitto/mosquitto.conf to allow remote access etc.

But as soon as I put these two twos in the config file, Mosquitto won't start anymore? Somehow it also seems like no one else has the problem? I reinstalled everything and still nothing works. When I type sudo systemctl status mosquitto I get the following:

Loaded: loaded (/lib/systemd/system/mosquitto.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Thu 2022-12-08 12:31:46 CET; 1min 50s ago
Docs: man:mosquitto.conf(5)
man:mosquitto(8)
Process: 630 ExecStartPre=/bin/mkdir -m 740 -p /var/log/mosquitto (code=exited, status=0/SUCCESS)
Process: 631 ExecStartPre=/bin/chown mosquitto /var/log/mosquitto (code=exited, status=0/SUCCESS)
Process: 632 ExecStartPre=/bin/mkdir -m 740 -p /run/mosquitto (code=exited, status=0/SUCCESS)
Process: 633 ExecStartPre=/bin/chown mosquitto /run/mosquitto (code=exited, status=0/SUCCESS)
Process: 634 ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf (code=exited, status=1/FAILURE)
Main PID: 634 (code=exited, status=1/FAILURE)
CPU: 91ms

Dec 08 12:31:46 MyPI systemd\[1\]: mosquitto.service: Scheduled restart job, restart counter is at 5.
Dec 08 12:31:46 MyPI systemd\[1\]: Stopped Mosquitto MQTT Broker.
Dec 08 12:31:46 MyPI systemd\[1\]: mosquitto.service: Start request repeated too quickly.
Dec 08 12:31:46 MyPI systemd\[1\]: mosquitto.service: Failed with result 'exit-code'.
Dec 08 12:31:46 MyPI systemd\[1\]: Failed to start Mosquitto MQTT Broker.

Configuration file:

# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
pid_file /run/mosquitto/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d

listener 1883
allow_anonymous true

EDIT: I now changed the listener to port 1884. And now it worked. Could it be maybe, that the Wi-Fi-Router does have some settings where it blocks every Port on 1883 or something?


问:
Typescript Visitor Pattern missing type info
I seem to be losing type info using the visitor design pattern in typescript:

```<code>abstract class AbsVisitor
{
  public abstract visitPerson(p: Person): void;
  public abstract visitAddress(p: Address): void;
}

class StrVisitor extends AbsVisitor
{
  public visitPerson(p: Person): void {
    console.log(`XXX ${typeof p}  XXX`) // <--- type Person is lost !
    console.log(`name: ${p.name}`);
  }
  public visitAddress(a: Address): void {
    console.log(`XXX ${typeof a}  XXX`) // <--- type Address is lost !
    console.log(`{a.street}( ${a.num} )`);
  }
}

class Person {
  constructor(public name: string){}
  public accept(v: AbsVisitor){ v.visitPerson(this); }
}

class Address {
  constructor(public street: string, public num: number){}
  public accept(v: AbsVisitor){ v.visitAddress(this); }
}

let v = new StrVisitor();
let p = new Person("moish");
let a = new Address("5th Ave.", 62);
p.accept(v);
a.accept(v);
</code>```

When I run it, I get the sub-optimal (incorrect?) result:

```<code>XXX object  XXX
name: moish
XXX object  XXX
{a.street}( 62 )
</code>```

Body:
I seem to be losing type info using the visitor design pattern in typescript:

abstract class AbsVisitor
{
  public abstract visitPerson(p: Person): void;
  public abstract visitAddress(p: Address): void;
}

class StrVisitor extends AbsVisitor
{
  public visitPerson(p: Person): void {
    console.log(`XXX ${typeof p}  XXX`) // <--- type Person is lost !
    console.log(`name: ${p.name}`);
  }
  public visitAddress(a: Address): void {
    console.log(`XXX ${typeof a}  XXX`) // <--- type Address is lost !
    console.log(`{a.street}( ${a.num} )`);
  }
}

class Person {
  constructor(public name: string){}
  public accept(v: AbsVisitor){ v.visitPerson(this); }
}

class Address {
  constructor(public street: string, public num: number){}
  public accept(v: AbsVisitor){ v.visitAddress(this); }
}

let v = new StrVisitor();
let p = new Person("moish");
let a = new Address("5th Ave.", 62);
p.accept(v);
a.accept(v);

When I run it, I get the sub-optimal (incorrect?) result:

XXX object  XXX
name: moish
XXX object  XXX
{a.street}( 62 )


问:
High light cell that contain certain text for 1 column openpyxl

A
B
C

1
jack has a cat
jack aa

2
jim has a car
jack ab

3
jack has a dog
jim cc

4
jack has a house
jim dd

I want to high light cell that got Jack with color red, Jim with yellow
what I came up with but have no outcome

```<code>def highlight_jack(ser):
       color= "red" if 'jack' in str(ser)  else ''
       return f"background-color: {color}"

def highlight_jim(ser):
       color= "yellow" if 'jim' in str(ser)  else ''
       return f"background-color: {color}"

df_merge.style.applymap(highlight_jack, subset=['B'])
df_merge.style.applymap(highlight_jim, subset=['B'])

df_merge.to_excel(writer, sheet_name= sheet, index=False)
writer.save()
</code>```

Body:
A
B
C

1
jack has a cat
jack aa

2
jim has a car
jack ab

3
jack has a dog
jim cc

4
jack has a house
jim dd

I want to high light cell that got Jack with color red, Jim with yellow
what I came up with but have no outcome

def highlight_jack(ser):
       color= "red" if 'jack' in str(ser)  else ''
       return f"background-color: {color}"

def highlight_jim(ser):
       color= "yellow" if 'jim' in str(ser)  else ''
       return f"background-color: {color}"

df_merge.style.applymap(highlight_jack, subset=['B'])
df_merge.style.applymap(highlight_jim, subset=['B'])

df_merge.to_excel(writer, sheet_name= sheet, index=False)
writer.save()


问:
CDI Interceptor fires BEFORE HttpAuthenticationMechanism validates request
We have a JSF App that uses a custom HttpAuthenticationMechanism for authentication, it forwards users to a login page if they do not have the role required and uses @AutoApplySession for authenticated users.

We have recently added a CDI interceptor @RolesPermitted that checks for required roles at Class or Method level in CDI beans (basically same at the @RolesAllowed annotation for EJB) and goes to an error page if the roles are not found.

However I found that if a backing bean has eg. @RolesPermitted({'admin'}) at the Class level and a page in /admin/secured-page.xhtml is requested as an unauthenticated user, the RolesPermitted interceptor fires BEFORE the HttpAuthenticationMechanism so we get a security exception rather than being forwarded to the login page.

The backing bean class is being referenced in the Facelets page so it seems that the JSF view is being processed before the HttpAuthenticationMechanism kicks in which seems wrong.

So the question is, how do I ensure the HttpAuthenticationMechanism is fired before my own security interceptor and user forwarded onto login page?

Here is the interceptor code:

```<code>@Interceptor
@RolesPermitted
@Priority(Interceptor.Priority.APPLICATION)
public class RoleInterceptor implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    @Inject private SecurityContext sec;
    @Inject private Logger log;

    @AroundInvoke
    public Object checkRole(InvocationContext ctx) throws Exception {

        if(ctx.getMethod().getDeclaringClass().isAnnotationPresent(RolesPermitted.class)) {
            String[] classRoles = ctx
                .getMethod().getDeclaringClass()
                .getAnnotation(RolesPermitted.class)
                .value();
            boolean hasRole = false;
            log.debug("Checking if user has {} roles to execute {}",Arrays.asList(classRoles).toString(),ctx.getMethod().getDeclaringClass().getName());
            for(String r:classRoles) {
                if(sec.isCallerInRole(r)) {
                    hasRole=true;
                }
            }
            if(!hasRole) {
                throw new java.security.GeneralSecurityException("User does not have any of the required roles "+Arrays.asList(classRoles).toString());
            }
        }
        if(ctx.getMethod().isAnnotationPresent(RolesPermitted.class)) {
            String[] methodRoles = ctx
                .getMethod()
                .getAnnotation(RolesPermitted.class)
                .value();
            if(methodRoles.length>0) {
                log.debug("Checking if user has {} roles to execute {}",Arrays.asList(methodRoles).toString(),ctx.getMethod().getName());
                for(String r:methodRoles) {
                    if(sec.isCallerInRole(r)) {
                        return ctx.proceed();
                    }
                }

                throw new java.security.GeneralSecurityException("User does not have any of the required roles "+Arrays.asList(methodRoles).toString());

            }
        }

        return ctx.proceed();

    }

}
</code>```

And backing bean that uses it...

```<code>@Named
@ViewScoped
@RolesPermitted({"admin"})
@Transactional(Transactional.TxType.REQUIRED)
public class AdminActions implements Serializable {

    //some page logic

}
</code>```

And our Authentication bean (bits removed for brevity)

```<code>@RequestScoped
@AutoApplySession
public class CustomAuthentication implements Serializable, HttpAuthenticationMechanism {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Inject private PasswordEncryptorEntities passwordEncryptor;
    @Inject private Logger log;

    /**
     * Note: this method is called for all requests (including public) to determine if authentication is required
     */
    @Override
    public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response,
            HttpMessageContext httpMessageContext) throws AuthenticationException {

        log.trace("Validating request {}",request.getRequestURI());

        if(httpMessageContext.isAuthenticationRequest()) {

            Set<String> roles = new HashSet<String>();

                    if(loginPrincipal.coreRole().equals(Role.admin)) {
                        Admin admin = (Admin) loginPrincipal;
                        if(admin.isSuperUser()) {
                            roles.add(Role.adminSuperuser.getRole());
                        }
                    }
                    UserPrincipal up = new UserPrincipal(loginPrincipal);
                    httpMessageContext.getClientSubject().getPrincipals().add(up);
                    httpMessageContext.setRegisterSession(up.getName(), roles);
                    log.debug("Login successful for {} with roles {}",loginPrincipal.getFullname(),roles.toString());
                    return httpMessageContext.notifyContainerAboutLogin(up,roles);

        }else if(httpMessageContext.isProtected() && request.getUserPrincipal()==null) {
            //Protected resource requested with no logged in user, forward to login page
            return httpMessageContext.forward(loginUrl);

            log.error("Protected resource requested does not have corresponding Role: {}",request.getRequestURI());

        }else if(httpMessageContext.isProtected() && request.getUserPrincipal()!=null) {
            //Protected resource requested with wrong role set, forward to login page
            UserPrincipal up = (UserPrincipal) request.getUserPrincipal();
            return httpMessageContext.forward(up.getAppUser().coreRole().getLoginPage().getPath());
        }

        return httpMessageContext.doNothing();

    }

}
</code>```

In web.xml we declare the security constraints and roles, eg...

```<code><security-constraint>
        <web-resource-collection>
            <web-resource-name>Admin User Login Area</web-resource-name>
            <url-pattern>/admin/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>admin</role-name>
        </auth-constraint>
        <user-data-constraint>
           <transport-guarantee>CONFIDENTIAL</transport-guarantee>
       </user-data-constraint>
    </security-constraint>
</code>```

Body:
We have a JSF App that uses a custom HttpAuthenticationMechanism for authentication, it forwards users to a login page if they do not have the role required and uses @AutoApplySession for authenticated users.

We have recently added a CDI interceptor @RolesPermitted that checks for required roles at Class or Method level in CDI beans (basically same at the @RolesAllowed annotation for EJB) and goes to an error page if the roles are not found.

However I found that if a backing bean has eg. @RolesPermitted({'admin'}) at the Class level and a page in /admin/secured-page.xhtml is requested as an unauthenticated user, the RolesPermitted interceptor fires BEFORE the HttpAuthenticationMechanism so we get a security exception rather than being forwarded to the login page.

The backing bean class is being referenced in the Facelets page so it seems that the JSF view is being processed before the HttpAuthenticationMechanism kicks in which seems wrong.

So the question is, how do I ensure the HttpAuthenticationMechanism is fired before my own security interceptor and user forwarded onto login page?

Here is the interceptor code:

@Interceptor
@RolesPermitted
@Priority(Interceptor.Priority.APPLICATION)
public class RoleInterceptor implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    @Inject private SecurityContext sec;
    @Inject private Logger log;

    @AroundInvoke
    public Object checkRole(InvocationContext ctx) throws Exception {

        if(ctx.getMethod().getDeclaringClass().isAnnotationPresent(RolesPermitted.class)) {
            String[] classRoles = ctx
                .getMethod().getDeclaringClass()
                .getAnnotation(RolesPermitted.class)
                .value();
            boolean hasRole = false;
            log.debug("Checking if user has {} roles to execute {}",Arrays.asList(classRoles).toString(),ctx.getMethod().getDeclaringClass().getName());
            for(String r:classRoles) {
                if(sec.isCallerInRole(r)) {
                    hasRole=true;
                }
            }
            if(!hasRole) {
                throw new java.security.GeneralSecurityException("User does not have any of the required roles "+Arrays.asList(classRoles).toString());
            }
        }
        if(ctx.getMethod().isAnnotationPresent(RolesPermitted.class)) {
            String[] methodRoles = ctx
                .getMethod()
                .getAnnotation(RolesPermitted.class)
                .value();
            if(methodRoles.length>0) {
                log.debug("Checking if user has {} roles to execute {}",Arrays.asList(methodRoles).toString(),ctx.getMethod().getName());
                for(String r:methodRoles) {
                    if(sec.isCallerInRole(r)) {
                        return ctx.proceed();
                    }
                }

                throw new java.security.GeneralSecurityException("User does not have any of the required roles "+Arrays.asList(methodRoles).toString());

            }
        }

        return ctx.proceed();

    }

}

And backing bean that uses it...

@Named
@ViewScoped
@RolesPermitted({"admin"})
@Transactional(Transactional.TxType.REQUIRED)
public class AdminActions implements Serializable {

    //some page logic

}

And our Authentication bean (bits removed for brevity)

@RequestScoped
@AutoApplySession
public class CustomAuthentication implements Serializable, HttpAuthenticationMechanism {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Inject private PasswordEncryptorEntities passwordEncryptor;
    @Inject private Logger log;

    /**
     * Note: this method is called for all requests (including public) to determine if authentication is required
     */
    @Override
    public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response,
            HttpMessageContext httpMessageContext) throws AuthenticationException {

        log.trace("Validating request {}",request.getRequestURI());

        if(httpMessageContext.isAuthenticationRequest()) {

            Set<String> roles = new HashSet<String>();

                    if(loginPrincipal.coreRole().equals(Role.admin)) {
                        Admin admin = (Admin) loginPrincipal;
                        if(admin.isSuperUser()) {
                            roles.add(Role.adminSuperuser.getRole());
                        }
                    }
                    UserPrincipal up = new UserPrincipal(loginPrincipal);
                    httpMessageContext.getClientSubject().getPrincipals().add(up);
                    httpMessageContext.setRegisterSession(up.getName(), roles);
                    log.debug("Login successful for {} with roles {}",loginPrincipal.getFullname(),roles.toString());
                    return httpMessageContext.notifyContainerAboutLogin(up,roles);

        }else if(httpMessageContext.isProtected() && request.getUserPrincipal()==null) {
            //Protected resource requested with no logged in user, forward to login page
            return httpMessageContext.forward(loginUrl);

            log.error("Protected resource requested does not have corresponding Role: {}",request.getRequestURI());

        }else if(httpMessageContext.isProtected() && request.getUserPrincipal()!=null) {
            //Protected resource requested with wrong role set, forward to login page
            UserPrincipal up = (UserPrincipal) request.getUserPrincipal();
            return httpMessageContext.forward(up.getAppUser().coreRole().getLoginPage().getPath());
        }

        return httpMessageContext.doNothing();

    }

}

In web.xml we declare the security constraints and roles, eg...

<security-constraint>
        <web-resource-collection>
            <web-resource-name>Admin User Login Area</web-resource-name>
            <url-pattern>/admin/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>admin</role-name>
        </auth-constraint>
        <user-data-constraint>
           <transport-guarantee>CONFIDENTIAL</transport-guarantee>
       </user-data-constraint>
    </security-constraint>


问:
React Link changes the URL path but does not load the page automatically
I'm using Link to load my detail component by a specific id which i get from firebase but when i click on it, it,ll update the URL but doesn't load the page automatically however I'm able to load it manually by refreshing the page myself.

here's my Movies.js component:

```<code>

  return (
    <Container>
        <h4>Recommended for You</h4>
        <Content>
            { movies &&
                movies.map((movie) =>(
                <Wrap key={movie.id} >
                <Link  to={`/detail/${movie.id}`}>
                    <img src={movie.cardImg} />
                    </Link>
                </Wrap>
                ))
            }
        </Content>
    </Container>
  )
}

export default Movies
</code>```

and my app.js :

```<code>import React from 'react';
import logo from './logo.svg';
import { Counter } from './features/counter/Counter';
import './App.css';
import Header from './components/Header';
import Home from './components/Home';
import Detail from './components/Detail';
import Login from './components/Login';

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

function App() {
  return (
    <div className="App">

      <Router>
      <Header />
      <Switch>
      <Route path="/login">
          <Login />
      </Route>
        <Route path="/detail/:id">
          <Detail />
        </Route>
        <Route path="/">
          <Home />
        </Route>
      </Switch>
      </Router>
    </div>
  );
}

export default App;
</code>```

Body:
I'm using Link to load my detail component by a specific id which i get from firebase but when i click on it, it,ll update the URL but doesn't load the page automatically however I'm able to load it manually by refreshing the page myself.

here's my Movies.js component:

  return (
    <Container>

Recommended for You

        <Content>
            { movies &&
                movies.map((movie) =>(
                <Wrap key={movie.id} >
                <Link  to={`/detail/${movie.id}`}>

                    </Link>
                </Wrap>
                ))
            }
        </Content>
    </Container>
  )
}

export default Movies

and my app.js :

import React from 'react';
import logo from './logo.svg';
import { Counter } from './features/counter/Counter';
import './App.css';
import Header from './components/Header';
import Home from './components/Home';
import Detail from './components/Detail';
import Login from './components/Login';

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

function App() {
  return (

      <Router>

      <Switch>
      <Route path="/login">
          <Login />
      </Route>
        <Route path="/detail/:id">
          <Detail />
        </Route>
        <Route path="/">
          <Home />
        </Route>
      </Switch>
      </Router>

  );
}

export default App;


问:
Terraform nested loop conditionnal
I have written code that works well in order to create Azure Firewall Network Rules via Terraform. Weeks later i'm asked to add an attribute "expiration" in order to enable users to create temporary network rules.

If the expiration field is 0, means the rule is permanent, if not, i compare the date with the sysdate.

I have tried nearly every possible "for_each" with "for" and "if" combinations, but nothing seems to work. That "expiration" attribute seems inaccessible from outside the loop.

Here are the files of my code:

main.tf

module.tf (edits must be done here, in the dynamic "rule" bloçk of the network_rule_collection block, all other files have been simplified and are here only for better understanding of the code logic)

variables.tf

net_rules.yaml

fw_collections.yaml

Main.tf

```<code>locals {
  collections = yamldecode(file("../environments/fw_collections.yaml"))
  netrules   = yamldecode(file("../environments/net_rules.yaml"))
  apprules   = yamldecode(file("../environments/app_rules.yaml"))

}

module "tdf_az_firewall_policy_rule_collection_group" {
  source       = "../../modules/tdf_az_firewall_policy_rule_collection_group"
  fw_policy_id = module.tdf_az_firewall_policy.firewall_policy_id
  fw_c         = local.collections.FW_Collections
  fw_nr        = local.netrules.FW_NET_Rules
  fw_ar        = local.apprules.FW_APP_Rules
  rgname       = data.azurerm_resource_group.ipgrg.name
  sub          = element(split("/", module.tdf_az_virtual_hub_module.virtual_hub_id), 2)
  depends_on   = [module.tdf_az_firewall_policy, module.tdf_az_firewall]
}

</code>```

Module.tf

```<code>resource "azurerm_firewall_policy_rule_collection_group" "fw-prcg" {
  for_each           = var.fw_c
  name               = each.key
  firewall_policy_id = var.fw_policy_id
  priority           = each.value[0]

  dynamic "network_rule_collection" {
    for_each = { for nr, name in var.fw_nr : nr => name if nr == each.key }
    content {
      name     = each.key
      priority = each.value[0]
      action   = each.value[1]
      dynamic "rule" {
      for_each = { for x, y in var.fw_nr[each.key] : x => y.expiration if timecmp(y.expiration, timestamp()) == 1 }
        content {
          name                  = rule.value.name
          protocols             = rule.value.protocols
          source_ip_groups      = [for s in rule.value.source_ip_groups : join("/", ["/subscriptions", var.sub, "resourceGroups", var.rgname, "providers/Microsoft.Network/ipGroups", s])]
          destination_ip_groups = [for d in rule.value.destination_ip_groups : join("/", ["/subscriptions", var.sub, "resourceGroups", var.rgname, "providers/Microsoft.Network/ipGroups", d])]

          destination_ports = rule.value.destination_ports
        }
      }
    }
    }

  dynamic "application_rule_collection" {
    for_each = { for ar, name in var.fw_ar : ar => name if ar == each.key }
    content {
      name     = each.key
      priority = each.value[0]
      action   = each.value[1]
      dynamic "rule" {
        for_each = var.fw_ar[each.key]
        content {
          name = rule.value.name
          dynamic "protocols" {
            for_each = rule.value.protocols
            content {
              type = protocols.value.type
              port = protocols.value.port
            }
          }
          source_ip_groups      = [for s in rule.value.source_ip_groups : join("/", ["/subscriptions", var.sub, "resourceGroups", var.rgname, "providers/Microsoft.Network/ipGroups", s])]
          destination_fqdns     = rule.value.destination_fqdns
          destination_urls      = rule.value.destination_urls
          terminate_tls         = rule.value.terminate_tls
          web_categories        = rule.value.web_categories
          destination_fqdn_tags = rule.value.destination_fqdn_tags
        }
      }
    }
  }}
</code>```

variables.tf

```<code>variable "fw_policy_id" {}
variable "fw_c" {}
variable "fw_nr" {}
variable "fw_ar" {}
variable "sub" {}
variable "rgname" {}

</code>```

netrules.yaml

```<code>FW_NET_Rules:
  Blacklist-Net:
    - name: blacklisted_inbound_ips_rule_inbound
      source_ip_groups: ["blacklisted_inbound_ips"]
      destination_ip_groups: ["Any-ip"]
      estination_ports: ["*"]
      protocols: ["Any"]
      expiration: 0
    - name: k8saas_backlisted_idps_rule_inbound
      source_ip_groups: ["k8saas_blacklist_ip_inbound"]
      destination_ip_groups: ["Any-ip"]
      destination_ports: ["*"]
      protocols: ["Any"]
      expiration: 0
  Mobility:
    - name: Mobility-LAN-VNET
      source_ip_groups: ["Mobility-LAN"]
      destination_ip_groups: ["Mobility-VNET"]
      destination_ports: ["443"]
      protocols: ["TCP"]
      expiration: "2022-12-12T00:00:00Z"
    - name: Mobility-LAN-To-Data
      source_ip_groups: ["Mobility-LAN"]
      destination_ip_groups: ["Data-VNET"]
      destination_ports: ["443"]
      protocols: ["TCP"]
      expiration: "2022-12-12T00:00:00Z"
</code>```

fw_collections.yaml

```<code>FW_Collections:
  Blacklist-Net: [100, "Deny"]
  Mobility: [105, "Allow"]
</code>```

Title: Terraform nested loop conditionnal

Body:
I have written code that works well in order to create Azure Firewall Network Rules via Terraform. Weeks later i'm asked to add an attribute "expiration" in order to enable users to create temporary network rules.

If the expiration field is 0, means the rule is permanent, if not, i compare the date with the sysdate.

I have tried nearly every possible "for_each" with "for" and "if" combinations, but nothing seems to work. That "expiration" attribute seems inaccessible from outside the loop.

Here are the files of my code:

main.tf

module.tf (edits must be done here, in the dynamic "rule" bloçk of the network_rule_collection block, all other files have been simplified and are here only for better understanding of the code logic)

variables.tf

net_rules.yaml

fw_collections.yaml

Main.tf

locals {
  collections = yamldecode(file("../environments/fw_collections.yaml"))
  netrules   = yamldecode(file("../environments/net_rules.yaml"))
  apprules   = yamldecode(file("../environments/app_rules.yaml"))

}

module "tdf_az_firewall_policy_rule_collection_group" {
  source       = "../../modules/tdf_az_firewall_policy_rule_collection_group"
  fw_policy_id = module.tdf_az_firewall_policy.firewall_policy_id
  fw_c         = local.collections.FW_Collections
  fw_nr        = local.netrules.FW_NET_Rules
  fw_ar        = local.apprules.FW_APP_Rules
  rgname       = data.azurerm_resource_group.ipgrg.name
  sub          = element(split("/", module.tdf_az_virtual_hub_module.virtual_hub_id), 2)
  depends_on   = [module.tdf_az_firewall_policy, module.tdf_az_firewall]
}

Module.tf

resource "azurerm_firewall_policy_rule_collection_group" "fw-prcg" {
  for_each           = var.fw_c
  name               = each.key
  firewall_policy_id = var.fw_policy_id
  priority           = each.value[0]

  dynamic "network_rule_collection" {
    for_each = { for nr, name in var.fw_nr : nr => name if nr == each.key }
    content {
      name     = each.key
      priority = each.value[0]
      action   = each.value[1]
      dynamic "rule" {
      for_each = { for x, y in var.fw_nr[each.key] : x => y.expiration if timecmp(y.expiration, timestamp()) == 1 }
        content {
          name                  = rule.value.name
          protocols             = rule.value.protocols
          source_ip_groups      = [for s in rule.value.source_ip_groups : join("/", ["/subscriptions", var.sub, "resourceGroups", var.rgname, "providers/Microsoft.Network/ipGroups", s])]
          destination_ip_groups = [for d in rule.value.destination_ip_groups : join("/", ["/subscriptions", var.sub, "resourceGroups", var.rgname, "providers/Microsoft.Network/ipGroups", d])]

          destination_ports = rule.value.destination_ports
        }
      }
    }
    }

  dynamic "application_rule_collection" {
    for_each = { for ar, name in var.fw_ar : ar => name if ar == each.key }
    content {
      name     = each.key
      priority = each.value[0]
      action   = each.value[1]
      dynamic "rule" {
        for_each = var.fw_ar[each.key]
        content {
          name = rule.value.name
          dynamic "protocols" {
            for_each = rule.value.protocols
            content {
              type = protocols.value.type
              port = protocols.value.port
            }
          }
          source_ip_groups      = [for s in rule.value.source_ip_groups : join("/", ["/subscriptions", var.sub, "resourceGroups", var.rgname, "providers/Microsoft.Network/ipGroups", s])]
          destination_fqdns     = rule.value.destination_fqdns
          destination_urls      = rule.value.destination_urls
          terminate_tls         = rule.value.terminate_tls
          web_categories        = rule.value.web_categories
          destination_fqdn_tags = rule.value.destination_fqdn_tags
        }
      }
    }
  }}

variables.tf

variable "fw_policy_id" {}
variable "fw_c" {}
variable "fw_nr" {}
variable "fw_ar" {}
variable "sub" {}
variable "rgname" {}

netrules.yaml

FW_NET_Rules:
  Blacklist-Net:
    - name: blacklisted_inbound_ips_rule_inbound
      source_ip_groups: ["blacklisted_inbound_ips"]
      destination_ip_groups: ["Any-ip"]
      estination_ports: ["*"]
      protocols: ["Any"]
      expiration: 0
    - name: k8saas_backlisted_idps_rule_inbound
      source_ip_groups: ["k8saas_blacklist_ip_inbound"]
      destination_ip_groups: ["Any-ip"]
      destination_ports: ["*"]
      protocols: ["Any"]
      expiration: 0
  Mobility:
    - name: Mobility-LAN-VNET
      source_ip_groups: ["Mobility-LAN"]
      destination_ip_groups: ["Mobility-VNET"]
      destination_ports: ["443"]
      protocols: ["TCP"]
      expiration: "2022-12-12T00:00:00Z"
    - name: Mobility-LAN-To-Data
      source_ip_groups: ["Mobility-LAN"]
      destination_ip_groups: ["Data-VNET"]
      destination_ports: ["443"]
      protocols: ["TCP"]
      expiration: "2022-12-12T00:00:00Z"

fw_collections.yaml

FW_Collections:
  Blacklist-Net: [100, "Deny"]
  Mobility: [105, "Allow"]


问:
Error Failed to install the app. Make sure you have the Android development environment set up :React-Native
I created new project with react-native but isn't working because my react-native can't running even though emulator is open .I looked stackOverflow for solutions then I try to fix the error but react native still can't running.

This is error:

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.

SDK location not found. Define a valid SDK location with an ANDROID_HOME environment variable or by setting the sdk.dir path in your project's local properties file at 'D:\ReactNative\Boniki\android\local.properties'.


问:
Spring Security securing absolute URL paths vs generic regex paths
In Spring Security I want to secure two endpoints behind RBAC

1 - /api/v1/user/bankDetails - only users with admin permissions should be able to call this endpoint

2 - /api/v1/user/** - all the other API endpoints (other than getInfo) can be accessed by any user with read permissions

How can I ensure that Spring adds RBAC for all /api/v1/user/** endpoints but for /api/v1/user/bankDetails, only admin are allowed?

Now when I add this in my WebFlux application like this -

http
.authorizeExchange()
.pathMatchers("/api/v1/user/**").hasAuthority("read")
.authorizeExchange()
.pathMatchers("/api/v1/user/bankDetails").hasAuthority("admin")
```

Spring security only considers the first one so bankDetails endpoint is also open to every user with read permissions. Is there a way to differentiate between absolute paths and regex paths such that regex paths have the expected secured behaviour as defined in pathMatchers but if the absolute path is defined, then its security check should precede the regex one?

Body:
In Spring Security I want to secure two endpoints behind RBAC

1 - /api/v1/user/bankDetails - only users with admin permissions should be able to call this endpoint

2 - /api/v1/user/** - all the other API endpoints (other than getInfo) can be accessed by any user with read permissions

How can I ensure that Spring adds RBAC for all /api/v1/user/** endpoints but for /api/v1/user/bankDetails, only admin are allowed?

Now when I add this in my WebFlux application like this -

http
.authorizeExchange()
.pathMatchers("/api/v1/user/**").hasAuthority("read")
.authorizeExchange()
.pathMatchers("/api/v1/user/bankDetails").hasAuthority("admin")

Spring security only considers the first one so bankDetails endpoint is also open to every user with read permissions. Is there a way to differentiate between absolute paths and regex paths such that regex paths have the expected secured behaviour as defined in pathMatchers but if the absolute path is defined, then its security check should precede the regex one?


问:
How to overlap the bottom container widget to the clip path container?
This is my code,

```<code>return MaterialApp(

      debugShowCheckedModeBanner: false,
      title: 'Example',
      home: Scaffold(

        backgroundColor: Colors.green.shade200,

        body: Column(

          children: [

            ClipPath(
              clipBehavior: Clip.antiAlias,
              clipper: MyCustomClipper(),
              child: Container(
                width: 600,
                height: 300,
                color: Colors.green.shade300,
                child:  Row(

                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,

                  children: const [

                    Icon(Icons.shopping_cart_outlined, color: Colors.black87, size: 30,),
                    Text('Example', style: TextStyle(fontSize: 22, color: Colors.black87,)),

                  ],
                ),
                ),
            ),

            Container(

              height: 360,
              width: 300,
              color: Colors.white,

            ),

          ],

        ),

      ),
    );
  }
}
</code>```

this is my clipper class, its just a basic design that we see on every other flutter app,

```<code>
// clipper class

class MyCustomClipper extends CustomClipper <Path> {

  @override
  Path getClip(Size size) {
    Path path = Path();
    path.lineTo(0, size.height / 2 );
    path.quadraticBezierTo(size.width / 2 , size.height, size.width, size.height / 2 );
    path.lineTo( size.width , 0);

    return path ;

  }

   @override
   bool shouldReclip(covariant CustomClipper <Path> oldClipper ) {
   return true ;

   }

}
</code>```

Current Situation

i really don't know how we can achieve such things

clip-path does not have any padding and margin by default

tried stack but no luck ?

used alignment property no luck

i read on other thread that clipping should be done separately not on the whole widget what does that mean ?

Body:
This is my code,

return MaterialApp(

      debugShowCheckedModeBanner: false,
      title: 'Example',
      home: Scaffold(

        backgroundColor: Colors.green.shade200,

        body: Column(

          children: [

            ClipPath(
              clipBehavior: Clip.antiAlias,
              clipper: MyCustomClipper(),
              child: Container(
                width: 600,
                height: 300,
                color: Colors.green.shade300,
                child:  Row(

                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,

                  children: const [

                    Icon(Icons.shopping_cart_outlined, color: Colors.black87, size: 30,),
                    Text('Example', style: TextStyle(fontSize: 22, color: Colors.black87,)),

                  ],
                ),
                ),
            ),

            Container(

              height: 360,
              width: 300,
              color: Colors.white,

            ),

          ],

        ),

      ),
    );
  }
}

this is my clipper class, its just a basic design that we see on every other flutter app,

// clipper class

class MyCustomClipper extends CustomClipper <Path> {

  @override
  Path getClip(Size size) {
    Path path = Path();
    path.lineTo(0, size.height / 2 );
    path.quadraticBezierTo(size.width / 2 , size.height, size.width, size.height / 2 );
    path.lineTo( size.width , 0);

    return path ;

  }

   @override
   bool shouldReclip(covariant CustomClipper <Path> oldClipper ) {
   return true ;

   }

}

Current Situation

i really don't know how we can achieve such things

clip-path does not have any padding and margin by default

tried stack but no luck ?

used alignment property no luck

i read on other thread that clipping should be done separately not on the whole widget what does that mean ?