问:
How can c# exception handling be localised without excessive nesting?
I'm learning c# and struggling to write good error handling code. For example, when opening and reading a file, it seems difficult to do error handling which is localised to where the error occurs. Take the following (much simplified) example:

```<code>        private static void ReadFile(string path) {
            try {
                using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                using var sr = new StreamReader(fs, Encoding.ASCII);

                var line = string.Empty;
                while ((line = sr.ReadLine()) != null) {
                    // Actions performed on each line here
                    Console.WriteLine(line);
                }
            }
            catch (IOException) {
                Console.Error.WriteLine("Exception");
                return;
            }
        }
</code>```

In the code above, the catch statement will catch any IOException raised whilst opening or reading the file. In a real world application there could also be other I/O operations within the main loop which could raise the same exception.

However, I would like to handle errors raised when opening the file differently from errors whilst reading the file so I would like different error handling code for each I/O operation.

How can I narrow down the scope of the try/catch so that it just catches exceptions during file opening? If I put the using statements in their own try/catch block like this:

```<code>try {
    using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
    using var sr = new StreamReader(fs, Encoding.ASCII);
catch (IOException) {
    // etc.
</code>```

it doesn't work because they go out of scope at the end of the block.

Body:
I'm learning c# and struggling to write good error handling code. For example, when opening and reading a file, it seems difficult to do error handling which is localised to where the error occurs. Take the following (much simplified) example:

        private static void ReadFile(string path) {
            try {
                using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                using var sr = new StreamReader(fs, Encoding.ASCII);

                var line = string.Empty;
                while ((line = sr.ReadLine()) != null) {
                    // Actions performed on each line here
                    Console.WriteLine(line);
                }
            }
            catch (IOException) {
                Console.Error.WriteLine("Exception");
                return;
            }
        }

In the code above, the catch statement will catch any IOException raised whilst opening or reading the file. In a real world application there could also be other I/O operations within the main loop which could raise the same exception.

However, I would like to handle errors raised when opening the file differently from errors whilst reading the file so I would like different error handling code for each I/O operation.

How can I narrow down the scope of the try/catch so that it just catches exceptions during file opening? If I put the using statements in their own try/catch block like this:

try {
    using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
    using var sr = new StreamReader(fs, Encoding.ASCII);
catch (IOException) {
    // etc.

it doesn't work because they go out of scope at the end of the block.


来源: stackexchange

问:
In scala cats 2.9.x, is it possible to flatMap a Set?
When I try to rewrite some of my libraries in scala cats, I found that not all operators are supported, e.g. it is very common to flatMap a Set in native Scala:

```<code>val v: Set[Int] = ???
v.flatMap(v => Set(v, v*2))
</code>```

But it is not possible using cats:

```<code>  def flatMap2[F[_]](vs: F[Int])(
      implicit
      isFlatMappable: FlatMap[F],
      canConvert: Factory[Int, F[Int]]
  ): F[Int] = {
    isFlatMappable.flatMap(vs)(v => canConvert.fromSpecific(Set(v, v * 2)))
  }

  flatMap2(Set(1, 2, 3))

// yield error: [Error] /xxx:yyy/zzz : could not find implicit value for parameter isFlatMappable: cats.FlatMap[scala.collection.immutable.Set]
</code>```

Why is it not working? What should be done to fix it?

ContentLicense: CC BY-SA 4.0

Body:
When I try to rewrite some of my libraries in scala cats, I found that not all operators are supported, e.g. it is very common to flatMap a Set in native Scala:

val v: Set[Int] = ???
v.flatMap(v => Set(v, v*2))

But it is not possible using cats:

  def flatMap2[F[_]](vs: F[Int])(
      implicit
      isFlatMappable: FlatMap[F],
      canConvert: Factory[Int, F[Int]]
  ): F[Int] = {
    isFlatMappable.flatMap(vs)(v => canConvert.fromSpecific(Set(v, v * 2)))
  }

  flatMap2(Set(1, 2, 3))

// yield error: [Error] /xxx:yyy/zzz : could not find implicit value for parameter isFlatMappable: cats.FlatMap[scala.collection.immutable.Set]

Why is it not working? What should be done to fix it?


问:
Cast to string failed when trying to upload image using base64
I'm trying to upload an image using Filebase64 but I get this error whenever I hit Submit form

I don't know what I'm missing, why it fails to cast to string!

My Post Model

```<code>const PostSchema = new mongoose.Schema(
    {
    userId: {
        type: String,
        required: true,
    },
        title: {
            type: String,
            required: true,
        },
        photo: {
            type: String,
        },
    },
    { timestamps: true }
);
</code>```

The code I'm using:

```<code>export default function NewPost() {

const { user } = useContext(Context)
    const [title, setTitle] = useState("");
    const [photo, setPhoto] = useState("");
    const [baseImage, setBaseImage] = useState("");

      const handleSubmit = async (e) => {
        e.preventDefault();
        const newPost = {
            userId: user._id,
            username: user.username,
            title,
            photo,
        }
        try {
            const res = await axios.post("/posts/", newPost);
            window.location.replace("/post/" + res.data._id);
            console.log('Saved Successfully');

        } catch (err) {
          console.log(err);

        }
    }

    const uploadImage = async (e) => {
        const file = e.target.files[0];
        const base64 = await convertBase64(file);
        setBaseImage(base64);
        console.log(base64);
        setPhoto({ photo: base64 });
      };

      const convertBase64 = (file) => {
        return new Promise((resolve, reject) => {
          const fileReader = new FileReader();
          fileReader.readAsDataURL(file);
          fileReader.onload = () => {
            resolve(fileReader.result);
          };
          fileReader.onerror = (error) => {
            reject(error);
          };
        });
      };

return (
              <input
              type="file"
              id="file"
              accept="image/*"
              onChange={(e) => { uploadImage(e); }} />
)

}
</code>```

Here I tried setPhoto({ photo: baseImage }); but no luck.
When I condole log photo I get the data, but I don't why it's not sending to the server.

Also My API console showing this error:
throw new TypeError(Invalid schema configuration: \${name}` is not ` +
^

TypeError: Invalid schema configuration: True is not a valid type at path userId.required. See https://bit.ly/ mongoose-schematypes for a list of valid schema types.

Body:
I'm trying to upload an image using Filebase64 but I get this error whenever I hit Submit form

I don't know what I'm missing, why it fails to cast to string!

My Post Model

const PostSchema = new mongoose.Schema(
    {
    userId: {
        type: String,
        required: true,
    },
        title: {
            type: String,
            required: true,
        },
        photo: {
            type: String,
        },
    },
    { timestamps: true }
);

The code I'm using:

export default function NewPost() {

const { user } = useContext(Context)
    const [title, setTitle] = useState("");
    const [photo, setPhoto] = useState("");
    const [baseImage, setBaseImage] = useState("");

      const handleSubmit = async (e) => {
        e.preventDefault();
        const newPost = {
            userId: user._id,
            username: user.username,
            title,
            photo,
        }
        try {
            const res = await axios.post("/posts/", newPost);
            window.location.replace("/post/" + res.data._id);
            console.log('Saved Successfully');

        } catch (err) {
          console.log(err);

        }
    }

    const uploadImage = async (e) => {
        const file = e.target.files[0];
        const base64 = await convertBase64(file);
        setBaseImage(base64);
        console.log(base64);
        setPhoto({ photo: base64 });
      };

      const convertBase64 = (file) => {
        return new Promise((resolve, reject) => {
          const fileReader = new FileReader();
          fileReader.readAsDataURL(file);
          fileReader.onload = () => {
            resolve(fileReader.result);
          };
          fileReader.onerror = (error) => {
            reject(error);
          };
        });
      };

return (
              <input
              type="file"
              id="file"
              accept="image/*"
              onChange={(e) => { uploadImage(e); }} />
)

}

Here I tried setPhoto({ photo: baseImage }); but no luck.
When I condole log photo I get the data, but I don't why it's not sending to the server.

Also My API console showing this error:
throw new TypeError(Invalid schema configuration: \${name}` is not ` +
^

TypeError: Invalid schema configuration: True is not a valid type at path userId.required. See https://bit.ly/ mongoose-schematypes for a list of valid schema types.


问:
When scroll a bar the content from all elements that has a scroll bar should be moved
I have implemented <overlay-scrollbars> in my project, and now have a problem and can't solve it; So I have few elements in my page that contains this component : <overlay-scrollbars>;

```<code><overlay-scrollbars
    :ref="`datesHeader`+room.id"
    :options="datesScrollOptions"
    :data-id="room.id"
>
  <div class="dates d-flex">
  ....
  </div>
</overlay-scrollbars>
</code>```

And the function to scroll left or right :

```<code>updateScrollButtons() {
    const activeElement = document.querySelector('.os-host-scrolling');
    if (activeElement) {
      this.currentRoom = activeElement.getAttribute('data-id');
    }
    if (this.$refs[`datesHeader${this.currentRoom}`]) {
      const inst = this.$refs[`datesHeader${this.currentRoom}`].osInstance();
      const scroll = inst.scroll();
      this.scrollLeftEnabled = scroll.position.x > 0;
      this.scrollRightEnabled = scroll.position.x < scroll.max.x;
      ([this.$refs.roomRows] || []).forEach((r) => {
        (window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame)(
          () => {
            // eslint-disable-next-line no-param-reassign
            r.scrollLeft = scroll.position.x;
          },
        );
      });
    }
  },
</code>```

The scope is : when scroll left or right from one element, automatically all elements that has this scrollbar should be moved identically

I tried to do a foreach between all elements : ``datesHeader+room.id but received an undefined osInstance(); I imagine that should be possible to added here the element from others rooms : ([this.$refs.roomRows] || []) but don't know if make sense

Have you an idea about this behaviour ?

Body:
I have implemented <overlay-scrollbars> in my project, and now have a problem and can't solve it; So I have few elements in my page that contains this component : <overlay-scrollbars>;

<overlay-scrollbars
    :ref="`datesHeader`+room.id"
    :options="datesScrollOptions"
    :data-id="room.id"
>

  ....

</overlay-scrollbars>

And the function to scroll left or right :

updateScrollButtons() {
    const activeElement = document.querySelector('.os-host-scrolling');
    if (activeElement) {
      this.currentRoom = activeElement.getAttribute('data-id');
    }
    if (this.$refs[`datesHeader${this.currentRoom}`]) {
      const inst = this.$refs[`datesHeader${this.currentRoom}`].osInstance();
      const scroll = inst.scroll();
      this.scrollLeftEnabled = scroll.position.x > 0;
      this.scrollRightEnabled = scroll.position.x < scroll.max.x;
      ([this.$refs.roomRows] || []).forEach((r) => {
        (window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame)(
          () => {
            // eslint-disable-next-line no-param-reassign
            r.scrollLeft = scroll.position.x;
          },
        );
      });
    }
  },

The scope is : when scroll left or right from one element, automatically all elements that has this scrollbar should be moved identically

I tried to do a foreach between all elements : ``datesHeader+room.id but received an undefined osInstance(); I imagine that should be possible to added here the element from others rooms : ([this.$refs.roomRows] || []) but don't know if make sense

Have you an idea about this behaviour ?


问:
SOLVED: How to configure Apache2 with Reverse Proxy. Map an internal website to a folder of another (public) website on the same server
I have build a SPA and deployed it to my server. It is running on http://my-server:3000.
I then installed Apache2 and created a static page. This website is on the same server http://my-server:80 and is open to the Internet via a My-domain.

What I'm trying to accomplish now is to add a link on this static page (http://my-server/foo) which is redirected to http://my-server:3000 in such a way that the here deployed SPA can be run from this sub-folder.

I configured a new Virtual host in Apache2 with the following configuration:

```<code><VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName My-domain

        ProxyRequests Off
        ProxyHTMLEnable On
        ProxyHTMLExtended Off
        ProxyPreserveHost On

        ProxyPass /foo/ http://my-server:3000/

        <Location /foo/>
                ProxyHTMLURLMap / /foo/
                ProxyPassReverse http://my-server:3000/
                SetOutputFilter INFLATE;DEFLATE
        </Location>
        <Proxy *>
                Order allow,deny
                Allow from all
        </Proxy>

        LogLevel info

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code>```

Although the SPA is accessed and all the files are loaded the application will not start due to the error No match for URL in routes. I think it is due to the fact that the SPA is build to run in the root of a website and I'm now trying to run it in a sub-folder.

Does anyone know if this is possible? A solution would be appreciated much :-)

I found a solution which works for me :-)
Since I can use any prefix before My-domain like foo.My-domain, just found out recently, I changed  the configuration for my Virtual host to this:

```<code><VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName foo.My-domain

        ProxyRequests Off
        ProxyHTMLEnable On
        ProxyHTMLExtended Off
        ProxyPreserveHost On

        ProxyPass / http://my-server:3000/

        <Location />
                ProxyPassReverse http://my-server:3000/
                SetOutputFilter INFLATE;DEFLATE
        </Location>
        <Proxy *>
                Order allow,deny
                Allow from all
        </Proxy>

        LogLevel info

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code>```

And because my SPA now is allowed to run in the root of a website it is working. :-)

Body:
I have build a SPA and deployed it to my server. It is running on http://my-server:3000.
I then installed Apache2 and created a static page. This website is on the same server http://my-server:80 and is open to the Internet via a My-domain.

What I'm trying to accomplish now is to add a link on this static page (http://my-server/foo) which is redirected to http://my-server:3000 in such a way that the here deployed SPA can be run from this sub-folder.

I configured a new Virtual host in Apache2 with the following configuration:

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName My-domain

        ProxyRequests Off
        ProxyHTMLEnable On
        ProxyHTMLExtended Off
        ProxyPreserveHost On

        ProxyPass /foo/ http://my-server:3000/

        <Location /foo/>
                ProxyHTMLURLMap / /foo/
                ProxyPassReverse http://my-server:3000/
                SetOutputFilter INFLATE;DEFLATE
        </Location>
        <Proxy *>
                Order allow,deny
                Allow from all
        </Proxy>

        LogLevel info

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Although the SPA is accessed and all the files are loaded the application will not start due to the error No match for URL in routes. I think it is due to the fact that the SPA is build to run in the root of a website and I'm now trying to run it in a sub-folder.

Does anyone know if this is possible? A solution would be appreciated much :-)

I found a solution which works for me :-)
Since I can use any prefix before My-domain like foo.My-domain, just found out recently, I changed  the configuration for my Virtual host to this:

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName foo.My-domain

        ProxyRequests Off
        ProxyHTMLEnable On
        ProxyHTMLExtended Off
        ProxyPreserveHost On

        ProxyPass / http://my-server:3000/

        <Location />
                ProxyPassReverse http://my-server:3000/
                SetOutputFilter INFLATE;DEFLATE
        </Location>
        <Proxy *>
                Order allow,deny
                Allow from all
        </Proxy>

        LogLevel info

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

And because my SPA now is allowed to run in the root of a website it is working. :-)


问:
Android Text selection handles
I've been working on an app Then I got a bug showing the root layout background when editing the text in EditText field

I'll leave a screenshot of the problem here

res/layout/main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
style="@style/AppTheme">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"        android:background="@color/B1"
android:layout_margin="20dp"        android:padding="20dp">

<EditText
android:layout_width="250dp"
android:hint="Just an EditText"
android:ems="10"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:typeface="serif"
android:textColor="@color/text"     android:textColorHint="@color/text"     android:textColorHighlight="@color/B2"/>

<ImageView      android:id="@+id/smaliCopy"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:src="@drawable/edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"android:maxWidth="30dp"
android:maxHeight="30dp"
android:background="@color/B1"/>

</RelativeLayout>
</LinearLayout>
```
<p>AppTheme style:</p>
<pre class="lang-xml prettyprint-override"><code><style name="AppTheme" parent="@android:style/Theme.Material">
</code>```

Guide me pls.

Title: Android Text selection handles

Body:
I've been working on an app Then I got a bug showing the root layout background when editing the text in EditText field

I'll leave a screenshot of the problem here

res/layout/main.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
style="@style/AppTheme">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"        android:background="@color/B1"
android:layout_margin="20dp"        android:padding="20dp">

<EditText
android:layout_width="250dp"
android:hint="Just an EditText"
android:ems="10"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:typeface="serif"
android:textColor="@color/text"     android:textColorHint="@color/text"     android:textColorHighlight="@color/B2"/>

<ImageView      android:id="@+id/smaliCopy"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:src="@drawable/edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"android:maxWidth="30dp"
android:maxHeight="30dp"
android:background="@color/B1"/>

</RelativeLayout>
</LinearLayout>

AppTheme style:


问:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
Ive only started coding for 3 weeks now and I have encountered a problem that I do not know how to solve. I have typed the code below into GoogleColab and got the error in the title. The code is as follows:

I get this error:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'

Can anyone please explain what I am doing wrong and help me solve this issue as I have an assignment due in 3 days.

Thanks in advance.

```<code>end=datetime.datetime.today()
AAPLdata=DataReader('AAPL', 'yahoo', '2012-09-29', end)['Adj Close']
AAPLdataF=AAPLdata.resample('M').last()
AAPLdataF=AAPLdataF.to_frame()
AAPLdataF['Year']=AAPLdataF.DatetimeIndex.year
AAPLdataF['Month']=AAPLdataF.DatetimeIndex.month
AAPLdataF.rename(columns={'Adj Close':'AAPL'},inplace=True)
</code>```

I get this error:

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'

Body:
Ive only started coding for 3 weeks now and I have encountered a problem that I do not know how to solve. I have typed the code below into GoogleColab and got the error in the title. The code is as follows:

I get this error:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'

Can anyone please explain what I am doing wrong and help me solve this issue as I have an assignment due in 3 days.

Thanks in advance.

end=datetime.datetime.today()
AAPLdata=DataReader('AAPL', 'yahoo', '2012-09-29', end)['Adj Close']
AAPLdataF=AAPLdata.resample('M').last()
AAPLdataF=AAPLdataF.to_frame()
AAPLdataF['Year']=AAPLdataF.DatetimeIndex.year
AAPLdataF['Month']=AAPLdataF.DatetimeIndex.month
AAPLdataF.rename(columns={'Adj Close':'AAPL'},inplace=True)

I get this error:

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'


问:
reverse cwt image to a wav file with pywt
I have a working function that takes in a Wav file and generates a CWT image of the wav.
This is what my first function does.
In the second function i try to do the reverse, but i have problems understanding the pywt documentation. The target i try to achive is get back the same wave file (if possible same checksum). But somehow no matter what i deliver to idwt as input i cant get any wav file out.

Either it says the wavelet class is for discrete wavelets and cmor is a continuouts wavelet (i dont get what that means) or it complains that wavelet being able to convert to a float.

```<code>import wave
import pywt
import numpy as np
from PIL import Image

def create_cwt_image(wave_file, image_file):
    with wave.open(wave_file, 'r') as wav:
        # Read wave file
        data = wav.readframes(wav.getnframes())
    data = np.frombuffer(data, dtype=np.int16)

    # Compute wavelet scalogram
    wavelet = 'cmor1-1.5'
    scales = np.arange(1, 129)
    cwtmatr, freqs = pywt.cwt(data, scales, wavelet, 1)
    cwtmatr = abs(cwtmatr)

    # Normalize wavelet scalogram to [0, 255] range
    cwtmatr = cwtmatr / cwtmatr.max() * 255
    cwtmatr = cwtmatr.astype(np.uint8)

    # Save wavelet scalogram as image
    Image.fromarray(cwtmatr, 'L').save(image_file)

def reverse_cwt_image(image_file, wave_file):
  # Read CWT image and convert to numpy array
  image = Image.open(image_file)
  image_data = np.array(image)

  # Convert image data to float32 and normalize to [0, 1] range
  image_data = image_data.astype(np.float32) / 255
  image_data = abs(image_data)

  # Compute inverse CWT
  wavelet = 'cmor'
  w = pywt.Wavelet(wavelet)
  cA, cD = pywt.dwt(image_data, wavelet=w, mode='constant')
  data = pywt.idwt(cA, cD, None, wavelet, 'symetric')
  data = np.array(data, dtype=np.int16)

  # Save data as wav file
  with wave.open(wave_file, 'w') as wav:
    wav.setnchannels(1)
    wav.setsampwidth(2)
    wav.setframerate(44100)
    wav.writeframes(data)

if __name__ == "__main__":
    print("now converting wav to spectrogram")
    create_cwt_image("1.wav", "spectrogram.png")
    print("now converting spectrogram to wav")
    reverse_cwt_image("spectrogram.png", "2.wav")
</code>```

This is the code i have so far, but no matter how i try i can not convert the huge image back to a wav and would appreciate someone helping me.

Body:
I have a working function that takes in a Wav file and generates a CWT image of the wav.
This is what my first function does.
In the second function i try to do the reverse, but i have problems understanding the pywt documentation. The target i try to achive is get back the same wave file (if possible same checksum). But somehow no matter what i deliver to idwt as input i cant get any wav file out.

Either it says the wavelet class is for discrete wavelets and cmor is a continuouts wavelet (i dont get what that means) or it complains that wavelet being able to convert to a float.

import wave
import pywt
import numpy as np
from PIL import Image

def create_cwt_image(wave_file, image_file):
    with wave.open(wave_file, 'r') as wav:
        # Read wave file
        data = wav.readframes(wav.getnframes())
    data = np.frombuffer(data, dtype=np.int16)

    # Compute wavelet scalogram
    wavelet = 'cmor1-1.5'
    scales = np.arange(1, 129)
    cwtmatr, freqs = pywt.cwt(data, scales, wavelet, 1)
    cwtmatr = abs(cwtmatr)

    # Normalize wavelet scalogram to [0, 255] range
    cwtmatr = cwtmatr / cwtmatr.max() * 255
    cwtmatr = cwtmatr.astype(np.uint8)

    # Save wavelet scalogram as image
    Image.fromarray(cwtmatr, 'L').save(image_file)

def reverse_cwt_image(image_file, wave_file):
  # Read CWT image and convert to numpy array
  image = Image.open(image_file)
  image_data = np.array(image)

  # Convert image data to float32 and normalize to [0, 1] range
  image_data = image_data.astype(np.float32) / 255
  image_data = abs(image_data)

  # Compute inverse CWT
  wavelet = 'cmor'
  w = pywt.Wavelet(wavelet)
  cA, cD = pywt.dwt(image_data, wavelet=w, mode='constant')
  data = pywt.idwt(cA, cD, None, wavelet, 'symetric')
  data = np.array(data, dtype=np.int16)

  # Save data as wav file
  with wave.open(wave_file, 'w') as wav:
    wav.setnchannels(1)
    wav.setsampwidth(2)
    wav.setframerate(44100)
    wav.writeframes(data)

if __name__ == "__main__":
    print("now converting wav to spectrogram")
    create_cwt_image("1.wav", "spectrogram.png")
    print("now converting spectrogram to wav")
    reverse_cwt_image("spectrogram.png", "2.wav")

This is the code i have so far, but no matter how i try i can not convert the huge image back to a wav and would appreciate someone helping me.


问:
How to set seed in python
I want to draw the same exact samples from the data, two times, in order to run a different analysis each time. To do so I did

```<code>random.seed(10)
data.sample(n = 1000)
</code>```

But this is not working, I get different samples each time. I searched for a built-in parameter in the sample() function but I found non. How do I set seed?

Thanks!

Title: How to set seed in python

Body:
I want to draw the same exact samples from the data, two times, in order to run a different analysis each time. To do so I did

random.seed(10)
data.sample(n = 1000)

But this is not working, I get different samples each time. I searched for a built-in parameter in the sample() function but I found non. How do I set seed?

Thanks!


问:
error in finding Spotify user ID with python
hey im trying to fetch my spotify user ID in order to create a playlist on my profile

im able to find the songs im interested in using the spotify API but im stuck after that

this is my code to find user ID
`

```<code># Use the Spotify API to get the authenticated user's ID
headers = {
    'Authorization': 'Bearer ' + access_token
}

response = requests.get('https://api.spotify.com/v1/me', headers=headers)

if response.status_code == 200:
    # Success!
    user_id = response.json()['id']
else:
    # Error occurred
    print('Error:', response.status_code)

</code>```

it keeps giving me a 401 error

after that im trying to create a playlist and add songs to that playlist

`

```<code># Use the Spotify API to create a new playlist
headers = {
    'Authorization': 'Bearer ' + access_token,
    'Content-Type': 'application/json'
}

data = {
    'name': 'Sample Playlist',
    'public': True
}

response = requests.post('https://api.spotify.com/v1/me/playlists', headers=headers, json=data)

if response.status_code == 201:
    # Success!
    playlist_id = response.json()['id']
else:
    # Error occurred
    print('Error:', response.status_code)
</code>```

``

please help

i tries using the endpoints in the docs but no solution

Body:
hey im trying to fetch my spotify user ID in order to create a playlist on my profile

im able to find the songs im interested in using the spotify API but im stuck after that

this is my code to find user ID
`

# Use the Spotify API to get the authenticated user's ID
headers = {
    'Authorization': 'Bearer ' + access_token
}

response = requests.get('https://api.spotify.com/v1/me', headers=headers)

if response.status_code == 200:
    # Success!
    user_id = response.json()['id']
else:
    # Error occurred
    print('Error:', response.status_code)

it keeps giving me a 401 error

after that im trying to create a playlist and add songs to that playlist

`

# Use the Spotify API to create a new playlist
headers = {
    'Authorization': 'Bearer ' + access_token,
    'Content-Type': 'application/json'
}

data = {
    'name': 'Sample Playlist',
    'public': True
}

response = requests.post('https://api.spotify.com/v1/me/playlists', headers=headers, json=data)

if response.status_code == 201:
    # Success!
    playlist_id = response.json()['id']
else:
    # Error occurred
    print('Error:', response.status_code)

``

please help

i tries using the endpoints in the docs but no solution


问:
Rewriting stored procedure as a transaction
I have a stored procedure in the form of:

```<code>CREATE FUNCTION schema.myfunction(id uuid)
RETURNS TABLE (report jsonb) AS $$
  BEGIN
  RETURN QUERY WITH rows AS (
    SELECT
      jsonb_build_object(
      'rowNumber', ROW_NUMBER(),
      'id', t.id
    ) AS row
  FROM schema.table t
  WHERE t.id = id
  )
  SELECT
    COALESCE(jsonb_agg(r.row), '[]') AS report
  FROM rows r;
  END;
  $$ LANGUAGE plpgsql STRICT STABLE SECURITY DEFINER;

  GRANT EXECUTE ON FUNCTION schema.myfunction(
        uuid
  ) TO schema_user;
</code>```

How can I get the same result but running this function as a transaction? Without creating the function itself. Something in the form of:

```<code>db.transaction(async (trx) => {
      const {
        rows: [result],
      } = await trx.raw(
        '<supposed code here, maybe>;',
        [id]
      );

      res.status(200).json(result);
}
</code>```

Is it possible?

I tried with DO block but I can't return anything from it. Any guidance on the right direction would help tremendously.

Body:
I have a stored procedure in the form of:

CREATE FUNCTION schema.myfunction(id uuid)
RETURNS TABLE (report jsonb) AS $$
  BEGIN
  RETURN QUERY WITH rows AS (
    SELECT
      jsonb_build_object(
      'rowNumber', ROW_NUMBER(),
      'id', t.id
    ) AS row
  FROM schema.table t
  WHERE t.id = id
  )
  SELECT
    COALESCE(jsonb_agg(r.row), '[]') AS report
  FROM rows r;
  END;
  $$ LANGUAGE plpgsql STRICT STABLE SECURITY DEFINER;

  GRANT EXECUTE ON FUNCTION schema.myfunction(
        uuid
  ) TO schema_user;

How can I get the same result but running this function as a transaction? Without creating the function itself. Something in the form of:

db.transaction(async (trx) => {
      const {
        rows: [result],
      } = await trx.raw(
        '<supposed code here, maybe>;',
        [id]
      );

      res.status(200).json(result);
}

Is it possible?

I tried with DO block but I can't return anything from it. Any guidance on the right direction would help tremendously.


问:
Cannot Use/Add Material Design 1 in Android Studio
I cannot add material design api to my app. I have tried different versions but always get the below errors.

A problem occurred evaluating root project 'Test'.
Could not find method implementation() for arguments [com.google.android.material:material:1.4.0] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

OR

A problem occurred evaluating root project 'Project'.
Build was configured to prefer settings repositories over project repositories but repository 'Google' was added by build file 'build.gradle'

```<code>My gradlefile:

    // Top-level build file where you can add configuration options common to all sub-projects/modules.
    plugins {
        id 'com.android.application' version '7.3.1' apply false
        id 'com.android.library' version '7.3.1' apply false
    }

    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        implementation 'com.google.android.material:material:1.4.0'
    }
</code>```

I have tried sing the Shrine project from https://codelabs.developers.google.com/codelabs/mdc-101-java#1 but get the same error as above.

I am using Android 9(Physical Device) and the Android Studio(Dolphin).

I would really appreciate any help. I was not able to find a solution for my problem on previous questions as they we not recent.

Body:
I cannot add material design api to my app. I have tried different versions but always get the below errors.

A problem occurred evaluating root project 'Test'.
Could not find method implementation() for arguments [com.google.android.material:material:1.4.0] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

OR

A problem occurred evaluating root project 'Project'.
Build was configured to prefer settings repositories over project repositories but repository 'Google' was added by build file 'build.gradle'

My gradlefile:

    // Top-level build file where you can add configuration options common to all sub-projects/modules.
    plugins {
        id 'com.android.application' version '7.3.1' apply false
        id 'com.android.library' version '7.3.1' apply false
    }

    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        implementation 'com.google.android.material:material:1.4.0'
    }

I have tried sing the Shrine project from https://codelabs.developers.google.com/codelabs/mdc-101-java#1 but get the same error as above.

I am using Android 9(Physical Device) and the Android Studio(Dolphin).

I would really appreciate any help. I was not able to find a solution for my problem on previous questions as they we not recent.


问:
Error coming while running 0x-api locally
I am trying to run 0x-api, locally. I followed instructions (https://github.com/0xProject/0x-api#getting-started), however, while running yarn db:migrate, I am getting following error:

Error during migration run:

MissingDriverError: Wrong driver: "undefined" given. Supported drivers are: "cordova", "expo", "mariadb", "mongodb", "mssql", "mysql", "oracle", "postgres", "sqlite", "better-sqlite3", "sqljs", "react-native", "aurora-data-api", "aurora-data-api-pg".

Software info:

postgres@14

m1 mac

forked latest 0x-api code.

What I tried?

I thought there might be some installation issues with postgres so I have reinstalled postgres in my local machine (m1 mac). Tried to connect it with pgAdmin portal via localhost. and its working.

Checked 0x-api code for default driver setting, but no where it has been explicitly mentioned.

Check postgres server, but its running fine.

I even tried on AWS ubuntu server, but getting same error.

I am not sure if this anything related to postgres server.


问:
Firebase Auth not loading persisted user from local storage
I'm using Firebase Auth in a Vue app. I want signed-in users to be persisted through reloading and closing the browser, so I'm using the 'local' persistence setting, which saves logged-in user tokens into the browser's localStorage.

The docs state that Firebase will automatically detect this localStorage entry, and publish a change in auth state, which fires onAuthStateChange handlers.

However, in my app the user credential is not being retrieved after a refresh.

The token is stored properly and can be viewed in the dev tools, so the browserLocalPersistence is working.

When I reload the page, however, the onAuthStateChange hook fires only one time, printing that the current user is null.

Code

Firebase init

const app = initializeApp(firebaseConfig);
const auth = initializeAuth(app);
setPersistence(auth, browserLocalPersistence)
```
<h4>Pinia store w/ action to update state:</h4>
<pre class="lang-js prettyprint-override"><code>export const useAuthStore = defineStore({
    id: "auth",
    state: (): UserState => ({
        user: null,
    }),
    actions: {
        init() {
            return new Promise<User | null>((resolve, reject) => {
                onAuthStateChanged(
                    getAuth(firebaseApp),
                    async (user) => {
                        console.log(user);
                        this.user = user;
                        resolve(user);
                    },
                    reject
                );
            });
        },
    },
});
</code>```

Initializing onAuthStateChanged hook within Pinia store from setup function of top-level Vue component:

const authStore = useAuthStore();
authStore.init().then(console.log);
```

With this code, I'm getting null printed to the console. That's understandable upon immediate page load, before Firebase has verified the persisted authentication, but I would expect the callback to fire a second time with the correct credentials loaded.

Everything works properly after an initial sign in -- it's only after a refresh that the credentials are not loaded from local storage.

Any help is appreciated!

Body:
I'm using Firebase Auth in a Vue app. I want signed-in users to be persisted through reloading and closing the browser, so I'm using the 'local' persistence setting, which saves logged-in user tokens into the browser's localStorage.

The docs state that Firebase will automatically detect this localStorage entry, and publish a change in auth state, which fires onAuthStateChange handlers.

However, in my app the user credential is not being retrieved after a refresh.

The token is stored properly and can be viewed in the dev tools, so the browserLocalPersistence is working.

When I reload the page, however, the onAuthStateChange hook fires only one time, printing that the current user is null.

Code

Firebase init

const app = initializeApp(firebaseConfig);
const auth = initializeAuth(app);
setPersistence(auth, browserLocalPersistence)

Pinia store w/ action to update state:

export const useAuthStore = defineStore({
    id: "auth",
    state: (): UserState => ({
        user: null,
    }),
    actions: {
        init() {
            return new Promise<User | null>((resolve, reject) => {
                onAuthStateChanged(
                    getAuth(firebaseApp),
                    async (user) => {
                        console.log(user);
                        this.user = user;
                        resolve(user);
                    },
                    reject
                );
            });
        },
    },
});

Initializing onAuthStateChanged hook within Pinia store from setup function of top-level Vue component:

const authStore = useAuthStore();
authStore.init().then(console.log);

With this code, I'm getting null printed to the console. That's understandable upon immediate page load, before Firebase has verified the persisted authentication, but I would expect the callback to fire a second time with the correct credentials loaded.

Everything works properly after an initial sign in -- it's only after a refresh that the credentials are not loaded from local storage.

Any help is appreciated!


问:
How to resolve "unclassifable error statement" in Fortran
Please I need help with fixing the "unclassifiable statement error" I get when I try to call a function rtsafe, which finds the root of a nonlinear algebraic equation; using the Newton-Raphson and bisection method. The function takes in three inputs: x1 and x2, which are initial guesses in which the root lies between them, and xacc the third input is the tolerance used in the convergence test. When I compile and run the function alone, it doesn't give any error. However, when I  call the function in the program, it gives the  error:

```<code>   rtsafe(0.09,1.0,0.001)
      1
Error: Unclassifiable statement at (1)
</code>```

kindly find the code below. Please note that I have attached to the code the FUNCTION which returns the given function and it's derivative at value x:

```<code>      program rootfinding

      implicit none
      real(4) :: rtsafe

      rtsafe(0.09,1.0,0.001)

      end program

      function rtsafe(x1,x2,xacc)
      implicit none
      integer,parameter :: maxit = 100
      real(4) :: x1,x2, xacc,
      real(4) :: rtsafe
      integer :: j
      real(4) :: df, dx, dxold, fh, fl, temp, xh, xl, f
      real(8):: func
      real(4):: funcd

      fl =  func(x1)
      fh = func(x2)
      if ((fl > 0 .and. fh > 0) .or. (fl < 0 .and. fh < 0)) then
         print *, 'root must be bracketed'
         return
      end if

      if (fl == 0) then
        rtsafe = x1
        return
      else if (fh == 0) then
        rtsafe = x2
        return

c    orient the search so that f(x1) < 0

      else if (fl < 0) then
         xl = x1
         xh = x2
      else
         xh = x1
         xl = x2
      end if

c    initialize  the guess for root,
         rtsafe = 0.5 * (x1+x2)

c    the step size before last

         dxold = abs(x2 - x1)

c    and the last step
         dx = dxold

      df = funcd(rtsafe)
      f = func(rtsafe)

c    loop over allowed iterations

      do j = 1, maxit

c    bisect if newton is out of range or not decreasing fast enough
          if (((rtsafe - xh)*df - f)*((rtsafe - xl)*df - f) > 0 .or.    &
     &           abs(2*f) > abs (dxold*df)) then
              dxold = dx
              dx = 0.5*(xh - xl)
              rtsafe = xl  + dx
              if (xl == rtsafe) return
          else
              dxold = dx
              dx = f/df
              temp = rtsafe
              rtsafe = rtsafe - dx
              if (temp == rtsafe ) return
          end if

c     convergence criterion
         if (abs(dx) < xacc) return

         f = func(rtsafe)
         if (f < 0) then
              xl = rtsafe
         else
              xh = rtsafe
         end if

      end do
      print *, "rtsafe exceeding maximum iterations"
      return
      end function rtsafe

c     function for the function at value x
      function func(x)
      implicit none
      real(8):: func
      real(4) :: x
      func = x**2 -0.25
      end function

c     function for the derivative of the function at value x
      function funcd(x)
      implicit none
      real(4):: funcd
      real(4) :: x
      funcd= 2*x
      end function
</code>```

I tried to check if there was any improper use of the 'if ' statement in the code but couldn't find any.

Body:
Please I need help with fixing the "unclassifiable statement error" I get when I try to call a function rtsafe, which finds the root of a nonlinear algebraic equation; using the Newton-Raphson and bisection method. The function takes in three inputs: x1 and x2, which are initial guesses in which the root lies between them, and xacc the third input is the tolerance used in the convergence test. When I compile and run the function alone, it doesn't give any error. However, when I  call the function in the program, it gives the  error:

   rtsafe(0.09,1.0,0.001)
      1
Error: Unclassifiable statement at (1)

kindly find the code below. Please note that I have attached to the code the FUNCTION which returns the given function and it's derivative at value x:

      program rootfinding

      implicit none
      real(4) :: rtsafe

      rtsafe(0.09,1.0,0.001)

      end program

      function rtsafe(x1,x2,xacc)
      implicit none
      integer,parameter :: maxit = 100
      real(4) :: x1,x2, xacc,
      real(4) :: rtsafe
      integer :: j
      real(4) :: df, dx, dxold, fh, fl, temp, xh, xl, f
      real(8):: func
      real(4):: funcd

      fl =  func(x1)
      fh = func(x2)
      if ((fl > 0 .and. fh > 0) .or. (fl < 0 .and. fh < 0)) then
         print *, 'root must be bracketed'
         return
      end if

      if (fl == 0) then
        rtsafe = x1
        return
      else if (fh == 0) then
        rtsafe = x2
        return

c    orient the search so that f(x1) < 0

      else if (fl < 0) then
         xl = x1
         xh = x2
      else
         xh = x1
         xl = x2
      end if

c    initialize  the guess for root,
         rtsafe = 0.5 * (x1+x2)

c    the step size before last

         dxold = abs(x2 - x1)

c    and the last step
         dx = dxold

      df = funcd(rtsafe)
      f = func(rtsafe)

c    loop over allowed iterations

      do j = 1, maxit

c    bisect if newton is out of range or not decreasing fast enough
          if (((rtsafe - xh)*df - f)*((rtsafe - xl)*df - f) > 0 .or.    &
     &           abs(2*f) > abs (dxold*df)) then
              dxold = dx
              dx = 0.5*(xh - xl)
              rtsafe = xl  + dx
              if (xl == rtsafe) return
          else
              dxold = dx
              dx = f/df
              temp = rtsafe
              rtsafe = rtsafe - dx
              if (temp == rtsafe ) return
          end if

c     convergence criterion
         if (abs(dx) < xacc) return

         f = func(rtsafe)
         if (f < 0) then
              xl = rtsafe
         else
              xh = rtsafe
         end if

      end do
      print *, "rtsafe exceeding maximum iterations"
      return
      end function rtsafe

c     function for the function at value x
      function func(x)
      implicit none
      real(8):: func
      real(4) :: x
      func = x**2 -0.25
      end function

c     function for the derivative of the function at value x
      function funcd(x)
      implicit none
      real(4):: funcd
      real(4) :: x
      funcd= 2*x
      end function

I tried to check if there was any improper use of the 'if ' statement in the code but couldn't find any.


问:
Navigate in compose based on result
I've this screen:

```<code>@Composable
fun SetNewPasswordScreen(
    viewModel: SetNewPasswordViewModel,
    navigateToSetDetails: () -> Unit,
) {
    val state by viewModel.state.collectAsState()
    if (state.passwordConfirmed) {
        LaunchedEffect(Unit) {
            navigateToSetDetails()
        }
    } else {
        SetNewPasswordScreen(
            confirmNewPassword = viewModel::confirmNewPassword
        )
    }
}
</code>```

and this is the view model:

```<code>@HiltViewModel
class SetNewPasswordViewModel @Inject constructor(
    private val setNewPassword: SetNewPassword,
) : ViewModel() {
    val state: StateFlow<SetNewPasswordViewState> = setNewPassword.flow
        .map { hasSetNewPassword ->
            SetNewPasswordViewState(passwordConfirmed = hasSetNewPassword)
        }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(),
            initialValue = SetNewPasswordViewState.Empty
        )

    fun confirmNewPassword(newPassword: String, repeatedNewPassword: String) {
        viewModelScope.launch {
            setNewPassword(SetNewPassword.Params(newPassword, repeatedNewPassword))
        }
    }
}
</code>```

My problem is when I try to navigate back from
SetDetailsScreen
to
SetNewPasswordScreen

I'm getting true for state.passwordConfirmed again, and I'm stuck in a loop.
I've thought about resetting passwordConfirmed right after the if statement, or using previousBackStackEntry in SetDetailsScreen to store that password should be confirmed again, but it doesn't seem right to do so every time I want to navigate back to a screen that got a result. What's the best practice for this kind of situation?

Title: Navigate in compose based on result

Body:
I've this screen:

@Composable
fun SetNewPasswordScreen(
    viewModel: SetNewPasswordViewModel,
    navigateToSetDetails: () -> Unit,
) {
    val state by viewModel.state.collectAsState()
    if (state.passwordConfirmed) {
        LaunchedEffect(Unit) {
            navigateToSetDetails()
        }
    } else {
        SetNewPasswordScreen(
            confirmNewPassword = viewModel::confirmNewPassword
        )
    }
}

and this is the view model:

@HiltViewModel
class SetNewPasswordViewModel @Inject constructor(
    private val setNewPassword: SetNewPassword,
) : ViewModel() {
    val state: StateFlow<SetNewPasswordViewState> = setNewPassword.flow
        .map { hasSetNewPassword ->
            SetNewPasswordViewState(passwordConfirmed = hasSetNewPassword)
        }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(),
            initialValue = SetNewPasswordViewState.Empty
        )

    fun confirmNewPassword(newPassword: String, repeatedNewPassword: String) {
        viewModelScope.launch {
            setNewPassword(SetNewPassword.Params(newPassword, repeatedNewPassword))
        }
    }
}

My problem is when I try to navigate back from
SetDetailsScreen
to
SetNewPasswordScreen

I'm getting true for state.passwordConfirmed again, and I'm stuck in a loop.
I've thought about resetting passwordConfirmed right after the if statement, or using previousBackStackEntry in SetDetailsScreen to store that password should be confirmed again, but it doesn't seem right to do so every time I want to navigate back to a screen that got a result. What's the best practice for this kind of situation?


问:
Starting inspector on localhost:9229 failed: address already in use
I'm running a node server using "http.createServer", running on port 3001, when I serve the server the first time it runs, and when I do a small change no matter what I get an error said :

```<code>**Starting inspector on localhost:9229 failed: address already in use
Server started on http://localhost:3001
Error: listen EADDRINUSE: address already in use :::3001
    at Server.setupListenHandle [as _listen2] (node:net:1372:16)
    at listenInCluster (node:net:1420:12)
    at Server.listen (node:net:1508:7)**
</code>```

about the 9229 - tried to investigate it by running

```<code>lsof -i :9229
</code>```

and saw that there is 2 instances of it :

```<code>node    88370    33u  IPv6 0x****************      0t0  TCP localhost:9229 (LISTEN)
node    88370    34u  IPv4 0x****************      0t0  TCP localhost:9229 (LISTEN)
</code>```

when I killed it, it created again and again on each code change, this is the first issue.
the second is regarding: "address already in use :::3001.." what is wrong here? I'm listening to that port -

```<code>server.listen(3001);
</code>```

do you have any ideas where to investigate it maybe?
thanks!

about the second issue i tried to change ports.

Body:
I'm running a node server using "http.createServer", running on port 3001, when I serve the server the first time it runs, and when I do a small change no matter what I get an error said :

**Starting inspector on localhost:9229 failed: address already in use
Server started on http://localhost:3001
Error: listen EADDRINUSE: address already in use :::3001
    at Server.setupListenHandle [as _listen2] (node:net:1372:16)
    at listenInCluster (node:net:1420:12)
    at Server.listen (node:net:1508:7)**

about the 9229 - tried to investigate it by running

lsof -i :9229

and saw that there is 2 instances of it :

node    88370    33u  IPv6 0x****************      0t0  TCP localhost:9229 (LISTEN)
node    88370    34u  IPv4 0x****************      0t0  TCP localhost:9229 (LISTEN)

when I killed it, it created again and again on each code change, this is the first issue.
the second is regarding: "address already in use :::3001.." what is wrong here? I'm listening to that port -

server.listen(3001);

do you have any ideas where to investigate it maybe?
thanks!

about the second issue i tried to change ports.


问:
Can I get WebStorm to skip files that are single lines with export statements when navigating?
I'm looking for the site banner, so I tap Shift Shift and search for "sitebanner", which leads me to packages/shared/src/app/components/index.ts. I open that and it is one line:

```<code>export { default as SiteBanner } from './SiteBanner';
</code>```

I Cmd + click on './SiteBanner'; which leads me to:

```<code>export { default } from './SiteBanner';
</code>```

I Cmd + click on that ./SiteBanner and it leads me to the right place.

We have roughly 150 files like this in our code base. It's a pattern the org has adopted. It's usually just one (like the second one).

Is there any way to tell WebStorm to just skip files that only have one line and that line is an export? Kind of like how Java tools will skip/collapse empty directories.

Body:
I'm looking for the site banner, so I tap Shift Shift and search for "sitebanner", which leads me to packages/shared/src/app/components/index.ts. I open that and it is one line:

export { default as SiteBanner } from './SiteBanner';

I Cmd + click on './SiteBanner'; which leads me to:

export { default } from './SiteBanner';

I Cmd + click on that ./SiteBanner and it leads me to the right place.

We have roughly 150 files like this in our code base. It's a pattern the org has adopted. It's usually just one (like the second one).

Is there any way to tell WebStorm to just skip files that only have one line and that line is an export? Kind of like how Java tools will skip/collapse empty directories.


问:
How to speed up df.query
df.query uses numexpr under the hood, but is much slower than pure numexpr

Let's say I have a big DataFrame:

```<code>from random import shuffle
import pandas as pd
l1=list(range(1000000))
l2=list(range(1000000))
shuffle(l1)
shuffle(l2)
df = pd.DataFrame([l1, l2]).T
df=df.sample(frac=1)
df=df.rename(columns={0: 'A', 1:'B'})
</code>```

And I want to compare 2 columns:

```<code>%timeit (df.A == df.B) | (df.A / df.B < 1) |  (df.A * df.B > 3000)
10.8 ms ± 309 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

It takes 10.8 ms in this example

Now I import numexpr and do the same thing:

```<code>import numexpr
a = df.A.__array__()
b = df.B.__array__()
%timeit numexpr.evaluate('((a == b) | (a / b < 1) | (a * b > 3000))')
1.95 ms ± 25.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

numexpr is 6 times faster than Pandas

Now let's use df.loc:

```<code>%timeit df.loc[numexpr.evaluate('((a == b) | (a / b < 1) | (a * b > 3000))')]
20.5 ms ± 155 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df.loc[(df.A == df.B) | (df.A / df.B < 1) |  (df.A * df.B > 3000)]
27 ms ± 296 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df.query('((A == B) | (A / B < 1) | (A * B > 3000))')
32.5 ms ± 80.4 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

numexpr is still significantly faster than pure Pandas. But why is df.query so slow? It uses numexpr under the hood. Is there a way to fix that? Or any other way to use numexpr in pandas without doing a lot of tweaking

Title: How to speed up df.query

Body:
df.query uses numexpr under the hood, but is much slower than pure numexpr

Let's say I have a big DataFrame:

from random import shuffle
import pandas as pd
l1=list(range(1000000))
l2=list(range(1000000))
shuffle(l1)
shuffle(l2)
df = pd.DataFrame([l1, l2]).T
df=df.sample(frac=1)
df=df.rename(columns={0: 'A', 1:'B'})

And I want to compare 2 columns:

%timeit (df.A == df.B) | (df.A / df.B < 1) |  (df.A * df.B > 3000)
10.8 ms ± 309 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

It takes 10.8 ms in this example

Now I import numexpr and do the same thing:

import numexpr
a = df.A.__array__()
b = df.B.__array__()
%timeit numexpr.evaluate('((a == b) | (a / b < 1) | (a * b > 3000))')
1.95 ms ± 25.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

numexpr is 6 times faster than Pandas

Now let's use df.loc:

%timeit df.loc[numexpr.evaluate('((a == b) | (a / b < 1) | (a * b > 3000))')]
20.5 ms ± 155 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df.loc[(df.A == df.B) | (df.A / df.B < 1) |  (df.A * df.B > 3000)]
27 ms ± 296 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df.query('((A == B) | (A / B < 1) | (A * B > 3000))')
32.5 ms ± 80.4 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

numexpr is still significantly faster than pure Pandas. But why is df.query so slow? It uses numexpr under the hood. Is there a way to fix that? Or any other way to use numexpr in pandas without doing a lot of tweaking


问:
ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting
I am trying to do some Time Series model, so I tried copying the lines on some Youtube video: https://www.youtube.com/watch?v=e8Yw4alG16Q&t=1000s but I had an error in the ARIMA model´s line:

```<code>from statsmodels.tsa.arima.model import ARIMA
model = ARIMA(ventas_diarias_log, order=(1,1,1))
results_AR = model.fit
plt.plot(ventas_diariasLogDiffShifting)
plt.plot(results_AR().fittedvalues, color='red')
plt.title('RSS: %.4f'% sum((results_AR().fittedvalues-   ventas_diariasLogDiffShifting['ventas_por_día'])**2))
print('Plotting AR model')
</code>```
```<code>C:\Users\Usuario\anaconda3\lib\site-packages\statsmodels\tsa\base\tsa_model.py:471: ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting.
  self._init_dates(dates, freq)
</code>```

I looked for the error in Stackoverflow but there was no answer that helped me to solve the error.

Body:
I am trying to do some Time Series model, so I tried copying the lines on some Youtube video: https://www.youtube.com/watch?v=e8Yw4alG16Q&t=1000s but I had an error in the ARIMA model´s line:

from statsmodels.tsa.arima.model import ARIMA
model = ARIMA(ventas_diarias_log, order=(1,1,1))
results_AR = model.fit
plt.plot(ventas_diariasLogDiffShifting)
plt.plot(results_AR().fittedvalues, color='red')
plt.title('RSS: %.4f'% sum((results_AR().fittedvalues-   ventas_diariasLogDiffShifting['ventas_por_día'])**2))
print('Plotting AR model')

C:\Users\Usuario\anaconda3\lib\site-packages\statsmodels\tsa\base\tsa_model.py:471: ValueWarning: A date index has been provided, but it has no associated frequency information and so will be ignored when e.g. forecasting.
  self._init_dates(dates, freq)

I looked for the error in Stackoverflow but there was no answer that helped me to solve the error.


问:
C#, ClosedXML. Taking cell addresses from an Excel sheet, and taking data from a data table, and use this addresses and datas to fill a template file
Addresses Excel

I have an issue with my c# code with ClosedXML, which takes cell addresses from another excel file, takes data from another excel table, and writes data to an excel file which is a template but while taking the addresses, it's sorting them, if the data table has a certain value, it's should write the value to a certain address. For example, if the C5 cell in the data table has "SPHERE", it's gonna write to value to K1 cell, if the C5 cell in the data table has "BODY", it's gonna write to value to K5 cell, if the C5 cell in the data table is empty, it's not gonna use that parameter and directly write the value to G3, this example can be multiplied by different parameters.

But the problem is when it takes data from a cell first, it fills the defined cell in the if and saves the file, when it comes to a second file, it fills the first cell with the value before, then fills the second cell. It iterates like this until the parameter has different value.

```<code>        public void Read(string path, string directory, bool savewithdatetime)
        {
            // Open workbook and get worksheet at index 1
            XLWorkbook excelBook = new XLWorkbook(path);
            IXLWorksheet excelWorkSheet = excelBook.Worksheet(1);
            excelWorkSheet.Row(1).Delete();
            // Get number of rows with data
            int excelRowCount = excelWorkSheet.RowsUsed().Count();

            // Open data source and get the worksheet at index 1
            XLWorkbook dataSource = new XLWorkbook(Application.StartupPath + "/dataSource.xlsx");
            IXLWorksheet dataSourceWS = dataSource.Worksheet(1);

            List<string> ifList = new List<string>();
            List<string> parameterList = new List<string>();
            List<string> fromList = new List<string>();
            List<string> toList = new List<string>();

            for (int i = 1; i <= dataSourceWS.RowsUsed().Count(); i++)
            {
                ifList.Add(dataSourceWS.Cell("A" + i).Value.ToString());
                parameterList.Add(dataSourceWS.Cell("D" + i).Value.ToString());
                fromList.Add(dataSourceWS.Cell("B" + i).Value.ToString());
                toList.Add(dataSourceWS.Cell("C" + i).Value.ToString());
            }

            string time = TimeStamp(savewithdatetime);
            // Iterate over each row in the excelWorkSheet
            for (int row = 1; row <= excelRowCount; row++)
            {
                // Reset templateWS to the original template
                templateWS = template.Worksheet(1);

                // Iterate through the data source rows
                for (int i = 0; i < fromList.Count; i++)
                {
                    // Check if the cell at the given address in excelWorkSheet is empty
                    if (string.IsNullOrEmpty(excelWorkSheet.Cell(ifList[i]).Value.ToString()))
                    {
                        // If empty, skip to the next iteration
                        continue;
                    }
                    // Check if the value of the cell at the given address in excelWorkSheet matches the value of the cell at the corresponding address in parameterList
                    else if (parameterList[i] == excelWorkSheet.Cell(ifList[i]).Value.ToString())
                    {
                        // If the values match, set the value of the cell at the corresponding address in toList to the value of the cell at the corresponding address in fromList
                        templateWS.Cell(toList[i]).Value = excelWorkSheet.Cell(fromList[i]).Value;
                    }
                }

                // Save template workbook as new file with incremented index in the specified directory
                template.SaveAs(directory + "/Test results" + time + "/Test result-[" + (row) + "].xlsx");

                if (row == excelRowCount)
                {
                    break;
                }

                // Delete the first row of the excelWorkSheet so that the next iteration will use the next row of data
                excelWorkSheet.Row(1).Delete();
            }

            // Clear the lists and collect garbage to free up memory
            ifList.Clear();
            fromList.Clear();
            parameterList.Clear();
            toList.Clear();
            GC.Collect();
        }

</code>```

Body:
Addresses Excel

I have an issue with my c# code with ClosedXML, which takes cell addresses from another excel file, takes data from another excel table, and writes data to an excel file which is a template but while taking the addresses, it's sorting them, if the data table has a certain value, it's should write the value to a certain address. For example, if the C5 cell in the data table has "SPHERE", it's gonna write to value to K1 cell, if the C5 cell in the data table has "BODY", it's gonna write to value to K5 cell, if the C5 cell in the data table is empty, it's not gonna use that parameter and directly write the value to G3, this example can be multiplied by different parameters.

But the problem is when it takes data from a cell first, it fills the defined cell in the if and saves the file, when it comes to a second file, it fills the first cell with the value before, then fills the second cell. It iterates like this until the parameter has different value.

        public void Read(string path, string directory, bool savewithdatetime)
        {
            // Open workbook and get worksheet at index 1
            XLWorkbook excelBook = new XLWorkbook(path);
            IXLWorksheet excelWorkSheet = excelBook.Worksheet(1);
            excelWorkSheet.Row(1).Delete();
            // Get number of rows with data
            int excelRowCount = excelWorkSheet.RowsUsed().Count();

            // Open data source and get the worksheet at index 1
            XLWorkbook dataSource = new XLWorkbook(Application.StartupPath + "/dataSource.xlsx");
            IXLWorksheet dataSourceWS = dataSource.Worksheet(1);

            List<string> ifList = new List<string>();
            List<string> parameterList = new List<string>();
            List<string> fromList = new List<string>();
            List<string> toList = new List<string>();

            for (int i = 1; i <= dataSourceWS.RowsUsed().Count(); i++)
            {
                ifList.Add(dataSourceWS.Cell("A" + i).Value.ToString());
                parameterList.Add(dataSourceWS.Cell("D" + i).Value.ToString());
                fromList.Add(dataSourceWS.Cell("B" + i).Value.ToString());
                toList.Add(dataSourceWS.Cell("C" + i).Value.ToString());
            }

            string time = TimeStamp(savewithdatetime);
            // Iterate over each row in the excelWorkSheet
            for (int row = 1; row <= excelRowCount; row++)
            {
                // Reset templateWS to the original template
                templateWS = template.Worksheet(1);

                // Iterate through the data source rows
                for (int i = 0; i < fromList.Count; i++)
                {
                    // Check if the cell at the given address in excelWorkSheet is empty
                    if (string.IsNullOrEmpty(excelWorkSheet.Cell(ifList[i]).Value.ToString()))
                    {
                        // If empty, skip to the next iteration
                        continue;
                    }
                    // Check if the value of the cell at the given address in excelWorkSheet matches the value of the cell at the corresponding address in parameterList
                    else if (parameterList[i] == excelWorkSheet.Cell(ifList[i]).Value.ToString())
                    {
                        // If the values match, set the value of the cell at the corresponding address in toList to the value of the cell at the corresponding address in fromList
                        templateWS.Cell(toList[i]).Value = excelWorkSheet.Cell(fromList[i]).Value;
                    }
                }

                // Save template workbook as new file with incremented index in the specified directory
                template.SaveAs(directory + "/Test results" + time + "/Test result-[" + (row) + "].xlsx");

                if (row == excelRowCount)
                {
                    break;
                }

                // Delete the first row of the excelWorkSheet so that the next iteration will use the next row of data
                excelWorkSheet.Row(1).Delete();
            }

            // Clear the lists and collect garbage to free up memory
            ifList.Clear();
            fromList.Clear();
            parameterList.Clear();
            toList.Clear();
            GC.Collect();
        }


问:
Make this batch file that uses NirCMD close also folder properties windows
the batch file code is below It closes all open explorer windows without Stopping copy or move operations and I like that But I would also like if it would close windows explorer properties windows like the below one if those are open too thanks for in advance for any help on this

@echo
cls
nircmd.exe win close class "CabinetWClass"

" I looked on nircmd documentation but couldn't find anything"


问:
No module named 'gtts'
i install gtts with :
pip install gTTS
but Pycharm doesnt import it correctly :/

Python version : 3.7   (i use this version for use pygame)
pip version : 22.3.1

I reinstalled python
but doesnt work
my name file is test (not gtts)

Title: No module named 'gtts'


问:
How to draw rectangle canvas on camera with .Net MAUI?
I try draw a rectangle on camera View to center a card ID and return image cut. I done previously with Xamarin Forms with a Redenrers to IOS and Android, but libraries already deprecated or obsolete.

I want help to another method or package to resolve it. I search some days, but I haven't found a solution.

P.D. I don't need recognize card ID info, only need crop image.


问:
Python Plotly Treemap Color Scale Variable Not Adding Up Child Values
I am trying to plot treemap using Plotly in Python. I have three categorical variables that I am using as parent/child variables for the plot and two other continuous variables - "Sales_Quantity" and "Sales_Amount", and I am passing one of these as "value" - represented as area, and "color" variables respectively.

Here is the sample of my data-

```<code>{'Category': {1171: 'Cat_1049',
  1172: 'Cat_1049',
  1173: 'Cat_1049',
  1174: 'Cat_1049',
  1175: 'Cat_1049'},
 'SubCategory_1': {1171: 6754, 1172: 6752, 1173: 6748, 1174: 6746, 1175: 6742},
 'SubCategory_2': {1171: 'MCW-145',
  1172: 'MCW-145',
  1173: 'MCW-145',
  1174: 'MCW-145',
  1175: 'MCW-141'},
 'Sales_Amount': {1171: 13509.043,
  1172: 8662.54,
  1173: 92531.29,
  1174: 11312.07,
  1175: 6427.037},
 'Sales_Quantity': {1171: 6, 1172: 4, 1173: 38, 1174: 5, 1175: 3}}
</code>```

I was expecting the values of "color" --> "Sales Amount" of all child variables to be added up and the color of the parent boxes displayed accordingly. However, this is not happening. And the value shown on hover on the parent nodes are often lower than the "Sales Amount" on individual child nodes.

Here is the code I used-

```<code>fig = px.treemap(df_test, path=
[px.Constant('All'),'Category', 'SubCategory_1','SubCategory_2'],
                 values='Sales_Quantity',
                 color='Sales_Amount',
color_continuous_scale=px.colors.sequential.Turbo)
    fig.update_layout(legend_title="",
    autosize=False,
    width=1440,
    height=900,
    margin=dict(
        l=0,
        r=15,
        b=10,
        t=30,
        pad=3
    ),title={'text':(f'Sales Amount and Quantities by Groups'),
           'y':0.99,'x':0.5,'xanchor':'center',
'yanchor': 'top','font_size':20},
    #title_x=0.5,
    legend=dict(orientation="h"))

fig.show()
</code>```

I am not sure if I am doing something wrong here or if the data is not structured properly. It does not make sense why it would take care of the aggregation on the "value" variable and not on the "color" variable.

For example, the sub-categories in "Cat_1049"  have the highest "Sales Amount" of all, and the aggregate sales for this parent category is about $61.9 M. However, the color scheme is showing it as $5.4M.

Is there a way to make the colors appear the way I need it - which is for it expand the range of color scale and assign colors to the parent nodes accordingly?

I have tried some of the potential tweaks that could solve this from those found in treemap documentation - including branchvalues etc. Based on another tip - I made  sure that all NaNs were removed, reorderdered the data-frame by the three categorical columns and reset the index.  I also tried plotting using go.Treemap - which I could not even get it to display the plot in the first place.

Body:
I am trying to plot treemap using Plotly in Python. I have three categorical variables that I am using as parent/child variables for the plot and two other continuous variables - "Sales_Quantity" and "Sales_Amount", and I am passing one of these as "value" - represented as area, and "color" variables respectively.

Here is the sample of my data-

{'Category': {1171: 'Cat_1049',
  1172: 'Cat_1049',
  1173: 'Cat_1049',
  1174: 'Cat_1049',
  1175: 'Cat_1049'},
 'SubCategory_1': {1171: 6754, 1172: 6752, 1173: 6748, 1174: 6746, 1175: 6742},
 'SubCategory_2': {1171: 'MCW-145',
  1172: 'MCW-145',
  1173: 'MCW-145',
  1174: 'MCW-145',
  1175: 'MCW-141'},
 'Sales_Amount': {1171: 13509.043,
  1172: 8662.54,
  1173: 92531.29,
  1174: 11312.07,
  1175: 6427.037},
 'Sales_Quantity': {1171: 6, 1172: 4, 1173: 38, 1174: 5, 1175: 3}}

I was expecting the values of "color" --> "Sales Amount" of all child variables to be added up and the color of the parent boxes displayed accordingly. However, this is not happening. And the value shown on hover on the parent nodes are often lower than the "Sales Amount" on individual child nodes.

Here is the code I used-

fig = px.treemap(df_test, path=
[px.Constant('All'),'Category', 'SubCategory_1','SubCategory_2'],
                 values='Sales_Quantity',
                 color='Sales_Amount',
color_continuous_scale=px.colors.sequential.Turbo)
    fig.update_layout(legend_title="",
    autosize=False,
    width=1440,
    height=900,
    margin=dict(
        l=0,
        r=15,
        b=10,
        t=30,
        pad=3
    ),title={'text':(f'Sales Amount and Quantities by Groups'),
           'y':0.99,'x':0.5,'xanchor':'center',
'yanchor': 'top','font_size':20},
    #title_x=0.5,
    legend=dict(orientation="h"))

fig.show()

I am not sure if I am doing something wrong here or if the data is not structured properly. It does not make sense why it would take care of the aggregation on the "value" variable and not on the "color" variable.

For example, the sub-categories in "Cat_1049"  have the highest "Sales Amount" of all, and the aggregate sales for this parent category is about $61.9 M. However, the color scheme is showing it as $5.4M.

Is there a way to make the colors appear the way I need it - which is for it expand the range of color scale and assign colors to the parent nodes accordingly?

I have tried some of the potential tweaks that could solve this from those found in treemap documentation - including branchvalues etc. Based on another tip - I made  sure that all NaNs were removed, reorderdered the data-frame by the three categorical columns and reset the index.  I also tried plotting using go.Treemap - which I could not even get it to display the plot in the first place.


问:
Problem Uploading File Using FTPS Protocol
I'm try to upload file using FTPS.

Currently I use the library org.apache.commons.net.ftp.FTPSClient;

This is part of code that I use:

FTPSClient ftpClient = new FTPSClient("SSL", true); ftpClient.connect(host, port); ftpClient.login(user, password);
And I check the connection using:
ftpClient.isConnected()

This return a boolean value, when is ok return: true

The problem is when try to upload a file, for this I Use:

ftpClient.storeFile(file.getName(), fis);

This return false and the message: 501 Server cannot accept argument.

I am grateful for any support that the community can give me with this issue.

Thanks

This is the Code snippet that I use:

```<code>FTPSClient ftpClient = new FTPSClient("SSL",true);`
try {
  FTPClientConfig  conf=newFTPClientConfig(FTPClientConfig.SYST_NT);
  ftpClient.configure(conf);
  ftpClient.connect(host,port);
  ftpClient.login(user, pass);
  System.out.println("Connected?: "+ftpClient.isConnected());
  ftpClient.enterLocalPassiveMode();
  String path = carpetaLocal;
  File directorio = new File(path);
  File[] ficheros = directorio.listFiles();
for (int i = 0; i < ficheros.length; i++) {
  File file = (ficheros[i]);
  FileInputStream fis = new FileInputStream(file);
  Client.setFileType(FTPClient.BINARY_FILE_TYPE);
  ftpClient.enterLocalActiveMode();
  boolean res = ftpClient.storeFile(file.getName(), fis);
  System.out.println("File Upload Successful?: " + res);
 }
 ftpClient.disconnect();
 System.out.println("Connected?: " +ftpClient.isConnected());
} catch (IOException ex) {
    ex.printStackTrace();
    System.exit(1);
  }

</code>```

Body:
I'm try to upload file using FTPS.

Currently I use the library org.apache.commons.net.ftp.FTPSClient;

This is part of code that I use:

FTPSClient ftpClient = new FTPSClient("SSL", true); ftpClient.connect(host, port); ftpClient.login(user, password);
And I check the connection using:
ftpClient.isConnected()

This return a boolean value, when is ok return: true

The problem is when try to upload a file, for this I Use:

ftpClient.storeFile(file.getName(), fis);

This return false and the message: 501 Server cannot accept argument.

I am grateful for any support that the community can give me with this issue.

Thanks

This is the Code snippet that I use:

FTPSClient ftpClient = new FTPSClient("SSL",true);`
try {
  FTPClientConfig  conf=newFTPClientConfig(FTPClientConfig.SYST_NT);
  ftpClient.configure(conf);
  ftpClient.connect(host,port);
  ftpClient.login(user, pass);
  System.out.println("Connected?: "+ftpClient.isConnected());
  ftpClient.enterLocalPassiveMode();
  String path = carpetaLocal;
  File directorio = new File(path);
  File[] ficheros = directorio.listFiles();
for (int i = 0; i < ficheros.length; i++) {
  File file = (ficheros[i]);
  FileInputStream fis = new FileInputStream(file);
  Client.setFileType(FTPClient.BINARY_FILE_TYPE);
  ftpClient.enterLocalActiveMode();
  boolean res = ftpClient.storeFile(file.getName(), fis);
  System.out.println("File Upload Successful?: " + res);
 }
 ftpClient.disconnect();
 System.out.println("Connected?: " +ftpClient.isConnected());
} catch (IOException ex) {
    ex.printStackTrace();
    System.exit(1);
  }


问:
Is there a SaaS provider for a HTTPS hub/load-balancer, for bandwidth-constrained IoT devices?
The reason I write this post is I would like to avoid re-inventing the wheel if possible, as I think this is definitely a solved problem, but I am struggling to find a SaaS provider which offers an existing solution that fits my use-case.

The problem goes as follows:

I am running a fleet of data hungry IoT devices.

These devices need to send data to multiple 3rd party endpoints (all HTTPS).

Currently as each new endpoint is added, the mobile data usage (3G/4G/5G) scales in a linear manner, as it is sending to each 3rd-party from the IoT device itself.

Proposed solution:

The IoT devices transmit their data to a HTTPS "hub", this then forwards the data to a list of specified endpoints. Like how a HTTPS load-balancer would work, but operating in a send-to-all mode.

This would keep the IoT device data usage constant, while increasing the cloud data usage (which is orders of magnitude cheaper). Resulting in a cost saving.

Now I had imagined that this is a fairly common problem with IoT devices, but am struggling to find any provider offering this type of service already. I may be lacking knowledge of what terminology to search for if this already exists. If anybody knows the name of a service which offers something like this then this is the type of answer I am looking for.

Ideal features:

HTTPS retry. The service should cache a request if it fails to forward to one or more of the destinations, it should then attempt to re-transmit to the failed destinations after some amount of time.

A SLA regarding uptime, as downtime of this service would expectedly cause a larger outage than duplicating the requests in the original method.

Reverse proxy to preserve the original IP address if possible.

A web GUI (a nice-to-have but not essential).

If this doesn't exist I will likely write my own solution. Thanks in advance.


问:
How to Open and Read text files on Android in C#
The code I have now is:

```<code>        Intent intent = new Intent();
        intent.SetType("text/plain");
        intent.SetAction(Intent.ActionGetContent);
        StartActivityForResult(Intent.CreateChooser(intent, "Select file"), 1);
        string str = System.Environment.GetFolderPath(?????);
</code>```

That last line of course doesn't work. I'd like the user to be able to browse folders on the device and open one of them. This is simple in Windows but Android is proving difficult.

1/3/2023:
This issue is still unsolved. Coming from Windows and C# this is all trivial. But Android, not.

I have tried these:

var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
var documents = Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory);
var documents = System.Environment.CurrentDirectorygetExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);

WIth some I can save the file from my app on Android but I cannot find them (non-programmatically).

When I save files in FXTextEdit (on Android), I save them to folders I can easily access. Why not progammatically?

I am coding in C#.

Thanks.

Body:
The code I have now is:

        Intent intent = new Intent();
        intent.SetType("text/plain");
        intent.SetAction(Intent.ActionGetContent);
        StartActivityForResult(Intent.CreateChooser(intent, "Select file"), 1);
        string str = System.Environment.GetFolderPath(?????);

That last line of course doesn't work. I'd like the user to be able to browse folders on the device and open one of them. This is simple in Windows but Android is proving difficult.

1/3/2023:
This issue is still unsolved. Coming from Windows and C# this is all trivial. But Android, not.

I have tried these:

var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
var documents = Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory);
var documents = System.Environment.CurrentDirectorygetExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);

WIth some I can save the file from my app on Android but I cannot find them (non-programmatically).

When I save files in FXTextEdit (on Android), I save them to folders I can easily access. Why not progammatically?

I am coding in C#.

Thanks.


问:
Styling an extended native element in ShadowDOM
I understand that in order to style elements from the ShadowDOM, the shadowDOM itself has to "know"
the element, thus be declared inside of it.
It works well for regular web components but i haven't found an answer to it weather it's the same for an extended
native element.
For example, I wanted to know if the code I wrote is the best way, i.e. the external p acting as container, or am i creating a redundant p element.

JavaScript:

```<code>class P_example extends HTMLParagraphElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.innerHTML = `
        <style>
        p{
            background-color: orangered;
            width: max-content;
        }
        </style>
        <p><slot>Some default</slot></p>
    `;
    this.shadowRoot.append();
  }
  connectedCallback() {
    //add styling class to the p element
  }
}
customElements.define("omer-p", P_example, { extends: "p" });
</code>```

HTML:

```<code><p is="omer-p">Some sample text</p>
</code>```

Body:
I understand that in order to style elements from the ShadowDOM, the shadowDOM itself has to "know"
the element, thus be declared inside of it.
It works well for regular web components but i haven't found an answer to it weather it's the same for an extended
native element.
For example, I wanted to know if the code I wrote is the best way, i.e. the external p acting as container, or am i creating a redundant p element.

JavaScript:

class P_example extends HTMLParagraphElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.innerHTML = `

<slot>Some default</slot>

    `;
    this.shadowRoot.append();
  }
  connectedCallback() {
    //add styling class to the p element
  }
}
customElements.define("omer-p", P_example, { extends: "p" });

HTML:

Some sample text


问:
jPowerShell and PowerShell Core (7.x) Issue
I am trying to invoke PowerShell cmdlets and scripts from a Java Application. I am using jPowerShell . It works as expected as expected with PowerShell version 6.0.x. However, when I am running PowerShell 7.x, the executeCommand() method times out. Just wanted to find out if anyone else have had this issue and how you resolved it. I'd appreciate if you can let me know. Thanks

Here is my sample code:

```<code>   ..
   ..
   //Creates PowerShell session (we can execute several commands in the same session)
   try (PowerShell powerShell = PowerShell.openSession()) {
       //Execute a command in PowerShell session
       PowerShell powerShell = PowerShell.openSession("pwsh"); // pwsh is the executable in Linux
       Map<String, String> config = new HashMap<String, String>();
       config.put("maxWait", "60000"); // wait for a minute
       PowerShellResponse response = powerShell.executeCommand("Get-Process");

       responseBody = response.getCommandOutput();
       responseCode = response.isError() ? 1 : 0;
   } catch(Exception e) {
       StringBuffer sb = new StringBuffer(e.getMessage());
       return toResponse(responseCode, sb.toString());
   }
   ..
   ..
</code>```

Please note that I am running the above inside a Docker container and I am able to see the "pwsh -nologo -noexit -Command -" process running in the container before it times out.

Jay

I tried to run a PowerShell cmdlet from Java code using jPowerShell and I was expecting the result of the PowerShell cmdlet (for example, Get-Date, Get-Process, etc)

Body:
I am trying to invoke PowerShell cmdlets and scripts from a Java Application. I am using jPowerShell . It works as expected as expected with PowerShell version 6.0.x. However, when I am running PowerShell 7.x, the executeCommand() method times out. Just wanted to find out if anyone else have had this issue and how you resolved it. I'd appreciate if you can let me know. Thanks

Here is my sample code:

   ..
   ..
   //Creates PowerShell session (we can execute several commands in the same session)
   try (PowerShell powerShell = PowerShell.openSession()) {
       //Execute a command in PowerShell session
       PowerShell powerShell = PowerShell.openSession("pwsh"); // pwsh is the executable in Linux
       Map<String, String> config = new HashMap<String, String>();
       config.put("maxWait", "60000"); // wait for a minute
       PowerShellResponse response = powerShell.executeCommand("Get-Process");

       responseBody = response.getCommandOutput();
       responseCode = response.isError() ? 1 : 0;
   } catch(Exception e) {
       StringBuffer sb = new StringBuffer(e.getMessage());
       return toResponse(responseCode, sb.toString());
   }
   ..
   ..

Please note that I am running the above inside a Docker container and I am able to see the "pwsh -nologo -noexit -Command -" process running in the container before it times out.

Jay

I tried to run a PowerShell cmdlet from Java code using jPowerShell and I was expecting the result of the PowerShell cmdlet (for example, Get-Date, Get-Process, etc)


问:
Cursor in python
I am trying to make a computer-like cursor which moves when you press the arrow keys on the keyboard, I am using the keyboard extension. Here's the code:

```<code>import os
import keyboard
cursor = ""
count = 0
cursorPOS=""
cursorPOSl=""
cursorPOSr=""
while True:
    count = count + 1
    os.system('cls')
    print(cursorPOS,cursor)
    cursorPOS= cursorPOSl + "" + cursorPOSr

import keyboard
while True:
    try:
        if keyboard.is_pressed('right'):
            print('')
            break  # finishing the loop
    except:
        break
</code>```

I am stuck at the if keyboard is pressed part, there any way to detect and make the cursor move? Also, I didn't make the code for the cursor showing, but that's a second problem

Any tips on how to do those things?

Didn't exactly try something, just trying to discover what to do

Title: Cursor in python

Body:
I am trying to make a computer-like cursor which moves when you press the arrow keys on the keyboard, I am using the keyboard extension. Here's the code:

import os
import keyboard
cursor = ""
count = 0
cursorPOS=""
cursorPOSl=""
cursorPOSr=""
while True:
    count = count + 1
    os.system('cls')
    print(cursorPOS,cursor)
    cursorPOS= cursorPOSl + "" + cursorPOSr

import keyboard
while True:
    try:
        if keyboard.is_pressed('right'):
            print('')
            break  # finishing the loop
    except:
        break

I am stuck at the if keyboard is pressed part, there any way to detect and make the cursor move? Also, I didn't make the code for the cursor showing, but that's a second problem

Any tips on how to do those things?

Didn't exactly try something, just trying to discover what to do


问:
How to manage order of init services in nestjs
in nestjs app, I have 2 modules:
ServiceModule and ParamStoreModule

Param Store module has a ParamStoreService which loads Data from AWS Param Store (i load all params only once and store them in a map)

Service Module has a Work Service which during initialization (in constructor) requires a parameter from this ParamStoreService, but this value is loaded after the Worker service is created

Is there a way to create this Work Service after the values from Param Store will be loaded? Can we manage the order of creating Services?

regards


问:
Error with [webpack-cli] : Error [ERR_REQUIRE_ESM]: require() of ES Module
a few days ago I received my new MacBook M2 and I have some problems.

When I try "npm run dev" after "npm install" successfully, this is displayed:

```<code>npm run dev

> dev
> webpack serve --config ./bundler/webpack.dev.js

[webpack-cli] Failed to load '/Users/tombirembaut/Desktop/Resource Files/06-animations/bundler/webpack.dev.js' config
[webpack-cli] Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/tombirembaut/node_modules/internal-ip/index.js from /Users/tombirembaut/Desktop/Resource Files/06-animations/bundler/webpack.dev.js not supported.
Instead change the require of index.js in /Users/tombirembaut/Desktop/Resource Files/06-animations/bundler/webpack.dev.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/Users/tombirembaut/Desktop/Resource Files/06-animations/bundler/webpack.dev.js:3:12)
    at async Promise.all (index 0)
    at async WebpackCLI.tryRequireThenImport (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:225:26)
    at async loadConfigByPath (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:1325:27)
    at async Promise.all (index 0)
    at async WebpackCLI.loadConfig (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:1375:35)
    at async WebpackCLI.createCompiler (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:1643:22)
    at async Command.<anonymous> (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/@webpack-cli/serve/lib/index.js:82:30)
    at async Command.parseAsync (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/node_modules/commander/lib/command.js:916:5)
    at async Command.<anonymous> (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:1292:13)
    at async Command.parseAsync (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/node_modules/commander/lib/command.js:916:5)
    at async WebpackCLI.run (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:1296:9)
    at async runCLI (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/bootstrap.js:9:9) {
  code: 'ERR_REQUIRE_ESM'
}
</code>```

I tried to uninstall node and reinstall it without success, if you have any ideas where it could come from I'm interested !

Body:
a few days ago I received my new MacBook M2 and I have some problems.

When I try "npm run dev" after "npm install" successfully, this is displayed:

npm run dev

> dev
> webpack serve --config ./bundler/webpack.dev.js

[webpack-cli] Failed to load '/Users/tombirembaut/Desktop/Resource Files/06-animations/bundler/webpack.dev.js' config
[webpack-cli] Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/tombirembaut/node_modules/internal-ip/index.js from /Users/tombirembaut/Desktop/Resource Files/06-animations/bundler/webpack.dev.js not supported.
Instead change the require of index.js in /Users/tombirembaut/Desktop/Resource Files/06-animations/bundler/webpack.dev.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/Users/tombirembaut/Desktop/Resource Files/06-animations/bundler/webpack.dev.js:3:12)
    at async Promise.all (index 0)
    at async WebpackCLI.tryRequireThenImport (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:225:26)
    at async loadConfigByPath (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:1325:27)
    at async Promise.all (index 0)
    at async WebpackCLI.loadConfig (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:1375:35)
    at async WebpackCLI.createCompiler (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:1643:22)
    at async Command.<anonymous> (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/@webpack-cli/serve/lib/index.js:82:30)
    at async Command.parseAsync (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/node_modules/commander/lib/command.js:916:5)
    at async Command.<anonymous> (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:1292:13)
    at async Command.parseAsync (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/node_modules/commander/lib/command.js:916:5)
    at async WebpackCLI.run (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/webpack-cli.js:1296:9)
    at async runCLI (/Users/tombirembaut/Desktop/Resource Files/06-animations/node_modules/webpack-cli/lib/bootstrap.js:9:9) {
  code: 'ERR_REQUIRE_ESM'
}

I tried to uninstall node and reinstall it without success, if you have any ideas where it could come from I'm interested !


问:
my panning handler resets the offset state after the second time
Im trying to make a panning handler for my canvas element using a state for the offset and a state to hold the mouse start position. The first pan works as expected and the offset is set to the correct values. On the secont pan when clicked it worked as expected but then when i move it it resets the offset to 0 asif its the first pan. Im very new to react and will appreciate any help.

```<code>function handlePan(event) {
        switch (event.type) {
            case "mouseleave":
                setIsPanning(false);
                break;

            case "mousedown":
                setIsPanning(true);
                setPanStartX(event.clientX);
                setPanStartY(event.clientY);
                break;

            case "mouseup":
                setIsPanning(false);
                console.log("UP");
                break;

            case "mousemove":
                if (isPanning) {
                    // Calculate the panning offset based on the mouse position and the pan start position
                    const offsetX = event.clientX - panStartX;
                    const offsetY = event.clientY - panStartY;
                    setPanOffsetX(offsetX);
                    setPanOffsetY(offsetY);
                    console.log("PANNING");
                }
                break;

            default:
                break;
        }
    }
</code>```

I tried making a second state to store values to be substracted with the offset as the transform of the canvas which i thought would fix it but it made the canvas's offset stack when moved consecutively.

Body:
Im trying to make a panning handler for my canvas element using a state for the offset and a state to hold the mouse start position. The first pan works as expected and the offset is set to the correct values. On the secont pan when clicked it worked as expected but then when i move it it resets the offset to 0 asif its the first pan. Im very new to react and will appreciate any help.

function handlePan(event) {
        switch (event.type) {
            case "mouseleave":
                setIsPanning(false);
                break;

            case "mousedown":
                setIsPanning(true);
                setPanStartX(event.clientX);
                setPanStartY(event.clientY);
                break;

            case "mouseup":
                setIsPanning(false);
                console.log("UP");
                break;

            case "mousemove":
                if (isPanning) {
                    // Calculate the panning offset based on the mouse position and the pan start position
                    const offsetX = event.clientX - panStartX;
                    const offsetY = event.clientY - panStartY;
                    setPanOffsetX(offsetX);
                    setPanOffsetY(offsetY);
                    console.log("PANNING");
                }
                break;

            default:
                break;
        }
    }

I tried making a second state to store values to be substracted with the offset as the transform of the canvas which i thought would fix it but it made the canvas's offset stack when moved consecutively.