问:
Can I tell python multiprocessing.Process not to serialize something?
I essentially have a class like this:

```<code>class ConnectionClass:
    def __init__(self, addr:str) -> None:
        self.addr = addr

    def connection(self):
        if self._connection is None:
            self._connection = magic_create_socket(self.addr)
        return self._connection

    def do_something(self):
        self._connection.send_message("something")
</code>```

I will be passing it via something like:

```<code>def do_processing(connection):
    # this will run many times:
    connection.do_something()

# There will be more processes or maybe a process pool. I want to avoid repeating myself
my_connection = ConnectionClass("some address")
my_proc = multiprocessing.Process(do_processing, my_connection)
</code>```

Now clearly, each process should have its own connection sockets, file descriptors and so on. So while I want to pass any props that describe the connection, like addr in this simplified example, but I want the ConnectionClass._connection be None when it is copied to the other process, so it gets lazy initialized again.

I COULD make the connection description and the actual wrapper for the socket/fd separate, but it means extra classes, extra code to pass the description from one to another and so on.

Is it possible to use some annotation to tell Pythons multiprocessing library to ignore certain values when serializing the data for the other process?

Body:
I essentially have a class like this:

class ConnectionClass:
    def __init__(self, addr:str) -> None:
        self.addr = addr

    def connection(self):
        if self._connection is None:
            self._connection = magic_create_socket(self.addr)
        return self._connection

    def do_something(self):
        self._connection.send_message("something")

I will be passing it via something like:

def do_processing(connection):
    # this will run many times:
    connection.do_something()

# There will be more processes or maybe a process pool. I want to avoid repeating myself
my_connection = ConnectionClass("some address")
my_proc = multiprocessing.Process(do_processing, my_connection)

Now clearly, each process should have its own connection sockets, file descriptors and so on. So while I want to pass any props that describe the connection, like addr in this simplified example, but I want the ConnectionClass._connection be None when it is copied to the other process, so it gets lazy initialized again.

I COULD make the connection description and the actual wrapper for the socket/fd separate, but it means extra classes, extra code to pass the description from one to another and so on.

Is it possible to use some annotation to tell Pythons multiprocessing library to ignore certain values when serializing the data for the other process?


来源: stackexchange

问:
Parallel inference on single model in CUDA cause worker processes to terminate
I'm trying to start openai\whisper inference on single model in CUDA with multiprocessing.Pool.
On 6 workers inference works fine, except of some CUDA warnings on exiting worker processes.
On 7 and more workers all works, but at the end (when some workers finished) some workers crashing with "CUDA out of memory" and the same warnings as with 6 processes.

Does anybody know, what's wrong, and is there any way to solve this issue?

I'm using Ubuntu 20.04, GEFORCE RTX 3060, CUDA 12, Pytorch 13, and openai\whisper

When i run program below, with num_proc=6 or less, all works fine, processes finishing tasks:

```<code>import os
import dill
import torch
import whisper

from pathlib import Path

def whisper_transcribe(arg, lng= None):
    result = arg[0][0].transcribe(arg[1], task="transcribe", language=lng)
    with open(arg[1][:arg[1].rfind('.')] + '.txt', "w") as res:
        if result["text"] != "":
            res.write(result["text"])
    return 0

def wp_audio():
    lng = "ru"
    if lng == "all":
        lng = None

    filenames_list = ['videoplayback_1.mp3','videoplayback_2.mp3','videoplayback_3.mp3','videoplayback_4.mp3','videoplayback_5.mp3','videoplayback_6.mp3','videoplayback_7.mp3','videoplayback_8.mp3','videoplayback_9.mp3','videoplayback_10.mp3']
    lng_list = ['ru', 'ru', 'ru', 'ru', 'ru', 'ru', 'ru', 'ru', 'ru', 'ru']

    global model

    num_proc = 6

    model = dill.load(open("wm_large.dt", 'rb'))
    model.to('cuda')
    model.share_memory()

    lst = []
    model_list = [[model]]*num_proc
    for i in range(num_proc):
        lst.append([model_list[i],filenames_list[i]])

    torch.multiprocessing.set_start_method('spawn')
    with torch.multiprocessing.Pool(num_proc) as pl:
        pl.map(whisper_transcribe, lst)

    del model.encoder, model.decoder, model
    torch.cuda.empty_cache()

if __name__ == '__main__':
    wp_audio()
</code>```

In spite of this works fine, i get some CUDA warnings.

```<code>[W CudaIPCTypes.cpp:95] Producer process tried to deallocate over 1000 memory blocks referred by consumer processes. Deallocation might be significantly slowed down. We assume it will never going to be the case, but if it is, please file but to https://github.com/pytorch/pytorch
[W CudaIPCTypes.cpp:15] Producer process has been terminated before all shared CUDA tensors released. See Note [Sharing CUDA tensors]
</code>```

and hundreds of:

```<code>[W CUDAGuardImpl.h:46] Warning: CUDA warning: driver shutting down (function uncheckedGetDevice)
[W CUDAGuardImpl.h:62] Warning: CUDA warning: invalid device ordinal (function uncheckedSetDevice)
</code>```

with this at the and:

```<code>/usr/local/lib/python3.10/multiprocessing/resource_tracker.py:224: UserWarning: resource_tracker: There appear to be 1 leaked semaphore objects to clean up at shutdown
warnings.warn('resource_tracker: There appear to be %d '
</code>```

But when i use num_proc more than 6, some processes closing before their task finished, with this:

```<code>multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/multiprocessing/pool.py", line 125, in worker
    result = (True, func(*args, **kwds))
  File "/usr/local/lib/python3.10/multiprocessing/pool.py", line 48, in mapstar
    return list(map(*args))
  File "/home/user/Projekt/wp_audio_0.2.py", line 24, in whisper_transcribe
    def wp_audio():
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/transcribe.py", line 186, in transcribe
    result: DecodingResult = decode_with_fallback(segment)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/transcribe.py", line 119, in decode_with_fallback
    decode_result = model.decode(segment, options)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
    return func(*args, **kwargs)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/decoding.py", line 712, in decode
    result = DecodingTask(model, options).run(mel)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
    return func(*args, **kwargs)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/decoding.py", line 626, in run
    audio_features: Tensor = self._get_audio_features(mel)  # encoder forward pass
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/decoding.py", line 567, in _get_audio_features
    audio_features = self.model.encoder(mel)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1190, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/model.py", line 156, in forward
    x = block(x)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1190, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/model.py", line 124, in forward
    x = x + self.attn(self.attn_ln(x), mask=mask, kv_cache=kv_cache)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1190, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/model.py", line 85, in forward
    wv = self.qkv_attention(q, k, v, mask)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/model.py", line 99, in qkv_attention
    w = F.softmax(qk.float(), dim=-1).to(q.dtype)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/nn/functional.py", line 1841, in softmax
    ret = input.softmax(dim)
torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 172.00 MiB (GPU 0; 11.76 GiB total capacity; 287.76 MiB already allocated; 205.19 MiB free; 300.00 MiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/user/Projekt/wp_audio_0.2.py", line 60, in <module>
  File "/home/user/Projekt/wp_audio_0.2.py", line 52, in wp_audio
  File "/usr/local/lib/python3.10/multiprocessing/pool.py", line 367, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "/usr/local/lib/python3.10/multiprocessing/pool.py", line 774, in get
    raise self._value
torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 172.00 MiB (GPU 0; 11.76 GiB total capacity; 287.76 MiB already allocated; 205.19 MiB free; 300.00 MiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF
[W CudaIPCTypes.cpp:95] Producer process tried to deallocate over 1000 memory blocks referred by consumer processes. Deallocation might be significantly slowed down. We assume it will never going to be the case, but if it is, please file but to https://github.com/pytorch/pytorch
[W CudaIPCTypes.cpp:15] Producer process has been terminated before all shared CUDA tensors released. See Note [Sharing CUDA tensors]
</code>```

with hundreds of this:

```<code>[W CUDAGuardImpl.h:46] Warning: CUDA warning: driver shutting down (function uncheckedGetDevice)
[W CUDAGuardImpl.h:62] Warning: CUDA warning: invalid device ordinal (function uncheckedSetDevice)
</code>```

and this at the end:

```<code>/usr/local/lib/python3.10/multiprocessing/resource_tracker.py:224: UserWarning: resource_tracker: There appear to be 1 leaked semaphore objects to clean up at shutdown
  warnings.warn('resource_tracker: There appear to be %d '
</code>```

the error with num_proc more than 6 occur only in the end of the program (when some processes are already finished their task)

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to start openai\whisper inference on single model in CUDA with multiprocessing.Pool.
On 6 workers inference works fine, except of some CUDA warnings on exiting worker processes.
On 7 and more workers all works, but at the end (when some workers finished) some workers crashing with "CUDA out of memory" and the same warnings as with 6 processes.

Does anybody know, what's wrong, and is there any way to solve this issue?

I'm using Ubuntu 20.04, GEFORCE RTX 3060, CUDA 12, Pytorch 13, and openai\whisper

When i run program below, with num_proc=6 or less, all works fine, processes finishing tasks:

import os
import dill
import torch
import whisper

from pathlib import Path

def whisper_transcribe(arg, lng= None):
    result = arg[0][0].transcribe(arg[1], task="transcribe", language=lng)
    with open(arg[1][:arg[1].rfind('.')] + '.txt', "w") as res:
        if result["text"] != "":
            res.write(result["text"])
    return 0

def wp_audio():
    lng = "ru"
    if lng == "all":
        lng = None

    filenames_list = ['videoplayback_1.mp3','videoplayback_2.mp3','videoplayback_3.mp3','videoplayback_4.mp3','videoplayback_5.mp3','videoplayback_6.mp3','videoplayback_7.mp3','videoplayback_8.mp3','videoplayback_9.mp3','videoplayback_10.mp3']
    lng_list = ['ru', 'ru', 'ru', 'ru', 'ru', 'ru', 'ru', 'ru', 'ru', 'ru']

    global model

    num_proc = 6

    model = dill.load(open("wm_large.dt", 'rb'))
    model.to('cuda')
    model.share_memory()

    lst = []
    model_list = [[model]]*num_proc
    for i in range(num_proc):
        lst.append([model_list[i],filenames_list[i]])

    torch.multiprocessing.set_start_method('spawn')
    with torch.multiprocessing.Pool(num_proc) as pl:
        pl.map(whisper_transcribe, lst)

    del model.encoder, model.decoder, model
    torch.cuda.empty_cache()

if __name__ == '__main__':
    wp_audio()

In spite of this works fine, i get some CUDA warnings.

[W CudaIPCTypes.cpp:95] Producer process tried to deallocate over 1000 memory blocks referred by consumer processes. Deallocation might be significantly slowed down. We assume it will never going to be the case, but if it is, please file but to https://github.com/pytorch/pytorch
[W CudaIPCTypes.cpp:15] Producer process has been terminated before all shared CUDA tensors released. See Note [Sharing CUDA tensors]

and hundreds of:

[W CUDAGuardImpl.h:46] Warning: CUDA warning: driver shutting down (function uncheckedGetDevice)
[W CUDAGuardImpl.h:62] Warning: CUDA warning: invalid device ordinal (function uncheckedSetDevice)

with this at the and:

/usr/local/lib/python3.10/multiprocessing/resource_tracker.py:224: UserWarning: resource_tracker: There appear to be 1 leaked semaphore objects to clean up at shutdown
warnings.warn('resource_tracker: There appear to be %d '

But when i use num_proc more than 6, some processes closing before their task finished, with this:

multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/multiprocessing/pool.py", line 125, in worker
    result = (True, func(*args, **kwds))
  File "/usr/local/lib/python3.10/multiprocessing/pool.py", line 48, in mapstar
    return list(map(*args))
  File "/home/user/Projekt/wp_audio_0.2.py", line 24, in whisper_transcribe
    def wp_audio():
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/transcribe.py", line 186, in transcribe
    result: DecodingResult = decode_with_fallback(segment)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/transcribe.py", line 119, in decode_with_fallback
    decode_result = model.decode(segment, options)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
    return func(*args, **kwargs)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/decoding.py", line 712, in decode
    result = DecodingTask(model, options).run(mel)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
    return func(*args, **kwargs)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/decoding.py", line 626, in run
    audio_features: Tensor = self._get_audio_features(mel)  # encoder forward pass
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/decoding.py", line 567, in _get_audio_features
    audio_features = self.model.encoder(mel)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1190, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/model.py", line 156, in forward
    x = block(x)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1190, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/model.py", line 124, in forward
    x = x + self.attn(self.attn_ln(x), mask=mask, kv_cache=kv_cache)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1190, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/model.py", line 85, in forward
    wv = self.qkv_attention(q, k, v, mask)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/whisper/model.py", line 99, in qkv_attention
    w = F.softmax(qk.float(), dim=-1).to(q.dtype)
  File "/home/user/Projekt/.venv/lib/python3.10/site-packages/torch/nn/functional.py", line 1841, in softmax
    ret = input.softmax(dim)
torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 172.00 MiB (GPU 0; 11.76 GiB total capacity; 287.76 MiB already allocated; 205.19 MiB free; 300.00 MiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/user/Projekt/wp_audio_0.2.py", line 60, in <module>
  File "/home/user/Projekt/wp_audio_0.2.py", line 52, in wp_audio
  File "/usr/local/lib/python3.10/multiprocessing/pool.py", line 367, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "/usr/local/lib/python3.10/multiprocessing/pool.py", line 774, in get
    raise self._value
torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 172.00 MiB (GPU 0; 11.76 GiB total capacity; 287.76 MiB already allocated; 205.19 MiB free; 300.00 MiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF
[W CudaIPCTypes.cpp:95] Producer process tried to deallocate over 1000 memory blocks referred by consumer processes. Deallocation might be significantly slowed down. We assume it will never going to be the case, but if it is, please file but to https://github.com/pytorch/pytorch
[W CudaIPCTypes.cpp:15] Producer process has been terminated before all shared CUDA tensors released. See Note [Sharing CUDA tensors]

with hundreds of this:

[W CUDAGuardImpl.h:46] Warning: CUDA warning: driver shutting down (function uncheckedGetDevice)
[W CUDAGuardImpl.h:62] Warning: CUDA warning: invalid device ordinal (function uncheckedSetDevice)

and this at the end:

/usr/local/lib/python3.10/multiprocessing/resource_tracker.py:224: UserWarning: resource_tracker: There appear to be 1 leaked semaphore objects to clean up at shutdown
  warnings.warn('resource_tracker: There appear to be %d '

the error with num_proc more than 6 occur only in the end of the program (when some processes are already finished their task)


问:
Conda error usage and unable to reinstall it
I have an issue with conda. I cant use it so I want to reinstall it. I get the following error as soon as I try to use it.

```<code>ERROR: The install method you used for conda--probably either `pip install conda`
or `easy_install conda`--is not compatible with using conda as an application.
If your intention is to install conda as a standalone application, currently
supported install methods include the Anaconda installer and the miniconda
installer.  You can download the miniconda installer from
https://conda.io/miniconda.html.
</code>```

Also I followed the instructions but still it seems it uses another conda (not standalone version). So that's why I want to reinstall everything. The problem is that I cannot delete the following conda versions from dist-packages.

```<code>Requirement already satisfied: conda in /usr/local/lib/python3.8/dist-packages (4.3.16)
Requirement already satisfied: pycosat>=0.6.1 in /usr/local/lib/python3.8/dist-packages (from conda) (0.6.3)
Requirement already satisfied: ruamel.yaml>=0.11.14 in /usr/local/lib/python3.8/dist-packages (from conda) (0.17.21)
Requirement already satisfied: requests>=2.12.4 in /usr/lib/python3/dist-packages (from conda) (2.22.0)
Requirement already satisfied: ruamel.yaml.clib>=0.2.6; platform_python_implementation == "CPython" and python_version < "3.11" in /usr/local/lib/python3.8/dist-packages (from ruamel.yaml>=0.11.14->conda) (0.2.6)
</code>```

if I use rm -rf conda to remove it, but I get the following error.

```<code>rm: cannot remove 'conda_env/specs/binstar.py': Permission denied
rm: cannot remove 'conda_env/specs/__pycache__/__init__.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/specs/__pycache__/requirements.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/specs/__pycache__/notebook.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/specs/__pycache__/binstar.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/specs/__pycache__/yaml_file.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/specs/notebook.py': Permission denied
rm: cannot remove 'conda_env/specs/yaml_file.py': Permission denied
rm: cannot remove 'conda_env/specs/__init__.py': Permission denied
rm: cannot remove 'conda_env/specs/requirements.py': Permission denied
rm: cannot remove 'conda_env/cli/main_remove.py': Permission denied
rm: cannot remove 'conda_env/cli/main_upload.py': Permission denied
rm: cannot remove 'conda_env/cli/main.py': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/__init__.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_remove.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_create.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/common.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_list.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_attach.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_update.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_export.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_upload.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/main_update.py': Permission denied
rm: cannot remove 'conda_env/cli/main_list.py': Permission denied
rm: cannot remove 'conda_env/cli/main_attach.py': Permission denied
rm: cannot remove 'conda_env/cli/common.py': Permission denied
rm: cannot remove 'conda_env/cli/main_export.py': Permission denied
rm: cannot remove 'conda_env/cli/__init__.py': Permission denied
rm: cannot remove 'conda_env/cli/main_create.py': Permission denied
rm: cannot remove 'conda_env/exceptions.py': Permission denied
rm: cannot remove 'conda_env/__pycache__/__init__.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/__pycache__/yaml.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/__pycache__/env.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/__pycache__/compat.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/__pycache__/exceptions.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/__pycache__/pip_util.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/pip_util.py': Permission denied
rm: cannot remove 'conda_env/env.py': Permission denied
rm: cannot remove 'conda_env/yaml.py': Permission denied
rm: cannot remove 'conda_env/utils/notebooks.py': Permission denied
rm: cannot remove 'conda_env/utils/__pycache__/__init__.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/utils/__pycache__/notebooks.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/utils/__pycache__/uploader.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/utils/uploader.py': Permission denied
rm: cannot remove 'conda_env/utils/__init__.py': Permission denied
rm: cannot remove 'conda_env/__init__.py': Permission denied
rm: cannot remove 'conda_env/compat.py': Permission denied
rm: cannot remove 'conda_env/installers/__pycache__/__init__.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/installers/__pycache__/pip.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/installers/__pycache__/conda.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/installers/__pycache__/base.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/installers/conda.py': Permission denied
rm: cannot remove 'conda_env/installers/pip.py': Permission denied
rm: cannot remove 'conda_env/installers/base.py': Permission denied
rm: cannot remove 'conda_env/installers/__init__.py': Permission denied
</code>```

Apparently I do not have permission to delete the files.
Moreover, I tried to use pip uninstall conda and I get the following:

```<code>Found existing installation: conda 4.3.16
Uninstalling conda-4.3.16:
  Would remove:
    /usr/local/bin/conda
    /usr/local/lib/python3.8/dist-packages/conda-4.3.16.dist-info/*
    /usr/local/lib/python3.8/dist-packages/conda/*
    /usr/local/lib/python3.8/dist-packages/conda_env/*
Proceed (y/n)? y
ERROR: Exception:
Traceback (most recent call last):
  File "/usr/lib/python3.8/shutil.py", line 791, in move
    os.rename(src, real_dst)
PermissionError: [Errno 13] Permission denied: '/usr/local/bin/' -> '/tmp/pip-uninstall-yej0ctsl'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/base_command.py", line 186, in _main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/_internal/commands/uninstall.py", line 78, in run
    uninstall_pathset = req.uninstall(
  File "/usr/lib/python3/dist-packages/pip/_internal/req/req_install.py", line 687, in uninstall
    uninstalled_pathset.remove(auto_confirm, verbose)
  File "/usr/lib/python3/dist-packages/pip/_internal/req/req_uninstall.py", line 394, in remove
    moved.stash(path)
  File "/usr/lib/python3/dist-packages/pip/_internal/req/req_uninstall.py", line 283, in stash
    renames(path, new_path)
  File "/usr/lib/python3/dist-packages/pip/_internal/utils/misc.py", line 334, in renames
    shutil.move(old, new)
  File "/usr/lib/python3.8/shutil.py", line 809, in move
    rmtree(src)
  File "/usr/lib/python3.8/shutil.py", line 718, in rmtree
    _rmtree_safe_fd(fd, path, onerror)
  File "/usr/lib/python3.8/shutil.py", line 675, in _rmtree_safe_fd
    onerror(os.unlink, fullname, sys.exc_info())
  File "/usr/lib/python3.8/shutil.py", line 673, in _rmtree_safe_fd
    os.unlink(entry.name, dir_fd=topfd)
PermissionError: [Errno 13] Permission denied: 'conda'
</code>```

Any clues?

Body:
I have an issue with conda. I cant use it so I want to reinstall it. I get the following error as soon as I try to use it.

ERROR: The install method you used for conda--probably either `pip install conda`
or `easy_install conda`--is not compatible with using conda as an application.
If your intention is to install conda as a standalone application, currently
supported install methods include the Anaconda installer and the miniconda
installer.  You can download the miniconda installer from
https://conda.io/miniconda.html.

Also I followed the instructions but still it seems it uses another conda (not standalone version). So that's why I want to reinstall everything. The problem is that I cannot delete the following conda versions from dist-packages.

Requirement already satisfied: conda in /usr/local/lib/python3.8/dist-packages (4.3.16)
Requirement already satisfied: pycosat>=0.6.1 in /usr/local/lib/python3.8/dist-packages (from conda) (0.6.3)
Requirement already satisfied: ruamel.yaml>=0.11.14 in /usr/local/lib/python3.8/dist-packages (from conda) (0.17.21)
Requirement already satisfied: requests>=2.12.4 in /usr/lib/python3/dist-packages (from conda) (2.22.0)
Requirement already satisfied: ruamel.yaml.clib>=0.2.6; platform_python_implementation == "CPython" and python_version < "3.11" in /usr/local/lib/python3.8/dist-packages (from ruamel.yaml>=0.11.14->conda) (0.2.6)

if I use rm -rf conda to remove it, but I get the following error.

rm: cannot remove 'conda_env/specs/binstar.py': Permission denied
rm: cannot remove 'conda_env/specs/__pycache__/__init__.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/specs/__pycache__/requirements.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/specs/__pycache__/notebook.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/specs/__pycache__/binstar.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/specs/__pycache__/yaml_file.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/specs/notebook.py': Permission denied
rm: cannot remove 'conda_env/specs/yaml_file.py': Permission denied
rm: cannot remove 'conda_env/specs/__init__.py': Permission denied
rm: cannot remove 'conda_env/specs/requirements.py': Permission denied
rm: cannot remove 'conda_env/cli/main_remove.py': Permission denied
rm: cannot remove 'conda_env/cli/main_upload.py': Permission denied
rm: cannot remove 'conda_env/cli/main.py': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/__init__.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_remove.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_create.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/common.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_list.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_attach.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_update.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_export.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/__pycache__/main_upload.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/cli/main_update.py': Permission denied
rm: cannot remove 'conda_env/cli/main_list.py': Permission denied
rm: cannot remove 'conda_env/cli/main_attach.py': Permission denied
rm: cannot remove 'conda_env/cli/common.py': Permission denied
rm: cannot remove 'conda_env/cli/main_export.py': Permission denied
rm: cannot remove 'conda_env/cli/__init__.py': Permission denied
rm: cannot remove 'conda_env/cli/main_create.py': Permission denied
rm: cannot remove 'conda_env/exceptions.py': Permission denied
rm: cannot remove 'conda_env/__pycache__/__init__.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/__pycache__/yaml.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/__pycache__/env.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/__pycache__/compat.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/__pycache__/exceptions.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/__pycache__/pip_util.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/pip_util.py': Permission denied
rm: cannot remove 'conda_env/env.py': Permission denied
rm: cannot remove 'conda_env/yaml.py': Permission denied
rm: cannot remove 'conda_env/utils/notebooks.py': Permission denied
rm: cannot remove 'conda_env/utils/__pycache__/__init__.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/utils/__pycache__/notebooks.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/utils/__pycache__/uploader.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/utils/uploader.py': Permission denied
rm: cannot remove 'conda_env/utils/__init__.py': Permission denied
rm: cannot remove 'conda_env/__init__.py': Permission denied
rm: cannot remove 'conda_env/compat.py': Permission denied
rm: cannot remove 'conda_env/installers/__pycache__/__init__.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/installers/__pycache__/pip.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/installers/__pycache__/conda.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/installers/__pycache__/base.cpython-38.pyc': Permission denied
rm: cannot remove 'conda_env/installers/conda.py': Permission denied
rm: cannot remove 'conda_env/installers/pip.py': Permission denied
rm: cannot remove 'conda_env/installers/base.py': Permission denied
rm: cannot remove 'conda_env/installers/__init__.py': Permission denied

Apparently I do not have permission to delete the files.
Moreover, I tried to use pip uninstall conda and I get the following:

Found existing installation: conda 4.3.16
Uninstalling conda-4.3.16:
  Would remove:
    /usr/local/bin/conda
    /usr/local/lib/python3.8/dist-packages/conda-4.3.16.dist-info/*
    /usr/local/lib/python3.8/dist-packages/conda/*
    /usr/local/lib/python3.8/dist-packages/conda_env/*
Proceed (y/n)? y
ERROR: Exception:
Traceback (most recent call last):
  File "/usr/lib/python3.8/shutil.py", line 791, in move
    os.rename(src, real_dst)
PermissionError: [Errno 13] Permission denied: '/usr/local/bin/' -> '/tmp/pip-uninstall-yej0ctsl'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/base_command.py", line 186, in _main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/_internal/commands/uninstall.py", line 78, in run
    uninstall_pathset = req.uninstall(
  File "/usr/lib/python3/dist-packages/pip/_internal/req/req_install.py", line 687, in uninstall
    uninstalled_pathset.remove(auto_confirm, verbose)
  File "/usr/lib/python3/dist-packages/pip/_internal/req/req_uninstall.py", line 394, in remove
    moved.stash(path)
  File "/usr/lib/python3/dist-packages/pip/_internal/req/req_uninstall.py", line 283, in stash
    renames(path, new_path)
  File "/usr/lib/python3/dist-packages/pip/_internal/utils/misc.py", line 334, in renames
    shutil.move(old, new)
  File "/usr/lib/python3.8/shutil.py", line 809, in move
    rmtree(src)
  File "/usr/lib/python3.8/shutil.py", line 718, in rmtree
    _rmtree_safe_fd(fd, path, onerror)
  File "/usr/lib/python3.8/shutil.py", line 675, in _rmtree_safe_fd
    onerror(os.unlink, fullname, sys.exc_info())
  File "/usr/lib/python3.8/shutil.py", line 673, in _rmtree_safe_fd
    os.unlink(entry.name, dir_fd=topfd)
PermissionError: [Errno 13] Permission denied: 'conda'

Any clues?


问:
Do you know how to build a service in an ionic capacitor ( angular ) that works behind the scenes?
Do you know how to build a service in an ionic capacitor that works behind the scenes and sends requests and will not be seen either on the phone screen or as an open application ( in android)

i want to build a track gps that work behind the scenes
and send get posts every 10 min.
even the app close.

there have different between app and background service?

thenks

i was tried

Foreground Service from https://ionicframework.com/docs/v5/native/foreground-service

```<code>BackgroundMode  from https://ionicframework.com

</code>```

Body:
Do you know how to build a service in an ionic capacitor that works behind the scenes and sends requests and will not be seen either on the phone screen or as an open application ( in android)

i want to build a track gps that work behind the scenes
and send get posts every 10 min.
even the app close.

there have different between app and background service?

thenks

i was tried

Foreground Service from https://ionicframework.com/docs/v5/native/foreground-service

BackgroundMode  from https://ionicframework.com


问:
Why do I get varying variable importance charts when I run code?
Dataset found here.

Why is it that once I run R-Markdown, I get a different variable importance chart on my survival model?

library(randomForestSRC)
library(survival)

ucifile <- "https://archive.ics.uci.edu/ml/machine-learning-databases/00519/heart_failure_clinical_records_dataset.csv"

HF <- read.csv(ucifile, header=TRUE)

HF$anaemia = as.factor(HF$anaemia)
HF$diabetes = factor(HF$diabetes, levels=c(0, 1),
                     labels=c("Absent", "Present"))
HF$hypertension = factor(HF$high_blood_pressure,
                         levels=c(0, 1), labels=c("Absent", "Present"))

HF$sex = factor(HF$sex, levels=c(0, 1), labels=c("Female", "Male"))
HF$smoking = factor(HF$smoking, levels=c(0, 1), labels=c("No", "Yes"))
HF$DEATH_EVENT = as.factor(HF$DEATH_EVENT)

HF <- select(HF, -high_blood_pressure)

set.seed(0)

fit <- rfsrc(Surv(time, DEATH_EVENT) ~ .,
             data = HF,
             ntree = 1000,
             importance = TRUE,
             nsplit = 5)

#fit
plot(fit)
```

I'd like to only get the chart with ONE event-- the first.

OwnerDisplayName: Antonio

Body:
Dataset found here.

Why is it that once I run R-Markdown, I get a different variable importance chart on my survival model?

library(randomForestSRC)
library(survival)

ucifile <- "https://archive.ics.uci.edu/ml/machine-learning-databases/00519/heart_failure_clinical_records_dataset.csv"

HF <- read.csv(ucifile, header=TRUE)

HF$anaemia = as.factor(HF$anaemia)
HF$diabetes = factor(HF$diabetes, levels=c(0, 1),
                     labels=c("Absent", "Present"))
HF$hypertension = factor(HF$high_blood_pressure,
                         levels=c(0, 1), labels=c("Absent", "Present"))

HF$sex = factor(HF$sex, levels=c(0, 1), labels=c("Female", "Male"))
HF$smoking = factor(HF$smoking, levels=c(0, 1), labels=c("No", "Yes"))
HF$DEATH_EVENT = as.factor(HF$DEATH_EVENT)

HF <- select(HF, -high_blood_pressure)

set.seed(0)

fit <- rfsrc(Surv(time, DEATH_EVENT) ~ .,
             data = HF,
             ntree = 1000,
             importance = TRUE,
             nsplit = 5)

#fit
plot(fit)

I'd like to only get the chart with ONE event-- the first.


问:
Connect to SQL Server using GORM and Windows Authentication
I am trying to connect to a SQL Server database using gorm. I am able to connect through Golang datasource with the following connection string:

```<code>jdbc:jtds:sqlserver://{HOST}:1433/{DATABASE_NAME};useNTLMv2=true;domain={DOMAIN};encrypt=true;trustServerCertificate=true;instance={INSTANCE}
</code>```

I am trying the following dsn value in gorm:

```<code>sqlserver://{USER}:{PASS}@{HOST}:1433?database={DATABASE_NAME};trusted+connection=yes
</code>```

But I am getting login failed, am I missing something?

Body:
I am trying to connect to a SQL Server database using gorm. I am able to connect through Golang datasource with the following connection string:

jdbc:jtds:sqlserver://{HOST}:1433/{DATABASE_NAME};useNTLMv2=true;domain={DOMAIN};encrypt=true;trustServerCertificate=true;instance={INSTANCE}

I am trying the following dsn value in gorm:

sqlserver://{USER}:{PASS}@{HOST}:1433?database={DATABASE_NAME};trusted+connection=yes

But I am getting login failed, am I missing something?


问:
Angular RxJS Streams HTTP Request - Show more items
I'm trying to implement the show more button functionality, when you press it should call the api with the next offset and merge the value with the previous result. From what I saw so far I should use the SCAN function, however I'm lost.

When I click show more the offset is updated

```<code>public showMore(offset:number){
  this.offset$.next(offset)
}
</code>```

The api is returning this object

```<code>{
 requestInfo:Info,
 product:Product[]
}
</code>```

Info contains the number of results and the next offset, product contains a list of product (product name, price etc...)

What I tried so far is

```<code>public getProductsV3():Observable<ProductResponseApi>{

const combineLatest$ = combineLatest([this.offset$,this.limit$]).pipe(
  switchMap(([offset,limit])=>this.fetchProductsFromApiV2(offset,limit))
)

return combineLatest$.pipe(
  scan((prev,current)=> {infos:current.infos,products:[...prev.product,...current.products]} )
)
}
</code>```

But obviously it doesn't work

```<code>public getProductsV2():Observable<ProductResponseApi>{

return combineLatest$ = combineLatest([this.offset$,this.limit$]).pipe(
  switchMap(([offset,limit])=>this.fetchProductsFromApiV2(offset,limit))
)

}
</code>```

The version 2 is working, however it shows the next pages without keeping the old values.

The fetchProduct is quite simple

```<code>private fetchProductsFromApiV2(currentOffset:number,limit:number){

const params = new HttpParams().set('offset', currentOffset).set('limit', limit);
return this.http.get<ProductResponseApi>(this.apiUrl+'/products',{params,withCredentials:true});
}
</code>```

Thanks for help

Body:
I'm trying to implement the show more button functionality, when you press it should call the api with the next offset and merge the value with the previous result. From what I saw so far I should use the SCAN function, however I'm lost.

When I click show more the offset is updated

public showMore(offset:number){
  this.offset$.next(offset)
}

The api is returning this object

{
 requestInfo:Info,
 product:Product[]
}

Info contains the number of results and the next offset, product contains a list of product (product name, price etc...)

What I tried so far is

public getProductsV3():Observable<ProductResponseApi>{

const combineLatest$ = combineLatest([this.offset$,this.limit$]).pipe(
  switchMap(([offset,limit])=>this.fetchProductsFromApiV2(offset,limit))
)

return combineLatest$.pipe(
  scan((prev,current)=> {infos:current.infos,products:[...prev.product,...current.products]} )
)
}

But obviously it doesn't work

public getProductsV2():Observable<ProductResponseApi>{

return combineLatest$ = combineLatest([this.offset$,this.limit$]).pipe(
  switchMap(([offset,limit])=>this.fetchProductsFromApiV2(offset,limit))
)

}

The version 2 is working, however it shows the next pages without keeping the old values.

The fetchProduct is quite simple

private fetchProductsFromApiV2(currentOffset:number,limit:number){

const params = new HttpParams().set('offset', currentOffset).set('limit', limit);
return this.http.get<ProductResponseApi>(this.apiUrl+'/products',{params,withCredentials:true});
}

Thanks for help


问:
Unable to return request from simple nestjs
I am running into a weird bug.

For some reason, I can console.log(request) but I cant return the request parameter
here is the code that is giving me an issue.

```<code>import { Controller, Post, Body, Req } from '@nestjs/common';
import  express from 'express';

@Controller('media-alpha')
export class MediaAlphaController {

  @Post('/setflagonbid')
  setFlagsOnBid(
    @Req() request: express.Request
  ) {
    console.log(request); // This works perfect
    return request;  // this line throws an error

  }
}
</code>```

this is the error::

```<code>The inferred type of 'setFlagsOnBid' cannot be named without a reference to '.pnpm/@types+express-serve-static-core@4.17.31/node_modules/@types/express-serve-static-core'. This is likely not portable. A type annotation is necessary.ts(2742)

</code>```

why can I print the request but I cant return it?

Body:
I am running into a weird bug.

For some reason, I can console.log(request) but I cant return the request parameter
here is the code that is giving me an issue.

import { Controller, Post, Body, Req } from '@nestjs/common';
import  express from 'express';

@Controller('media-alpha')
export class MediaAlphaController {

  @Post('/setflagonbid')
  setFlagsOnBid(
    @Req() request: express.Request
  ) {
    console.log(request); // This works perfect
    return request;  // this line throws an error

  }
}

this is the error::

The inferred type of 'setFlagsOnBid' cannot be named without a reference to '.pnpm/@types+express-serve-static-core@4.17.31/node_modules/@types/express-serve-static-core'. This is likely not portable. A type annotation is necessary.ts(2742)

why can I print the request but I cant return it?


问:
I try to be able to load an image in the django admin, but I can't see it when I click
I don't know how to solve it. It's really frustrating. If you managed to help, I would be very grateful.

settings:

```<code>STATIC_URL = '/static/'
MEDIA_URL='Proyectoweb/media/'
MEDIA_ROOT=BASE_DIR / 'Proyecto/media'
</code>```

url:

```<code>from django.urls import path
from ProyectoApp import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

models:

```<code>from django.db import models

# Create your models here.

class Servicio(models.Model):
    titulo=models.CharField(max_length=50)
    contenido=models.CharField(max_length=50)
    imagen=models.ImageField(upload_to='servicios')
    created=models.DateTimeField(auto_now_add=True)
    updated=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name='servicio'
        verbose_name_plural='servicios'

    def __str__(self):
        return self.titulo
</code>```

admin:

```<code>from django.contrib import admin
from .models import  Servicio

# Register your models here.

class ServicioAdmin(admin.ModelAdmin):
    readonly_fields=('created', 'updated')

admin.site.register(Servicio, ServicioAdmin)
</code>```

For some reason, this page asks me for more details, when I think I have already given enough.

I try to be able to load an image in the django admin, but I can't see it when I click....

Body:
I don't know how to solve it. It's really frustrating. If you managed to help, I would be very grateful.

settings:

STATIC_URL = '/static/'
MEDIA_URL='Proyectoweb/media/'
MEDIA_ROOT=BASE_DIR / 'Proyecto/media'

url:

from django.urls import path
from ProyectoApp import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

models:

from django.db import models

# Create your models here.

class Servicio(models.Model):
    titulo=models.CharField(max_length=50)
    contenido=models.CharField(max_length=50)
    imagen=models.ImageField(upload_to='servicios')
    created=models.DateTimeField(auto_now_add=True)
    updated=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name='servicio'
        verbose_name_plural='servicios'

    def __str__(self):
        return self.titulo

admin:

from django.contrib import admin
from .models import  Servicio

# Register your models here.

class ServicioAdmin(admin.ModelAdmin):
    readonly_fields=('created', 'updated')

admin.site.register(Servicio, ServicioAdmin)

For some reason, this page asks me for more details, when I think I have already given enough.

I try to be able to load an image in the django admin, but I can't see it when I click....


问:
(iOS - Spring Boot) Process finished with exit code 130 (interrupted by signal 2: SIGINT)
Background:
I am a beginner at iOS development learning to integrate a Spring Boot rest api with an iOS app built using SwiftUI. My Spring Boot rest api communicates with a Postgres database.

Problem:
Scenario 1:

Step 1: Start spring boot app.

Step 2: Press the button in already running iOS app to execute a POST request. (This works)

Step 3: Close the app on the iPhone and reboot.

Step 4: Repeat Step 2. (Fails: no data fetched from the database)

Scenario 2:

Step 1: Start spring boot app.

Step 2: Start iOS app on iPhone.

Step 2: Press the button in the iOS app to execute a POST request. (Fails: no data fetched from the database)

Scenario 3:

Step 1: Start spring boot app.

Step 2: Press the button in already running iOS app to execute a POST request. (This works and navigates to the next UI View)

Step 3: Press the button to initiate another POST request to a different url. (Fails: no data fetched from the database)

Additional Info:

In each case, following statement is read on the spring boot terminal after failure:
Process finished with exit code 130 (interrupted by signal 2: SIGINT)

I tried debugging the rest api with the iOS app and Postman. The http request is correctly redirected, i.e, the rest api method is executed. However, no data is returned in case of the requests made from the iOS app whereas, the requests from Postman return the correct data.

I have tried googling the answers but couldn't find something that could be of help. Perhaps I'm too naive to understand as a beginner. Could anyone redirect me towards relevant resources to resolve the issue or help me find the problem?

Thanks in advance. :)


问:
Browser fails to set cookies even with Set-Cookie response header
I am trying to get my Express backend to set a site-wide cookie on my NextJS frontend, each of which is running on separate virtual machines. The relevant backend and frontend configurations are:

In the frontend, I initate the following HTTP request:

```<code>fetch('http://192.168.1.<Express virtual machine>:3000/service', {
   method: 'POST',
   headers: {
      'Content-Type': 'application/json'
   },
   body: JSON.stringify({...}),
   credentials: 'include'
}).then(res => res.json()).then(data => {console.log(data)});
</code>```

In the backend, the following Express application is running with a global CORS middleware configured:

```<code>app.use(cors({origin: 'http://192.168.1.<Frontend virtual machine>:3000', credentials: true}));

app.post('/service', (req, res) => {
   res.cookie('token', token, {
      secure: false,
      httpOnly: false,
      sameSite: 'none'
   });
   res.json({...});
});
</code>```

Upon initiating the HTTP request to /service, the Cookies section of my frontend application in the Storage (Firefox) or Application (Chrome) tab shows that there are no cookies set. However, in the network tab, the Cookies tab on my HTTP request shows that there is both a response cookie and a request cookie. The response cookie has path property set to '/' suggesting that it should have been set site-wide.

Body:
I am trying to get my Express backend to set a site-wide cookie on my NextJS frontend, each of which is running on separate virtual machines. The relevant backend and frontend configurations are:

In the frontend, I initate the following HTTP request:

fetch('http://192.168.1.<Express virtual machine>:3000/service', {
   method: 'POST',
   headers: {
      'Content-Type': 'application/json'
   },
   body: JSON.stringify({...}),
   credentials: 'include'
}).then(res => res.json()).then(data => {console.log(data)});

In the backend, the following Express application is running with a global CORS middleware configured:

app.use(cors({origin: 'http://192.168.1.<Frontend virtual machine>:3000', credentials: true}));

app.post('/service', (req, res) => {
   res.cookie('token', token, {
      secure: false,
      httpOnly: false,
      sameSite: 'none'
   });
   res.json({...});
});

Upon initiating the HTTP request to /service, the Cookies section of my frontend application in the Storage (Firefox) or Application (Chrome) tab shows that there are no cookies set. However, in the network tab, the Cookies tab on my HTTP request shows that there is both a response cookie and a request cookie. The response cookie has path property set to '/' suggesting that it should have been set site-wide.


问:
JavaScript Stringify() applies different rules to the key on the same object
I am working on a JSON file generator while everything works fine the final result is not as good as expected

With following stringify function call, following json file would be generated.

```<code>var jsonString = JSON.stringify(object, null, 2);
</code>```
```<code>{
  "key_1": 2397,
  "key_2": "text1",
  "key_3": "text",
  "key_4": [
    "12345",
    "23456"
  ],
  "key_5": [
    0,
    1
  ],
  "key_6": [
    0
  ],
  "key_7": [
    "https://xxxx",
    "https://xxxx"
  ],
  "key_8": "12345",
}

</code>```

In the JSON file I want to make key_5 and key_6 skip the stringify attributes and make it like this

```<code>  "key_5": [0,1],
  "key_6": [0],
</code>```

So the final file would look like this

```<code>{
  "key_1": 2397,
  "key_2": "text1",
  "key_3": "text",
  "key_4": [
    "12345",
    "23456"
  ],
  "key_5": [0,1],
  "key_6": [0],
  "key_7": [
    "https://xxxx",
    "https://xxxx"
  ],
  "key_8": "12345",
}
</code>```

I think it is possible to customized the rule for certain key but I am very new to JS so I am not sure how to do so...

```<code>    jsonString = JSON.stringify(object, (key, value) => {
      if (key === "key_5"||key === "key_6") return Do_something_ELSE;
      return value;
    }, 2);
</code>```

Body:
I am working on a JSON file generator while everything works fine the final result is not as good as expected

With following stringify function call, following json file would be generated.

var jsonString = JSON.stringify(object, null, 2);

{
  "key_1": 2397,
  "key_2": "text1",
  "key_3": "text",
  "key_4": [
    "12345",
    "23456"
  ],
  "key_5": [
    0,
    1
  ],
  "key_6": [
    0
  ],
  "key_7": [
    "https://xxxx",
    "https://xxxx"
  ],
  "key_8": "12345",
}

In the JSON file I want to make key_5 and key_6 skip the stringify attributes and make it like this

  "key_5": [0,1],
  "key_6": [0],

So the final file would look like this

{
  "key_1": 2397,
  "key_2": "text1",
  "key_3": "text",
  "key_4": [
    "12345",
    "23456"
  ],
  "key_5": [0,1],
  "key_6": [0],
  "key_7": [
    "https://xxxx",
    "https://xxxx"
  ],
  "key_8": "12345",
}

I think it is possible to customized the rule for certain key but I am very new to JS so I am not sure how to do so...

    jsonString = JSON.stringify(object, (key, value) => {
      if (key === "key_5"||key === "key_6") return Do_something_ELSE;
      return value;
    }, 2);


问:
problem in downloading zip folder from lambda/node/express api to reactjs app - Window can not open the folder
I run into unknown issue as described below,

I have node/express api which returns data as shown below,

```<code>    ...
    ...
    const zip = new AdmZip();

    // Define zip file name
    const timedate = this.getDateTime();
    let downloadName = `myZip-${timedate}.zip`;
    const data = zip.toBuffer();
    const fileType = 'application/zip';
    res.writeHead(200, {
        'Content-Disposition': `attachment; filename="${downloadName}"`,
        'Content-Type': fileType,
    })
    return res.end(data);
</code>```

ReactApp

```<code>const ReadResponse = async (response: any) => {

    const blob = await response.blob();

    /**
       I can confirm above blob object contains data as shown below

        size:13258
        type:"application/zip"
        [[Prototype]]:Blob

    **/

    const a = document.createElement('a');
    document.body.appendChild(a);

    const url = window.URL.createObjectURL(blob);

    a.href = url;
    const filename = "myZip.zip";
    a.download = filename;
    a.click();
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }, 0)
  };
</code>```

hitting localhost:2000/api/download, it downloads the zip folder and when I open it I can see the content in it.

But the same code when goes to lambda function, hitting whateverdomain/api/download api returns blob response, I can download the zip folder as well but when try to open it, it throws

windows can't open the folder

Tried with different different approaches but can't seem to find reason what's wrong ?

Body:
I run into unknown issue as described below,

I have node/express api which returns data as shown below,

    ...
    ...
    const zip = new AdmZip();

    // Define zip file name
    const timedate = this.getDateTime();
    let downloadName = `myZip-${timedate}.zip`;
    const data = zip.toBuffer();
    const fileType = 'application/zip';
    res.writeHead(200, {
        'Content-Disposition': `attachment; filename="${downloadName}"`,
        'Content-Type': fileType,
    })
    return res.end(data);

ReactApp

const ReadResponse = async (response: any) => {

    const blob = await response.blob();

    /**
       I can confirm above blob object contains data as shown below

        size:13258
        type:"application/zip"
        [[Prototype]]:Blob

    **/

    const a = document.createElement('a');
    document.body.appendChild(a);

    const url = window.URL.createObjectURL(blob);

    a.href = url;
    const filename = "myZip.zip";
    a.download = filename;
    a.click();
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }, 0)
  };

hitting localhost:2000/api/download, it downloads the zip folder and when I open it I can see the content in it.

But the same code when goes to lambda function, hitting whateverdomain/api/download api returns blob response, I can download the zip folder as well but when try to open it, it throws

windows can't open the folder

Tried with different different approaches but can't seem to find reason what's wrong ?


问:
How to append objects to a predefined list based on a metadata variable in R
We have a list which contain sublists, and these sublists contain Seurat objects. In each object metadata we have a variable which we'd like group based on. We'd like to group these objects into a new list based on this variable. Any help on appending objects to a predefined list based on this variable will be appreciated.

To visualise it we have:

```<code>list
 listA
  object1@metadata$variable1["X"]
  object2@metadata$variable1["Y"]
  object3@metadata$variable1["Z"]
  object4@metadata$variable1["X"]
  object5@metadata$variable1["Y"]
 listB
  object1@metadata$variable1["X"]
  object2@metadata$variable1["Y"]
  object3@metadata$variable1["Y"]
 listC
  object1@metadata$variable1["X"]
  object2@metadata$variable1["Y"]
  object3@metadata$variable1["X"]
 listD
  object1@metadata$variable1["X"]
  object2@metadata$variable1["X"]
  object3@metadata$variable1["Z"]
  object4@metadata$variable1["Z"]
</code>```

and we want to append these objects to a new list based on variable1, i.e all the listA variable1["X"] objects together, listA variable1["Y"] objects together, etc.

We've tried to use pmatch to match the string of the metadata variable to the string in the predefined list.

Any other strategies are very much welcome.

Body:
We have a list which contain sublists, and these sublists contain Seurat objects. In each object metadata we have a variable which we'd like group based on. We'd like to group these objects into a new list based on this variable. Any help on appending objects to a predefined list based on this variable will be appreciated.

To visualise it we have:

list
 listA
  object1@metadata$variable1["X"]
  object2@metadata$variable1["Y"]
  object3@metadata$variable1["Z"]
  object4@metadata$variable1["X"]
  object5@metadata$variable1["Y"]
 listB
  object1@metadata$variable1["X"]
  object2@metadata$variable1["Y"]
  object3@metadata$variable1["Y"]
 listC
  object1@metadata$variable1["X"]
  object2@metadata$variable1["Y"]
  object3@metadata$variable1["X"]
 listD
  object1@metadata$variable1["X"]
  object2@metadata$variable1["X"]
  object3@metadata$variable1["Z"]
  object4@metadata$variable1["Z"]

and we want to append these objects to a new list based on variable1, i.e all the listA variable1["X"] objects together, listA variable1["Y"] objects together, etc.

We've tried to use pmatch to match the string of the metadata variable to the string in the predefined list.

Any other strategies are very much welcome.


问:
Kafka topic and configurations and issue after deployment
Once the application is deployed, it will automatically creates the topic with the configurations,

```<code>datatransmit.minioSubJobTopic=datatransmit.asset.subjobs.upload
datatransmit.noOfConsumerInstance=3
datatransmit.corePoolSize=20
datatransmit.maxPoolSize=10
datatransmit.queueCapacity=300
datatransmit.sizeOfPage=1000
</code>```

In the Second deployment if any changes made in the configurations of the existing topic like ,

```<code>datatransmit.noOfConsumerInstance=10
datatransmit.corePoolSize=40
</code>```

and so on....

it is not reflecting the changes, so this application is basically able to create a configuration for the first time ,but if this application wants to modify existing  Topic Configurations, then the second time it is not reflecting the changes made rather it reflects the old configuration itself

Body:
Once the application is deployed, it will automatically creates the topic with the configurations,

datatransmit.minioSubJobTopic=datatransmit.asset.subjobs.upload
datatransmit.noOfConsumerInstance=3
datatransmit.corePoolSize=20
datatransmit.maxPoolSize=10
datatransmit.queueCapacity=300
datatransmit.sizeOfPage=1000

In the Second deployment if any changes made in the configurations of the existing topic like ,

datatransmit.noOfConsumerInstance=10
datatransmit.corePoolSize=40

and so on....

it is not reflecting the changes, so this application is basically able to create a configuration for the first time ,but if this application wants to modify existing  Topic Configurations, then the second time it is not reflecting the changes made rather it reflects the old configuration itself


问:
trimming video using ffmpeg corrupts output video stream
I am using ffmpeg to cut up a long video into sections. Using this command:

```<code>ffmpeg -i "long.mp4" -ss 00:38:25 -to 01:01:11 -c copy "section.mp4"
</code>```

I extracted a couple of different consecutive sections and they are fine. But then I cut out another one and its video stream is bad: just a few static frames are shown. Removing -c copy did not help. What am I doing wrong? TIA

Body:
I am using ffmpeg to cut up a long video into sections. Using this command:

ffmpeg -i "long.mp4" -ss 00:38:25 -to 01:01:11 -c copy "section.mp4"

I extracted a couple of different consecutive sections and they are fine. But then I cut out another one and its video stream is bad: just a few static frames are shown. Removing -c copy did not help. What am I doing wrong? TIA


问:
Java: find combinations of min. 3 elements, found in more than 1 data sets

PROBLEM DESCRIPTION

I try to find combinations of min. 3 fruits, found in more than 1 data sets.

for example, the combination "apple, mandarin, apricot" exists in #2 and #5

its not relevant in exaclty which data set it appears

I just want to determine which fruit combinations of 3 and more fruits occur in multiple data sets

PROBLEM (example)

#1: apple, orange, cherry, pear, coconut

#2: apple, grapefruit, mandarin, banana, mango, kiwi, melon, coconut, orange, apricot

#3: orange, plum, pineapple, kiwi, peach, avocado, apple, coconut

#4: coconut, strawberry, papaya, mandarin, apricot

#5: banana, mango, kiwi, melon, apricot, grapefruit, apple, mandarin, coconut

GOAL (example)

apple, kiwi, coconut

apple, kiwi, coconut, orange

apple, mandarin, apricot

Description

Unfortunately, I never learned such mathematical algorithms, am also not sure if I would really understand them.

After a long research I found the approach with permutation and combination. So I would have to permute the fruits (i.e. create all possible combinations)

```<code>         [apple, orange, cherry]

         [apple, cherry, orange]

         [cherry, apple, orange]

         [cherry, orange, apple]

         [orange, cherry, apple]

         [orange, apple, cherry]
</code>```

and then apply a grouping to all datasets like in SQL. But this will be quite complex.

Another approach would be, but unfortunately I'm not really sure how such sets are working:

Store the elements in a Set<Set>. Sets are unordered, so lookups don't care about the original order within a group.

My hope now is to the great programming language Java with its huge community, that this problem has probably been solved before.

Maybe already solved in a library like

Apache Commons combinationsIterator?

Guava combinations

CombinatoricsLib

Can anyone give me a hint on this one?

Body:
PROBLEM DESCRIPTION

I try to find combinations of min. 3 fruits, found in more than 1 data sets.

for example, the combination "apple, mandarin, apricot" exists in #2 and #5

its not relevant in exaclty which data set it appears

I just want to determine which fruit combinations of 3 and more fruits occur in multiple data sets

PROBLEM (example)

#1: apple, orange, cherry, pear, coconut

#2: apple, grapefruit, mandarin, banana, mango, kiwi, melon, coconut, orange, apricot

#3: orange, plum, pineapple, kiwi, peach, avocado, apple, coconut

#4: coconut, strawberry, papaya, mandarin, apricot

#5: banana, mango, kiwi, melon, apricot, grapefruit, apple, mandarin, coconut

GOAL (example)

apple, kiwi, coconut

apple, kiwi, coconut, orange

apple, mandarin, apricot

Description

Unfortunately, I never learned such mathematical algorithms, am also not sure if I would really understand them.

After a long research I found the approach with permutation and combination. So I would have to permute the fruits (i.e. create all possible combinations)

         [apple, orange, cherry]

         [apple, cherry, orange]

         [cherry, apple, orange]

         [cherry, orange, apple]

         [orange, cherry, apple]

         [orange, apple, cherry]

and then apply a grouping to all datasets like in SQL. But this will be quite complex.

Another approach would be, but unfortunately I'm not really sure how such sets are working:

Store the elements in a Set<Set>. Sets are unordered, so lookups don't care about the original order within a group.

My hope now is to the great programming language Java with its huge community, that this problem has probably been solved before.

Maybe already solved in a library like

Apache Commons combinationsIterator?

Guava combinations

CombinatoricsLib

Can anyone give me a hint on this one?


问:
How to use an inner join of 3 database tables with unique 4 columns in VB.NET
I need to run a query from VB.NET that needs to inner join 3 database tables with 4 unique columns. I have the example below to join 2 tables with 3 unique columns.

update LBSTS as t1
inner join GSDTS as t2 on t1.[PNM] = t2.[PNM] AND t1.[NOD] = t2.[NOD] AND t1.[ITM] = t2.[ITM]
set t1.[CIA] = t2.[CIU]
WHERE t1.PNM=@PNM
```

Given this example data:

TABLE NAME : GSDTS

PNM
ITM
QTY
CIU

1000
TEST R 1001
10
20000

1000
TEST R 1002
20
10000

TABLE NAME : GSGTS

PNM
DTS
SAC

1000
06/12/2022
01-01

TABLE NAME : LBSTS

RFN
DTS
ITEM
QTY
CIA

1000
06/12/2022
TEST R 1001
10
1

1000
06/12/2022
TEST R 1002
20
1

NOTE :
COLUMN SAC IS SAME WITH COLUMN RFN

COLUMN CIU IS SAME WITH COLUMN CIA

SET FOR UPDATE COLUMN CIA

How can I change this to also include the CIA column from the LBSTS table?

this Desired output :

TABLE NAME : GSDTS

PNM
ITM
QTY
CIU

1000
TEST R 1001
10
20000

1000
TEST R 1002
20
10000

TABLE NAME : GSGTS

PNM
DTS
SAC

1000
06/12/2022
01-01

TABLE NAME : LBSTS

RFN
DTS
ITEM
QTY
CIA

1000
06/12/2022
TEST R 1001
10
20000

1000
06/12/2022
TEST R 1002
20
10000

NOTE :
COLUMN SAC IS SAME WITH COLUMN RFN

COLUMN CIU IS SAME WITH COLUMN CIA

SET FOR UPDATE COLUMN CIA

Body:
I need to run a query from VB.NET that needs to inner join 3 database tables with 4 unique columns. I have the example below to join 2 tables with 3 unique columns.

update LBSTS as t1
inner join GSDTS as t2 on t1.[PNM] = t2.[PNM] AND t1.[NOD] = t2.[NOD] AND t1.[ITM] = t2.[ITM]
set t1.[CIA] = t2.[CIU]
WHERE t1.PNM=@PNM

Given this example data:

TABLE NAME : GSDTS

PNM
ITM
QTY
CIU

1000
TEST R 1001
10
20000

1000
TEST R 1002
20
10000

TABLE NAME : GSGTS

PNM
DTS
SAC

1000
06/12/2022
01-01

TABLE NAME : LBSTS

RFN
DTS
ITEM
QTY
CIA

1000
06/12/2022
TEST R 1001
10
1

1000
06/12/2022
TEST R 1002
20
1

NOTE :
COLUMN SAC IS SAME WITH COLUMN RFN

COLUMN CIU IS SAME WITH COLUMN CIA

SET FOR UPDATE COLUMN CIA

How can I change this to also include the CIA column from the LBSTS table?

this Desired output :

TABLE NAME : GSDTS

PNM
ITM
QTY
CIU

1000
TEST R 1001
10
20000

1000
TEST R 1002
20
10000

TABLE NAME : GSGTS

PNM
DTS
SAC

1000
06/12/2022
01-01

TABLE NAME : LBSTS

RFN
DTS
ITEM
QTY
CIA

1000
06/12/2022
TEST R 1001
10
20000

1000
06/12/2022
TEST R 1002
20
10000

NOTE :
COLUMN SAC IS SAME WITH COLUMN RFN

COLUMN CIU IS SAME WITH COLUMN CIA

SET FOR UPDATE COLUMN CIA


问:
SQL Code to eliminate text qualifiers from txt files
Searched existing threads, no answer

I am pulling data from a table and exporting to a CSV file using MYSQLWorkbench (only program compatible with our data system).  I have data that looks like the following:

Item Number
Item Desc

10
HDW Cell

105682
Water Tube

After I export this result to CSV, I then open/save it with notepad as a txt file.  I have to send this data to a vendor performing inventory for our stores, but the txt file looks as follows:

```<code>Item Number, Item Desc
"      10","HDW Cell"
"105682","Water Tube"
</code>```

I need to eliminate the double quotes from the column data somehow, but I cannot change the export file type, and do not want to add a step in the CSV or TXT files to find/replace the quotes.  It also looks like the first text column is adding spaces in front of the 10 to preserve the total number of characters in that column - I need to get rid of this as well.  I need the output data to look like.

```<code>Item Number, Item Desc
10,HDW Cell
105682,Water Tube
</code>```

I am currently using a simple select statement to pull the columns.  For background, this data can have as many as 200,000 + records, so I would like to accomplish as much as I can within the query before exporting the data to CSV.  I would be open to taking the original TXT file and using separate code to remove the text qualifiers.

Thanks

Body:
Searched existing threads, no answer

I am pulling data from a table and exporting to a CSV file using MYSQLWorkbench (only program compatible with our data system).  I have data that looks like the following:

Item Number
Item Desc

10
HDW Cell

105682
Water Tube

After I export this result to CSV, I then open/save it with notepad as a txt file.  I have to send this data to a vendor performing inventory for our stores, but the txt file looks as follows:

Item Number, Item Desc
"      10","HDW Cell"
"105682","Water Tube"

I need to eliminate the double quotes from the column data somehow, but I cannot change the export file type, and do not want to add a step in the CSV or TXT files to find/replace the quotes.  It also looks like the first text column is adding spaces in front of the 10 to preserve the total number of characters in that column - I need to get rid of this as well.  I need the output data to look like.

Item Number, Item Desc
10,HDW Cell
105682,Water Tube

I am currently using a simple select statement to pull the columns.  For background, this data can have as many as 200,000 + records, so I would like to accomplish as much as I can within the query before exporting the data to CSV.  I would be open to taking the original TXT file and using separate code to remove the text qualifiers.

Thanks


问:
LEETCODE #148 Sort List , runtime error: member access within null pointer of type 'struct ListNode'
```<code>struct ListNode* sortList(struct ListNode* head){

    struct ListNode *temp, *change;
    int temp_data;
    temp = head;
    change = head->next;  //<<<<<<<<<<<<<<<<<<

    while(temp)
    {
        change = temp->next;
        while(change)
        {
            if (temp->val > change->val)
            {
                temp_data = temp->val;
                temp->val = change->val;
                change->val = temp_data;
            }

            change = change->next;
        }

        temp = temp->next;
    }

    return head;
}
</code>```

leetcode Link
Given the head of a linked list, return the list after sorting it in ascending order.

I have tried to write that same code in Dev c++, everything seems working.
In the code about I tried to make pointer change to point to the next node in head, and leetcode gave me an error:

```<code>Line 13: Char 12: runtime error: member access within null pointer of type 'struct ListNode' [solution.c]

</code>```

What have caused that error? It not supposed to be error right?

Body:
struct ListNode* sortList(struct ListNode* head){

    struct ListNode *temp, *change;
    int temp_data;
    temp = head;
    change = head->next;  //<<<<<<<<<<<<<<<<<<

    while(temp)
    {
        change = temp->next;
        while(change)
        {
            if (temp->val > change->val)
            {
                temp_data = temp->val;
                temp->val = change->val;
                change->val = temp_data;
            }

            change = change->next;
        }

        temp = temp->next;
    }

    return head;
}

leetcode Link
Given the head of a linked list, return the list after sorting it in ascending order.

I have tried to write that same code in Dev c++, everything seems working.
In the code about I tried to make pointer change to point to the next node in head, and leetcode gave me an error:

Line 13: Char 12: runtime error: member access within null pointer of type 'struct ListNode' [solution.c]

What have caused that error? It not supposed to be error right?


问:
Add label on border PHPSpreadSheet
Is there any way to put a label on the top border like this image? Which way could be the best to have a render like this with PHPspreadsheet?

Thanks in advance.

Title: Add label on border PHPSpreadSheet


Title: Minimum electron package

Body:
I'm trying to distribute an electron browser with a minimal installation.

Its node_module folder seems huge even if the package.json dependecies are just a few:

  "dependencies": {
    "bonjour": "^3.5.0",
    "electron-squirrel-startup": "^1.0.0",
    "node-dns-sd": "^0.4.2",
    "request": "^2.88.2"
  }

After the electron forge build, looking into \resources\app\node_modules I found:

05/12/2022  12:40           198'105 .package-lock.json
05/12/2022  12:44    <DIR>          @electron
05/12/2022  12:44    <DIR>          @electron-forge
05/12/2022  12:44    <DIR>          @gar
05/12/2022  12:44    <DIR>          @malept
05/12/2022  12:44    <DIR>          @nodelib
05/12/2022  12:44    <DIR>          @npmcli
05/12/2022  12:44    <DIR>          @sindresorhus
05/12/2022  12:44    <DIR>          @szmarczak
05/12/2022  12:44    <DIR>          @tootallnate
05/12/2022  12:44    <DIR>          @types
05/12/2022  12:44    <DIR>          ajv
05/12/2022  12:44    <DIR>          array-flatten
05/12/2022  12:44    <DIR>          asn1
05/12/2022  12:44    <DIR>          assert-plus
05/12/2022  12:44    <DIR>          asynckit
05/12/2022  12:44    <DIR>          aws-sign2
05/12/2022  12:44    <DIR>          aws4
05/12/2022  12:44    <DIR>          bcrypt-pbkdf
05/12/2022  12:44    <DIR>          bonjour
05/12/2022  12:44    <DIR>          buffer-indexof
05/12/2022  12:44    <DIR>          call-bind
05/12/2022  12:44    <DIR>          caseless
05/12/2022  12:44    <DIR>          combined-stream
05/12/2022  12:44    <DIR>          core-util-is
05/12/2022  12:44    <DIR>          dashdash
05/12/2022  12:44    <DIR>          deep-equal
05/12/2022  12:44    <DIR>          define-properties
05/12/2022  12:44    <DIR>          delayed-stream
05/12/2022  12:44    <DIR>          dns-equal
05/12/2022  12:44    <DIR>          dns-packet
05/12/2022  12:44    <DIR>          dns-txt
05/12/2022  12:44    <DIR>          ecc-jsbn
05/12/2022  12:44    <DIR>          electron-squirrel-startup
05/12/2022  12:44    <DIR>          extend
05/12/2022  12:44    <DIR>          extsprintf
05/12/2022  12:44    <DIR>          fast-deep-equal
05/12/2022  12:44    <DIR>          fast-json-stable-stringify
05/12/2022  12:44    <DIR>          forever-agent
05/12/2022  12:44    <DIR>          form-data
05/12/2022  12:44    <DIR>          function-bind
05/12/2022  12:44    <DIR>          functions-have-names
05/12/2022  12:44    <DIR>          get-intrinsic
05/12/2022  12:44    <DIR>          getpass
05/12/2022  12:44    <DIR>          har-schema
05/12/2022  12:44    <DIR>          har-validator
05/12/2022  12:44    <DIR>          has
05/12/2022  12:44    <DIR>          has-property-descriptors
05/12/2022  12:44    <DIR>          has-symbols
05/12/2022  12:44    <DIR>          has-tostringtag
05/12/2022  12:44    <DIR>          http-signature
05/12/2022  12:44    <DIR>          ip
05/12/2022  12:44    <DIR>          is-arguments
05/12/2022  12:44    <DIR>          is-date-object
05/12/2022  12:44    <DIR>          is-regex
05/12/2022  12:44    <DIR>          is-typedarray
05/12/2022  12:44    <DIR>          isstream
05/12/2022  12:44    <DIR>          jsbn
05/12/2022  12:44    <DIR>          json-schema
05/12/2022  12:44    <DIR>          json-schema-traverse
05/12/2022  12:44    <DIR>          json-stringify-safe
05/12/2022  12:44    <DIR>          jsprim
05/12/2022  12:44    <DIR>          mime-db
05/12/2022  12:44    <DIR>          mime-types
05/12/2022  12:44    <DIR>          multicast-dns
05/12/2022  12:44    <DIR>          multicast-dns-service-types
05/12/2022  12:44    <DIR>          node-dns-sd
05/12/2022  12:44    <DIR>          oauth-sign
05/12/2022  12:44    <DIR>          object-is
05/12/2022  12:44    <DIR>          object-keys
05/12/2022  12:44    <DIR>          performance-now
05/12/2022  12:44    <DIR>          psl
05/12/2022  12:44    <DIR>          punycode
05/12/2022  12:44    <DIR>          qs
05/12/2022  12:44    <DIR>          regexp.prototype.flags
05/12/2022  12:44    <DIR>          request
05/12/2022  12:44    <DIR>          safe-buffer
05/12/2022  12:44    <DIR>          safer-buffer
05/12/2022  12:44    <DIR>          sshpk
05/12/2022  12:44    <DIR>          thunky
05/12/2022  12:44    <DIR>          tough-cookie
05/12/2022  12:44    <DIR>          tunnel-agent
05/12/2022  12:44    <DIR>          tweetnacl
05/12/2022  12:44    <DIR>          uri-js
05/12/2022  12:44    <DIR>          uuid
05/12/2022  12:44    <DIR>          verror

is this the minimun package for eletron?

I tried to prune and to reinstall electron with --production flag, but it doesn't change.


问:
R - Pad dataframe cell contents depending on contents of other cells
this is a bit of a difficult question to explain so forgive me!

I have an .xcsv file generated from a separate program, this is imported and the data is cleaned (brackets removed, etc.).

This gives me a data.frame that looks as follows:

So we have three columns: length (the length of the object), frames (the frames that the Object is in), and X (the ID assigned to the Object).

Each Object isn't in every frame, for example in the sample image above Object 10 is only is frames 25, 26, 27, 28,...etc. For each Object we have the length of it in each frame, so again for 10 that means in frame 25 it was 47.00475, frame 26 it was 49.68348, etc. etc.

I know how many frames there are in total (45) and how many Objects.

I can separate the lengths using:

```<code>l <- cSplit(df$length, 'length', ',')
l <- t(l)
l <- data.frame(l)
</code>```

However I now want to be able to align where those lengths are in my new data.frame depending on the corresponding frame number - if that makes sense?

For example if we look at the previous image Object 10 in frame 25 is 47.00475,
using the above code we can see in the following image that this value for Object 10 (X10) starts in frame 1, then when all of Object 10s values are given the values change to NA. Ideally, what I want, is for any NA values to only appear on frames that don't have a length and for the length to appear on the frames the are supposed to (according to the corresponding value in the frames column).

My eventual goal is to plot the change in lengths for all Objects over time.

So again my apologies if I haven't been clear. Hopefully I've made sense though! :) If anyone has any ideas or pointers that'd be much appreciated - thanks!

Body:
this is a bit of a difficult question to explain so forgive me!

I have an .xcsv file generated from a separate program, this is imported and the data is cleaned (brackets removed, etc.).

This gives me a data.frame that looks as follows:

So we have three columns: length (the length of the object), frames (the frames that the Object is in), and X (the ID assigned to the Object).

Each Object isn't in every frame, for example in the sample image above Object 10 is only is frames 25, 26, 27, 28,...etc. For each Object we have the length of it in each frame, so again for 10 that means in frame 25 it was 47.00475, frame 26 it was 49.68348, etc. etc.

I know how many frames there are in total (45) and how many Objects.

I can separate the lengths using:

l <- cSplit(df$length, 'length', ',')
l <- t(l)
l <- data.frame(l)

However I now want to be able to align where those lengths are in my new data.frame depending on the corresponding frame number - if that makes sense?

For example if we look at the previous image Object 10 in frame 25 is 47.00475,
using the above code we can see in the following image that this value for Object 10 (X10) starts in frame 1, then when all of Object 10s values are given the values change to NA. Ideally, what I want, is for any NA values to only appear on frames that don't have a length and for the length to appear on the frames the are supposed to (according to the corresponding value in the frames column).

My eventual goal is to plot the change in lengths for all Objects over time.

So again my apologies if I haven't been clear. Hopefully I've made sense though! :) If anyone has any ideas or pointers that'd be much appreciated - thanks!


问:
How does a Blazor app work after publishing?
I've created a simple Blazor WebAssembly application. Everything is fine, but I can't understand how it really works. I published and launched it. What I see in the network tab in the browser is 3 requests:

blazor.webassembly.js - I guess this is the file containing the code responsible for bootstraping the whole application

blazor.boot.json - this file contains information about all the assemblies and the entry point

dotnet.6.0.10.fuzsuyypq1.js - this seems like a file containing the application code. In the network tab, I see that the AJAX requests that my app makes are initiated in this file. However, when I go to that file, I see only just some JavaScript code and a signature block. I don't know what that block means. When I search for some code that I have in my app, I can't find anything. Also, this file is like 56 kB, so it's quite small.

Could you tell me where the application code is located?


问:
How extract and pivot values from PySpark "Array" column?
Let say I have PySpark dataframe where one column is "array" with different number of items, and I need to extract these values and pivot them into the columns:

Here is data pseudo code:

```<code>df[1, ] = [id = (1), tags = (["tag_a", "tag_b"])]
df[2, ] = [id = (2), tags = (["tag_a", "tag_c", "tag_d"])]

Desired output

columns(df_out) = (id, tag_a, tag_b, tag_c, tag_d)

df_out[1, ] = [1, 1, 1, 0, 0]
df_out[2, ] = [2, 1, 0, 1, 1]
</code>```

Any ideas are welcome !

Body:
Let say I have PySpark dataframe where one column is "array" with different number of items, and I need to extract these values and pivot them into the columns:

Here is data pseudo code:

df[1, ] = [id = (1), tags = (["tag_a", "tag_b"])]
df[2, ] = [id = (2), tags = (["tag_a", "tag_c", "tag_d"])]

Desired output

columns(df_out) = (id, tag_a, tag_b, tag_c, tag_d)

df_out[1, ] = [1, 1, 1, 0, 0]
df_out[2, ] = [2, 1, 0, 1, 1]

Any ideas are welcome !


问:
How to create a TABLE from STREAM with PRIMARY KEY in ksqldb
I'm creating a data conversion pipeline that will have MySQL as SOURCE and ElasticSearch as SYNC. My data source is modeled in MySQL like this:

CREATE TABLE `person` (
    `_uid` CHAR(36) NOT NULL PRIMARY KEY,
    `_created` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `_updated` DATETIME(3) NULL,
    `_disabled` DATETIME(3) NULL,
    `name` VARCHAR(100) NOT NULL,
    `age` INT NOT NULL
);
CREATE TABLE `contact_type` (
    `_uid` CHAR(36) NOT NULL PRIMARY KEY,
    `value` VARCHAR(100) NOT NULL
);
CREATE TABLE `person_contact` (
    `_uid` CHAR(36) NOT NULL PRIMARY KEY,
    `_created` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `_updated` DATETIME(3) NULL,
    `_disabled` DATETIME(3) NULL,
    `is_default` TINYINT NOT NULL DEFAULT 0,
    `value` TEXT NOT NULL,
    `contact_type_uid` CHAR(36) NOT NULL,
    `person_uid` CHAR(36) NOT NULL,
    FOREIGN KEY (`contact_type_uid`) REFERENCES `contact_type` (`_uid`),
    FOREIGN KEY (`person_uid`) REFERENCES `person` (`_uid`)
);
```
<p>To import the data into ksqldb I created a connector like this:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE SOURCE CONNECTOR "source-mysql" WITH (
  "connector.class"='io.confluent.connect.jdbc.JdbcSourceConnector',
  "connection.url"='jdbc:mysql://mysql:3306/db',
  "connection.user"='root',
  "connection.password"='root',
  "mode"='bulk',
  "topic.prefix"='source-mysql-'
);
</code>```

And then I created the source's pointing to the topic's like this:

CREATE STREAM "source-mysql-contact_type" (
  "_uid" STRING,
  "value" STRING
) WITH (
  KAFKA_TOPIC='source-mysql-contact_type',
  VALUE_FORMAT='AVRO'
);
```
<p>Next I'm trying to create a table from the STREAM as in the example below:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE "table-mysql-contact_type" WITH (
  KAFKA_TOPIC='table-mysql-contact_type',
  VALUE_FORMAT='AVRO'
) AS SELECT
  "_uid",
  LATEST_BY_OFFSET("value") AS "value"
FROM "source-mysql-contact_type"
GROUP BY "_uid"
EMIT CHANGES;
</code>```

The problem is that with this query I can't define the PRIMARY KEY "_uid" as it is in MySQL.

I also tried to create the table before and do the insert like this:

CREATE TABLE "table-mysql-contact_type" (
  "_uid" STRING PRIMARY KEY,
  "value" STRING
) WITH (
  KAFKA_TOPIC='table-mysql-contact_type',
  VALUE_FORMAT='AVRO'
);
INSERT INTO "table-mysql-contact_type"
SELECT
  "_uid",
  LATEST_BY_OFFSET("value") AS "value"
FROM "source-mysql-contact_type"
GROUP BY "_uid"
EMIT CHANGES;
```
<p>But I'm getting the message:</p>
```Exception while preparing statement: INSERT INTO can only be used to insert
into a stream. table-mysql-contact_type is a table.
```

What do I need to do to be able to create a TABLE that receives data from a STREAM but that I can define the PRIMARY KEY of it?

Body:
I'm creating a data conversion pipeline that will have MySQL as SOURCE and ElasticSearch as SYNC. My data source is modeled in MySQL like this:

CREATE TABLE `person` (
    `_uid` CHAR(36) NOT NULL PRIMARY KEY,
    `_created` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `_updated` DATETIME(3) NULL,
    `_disabled` DATETIME(3) NULL,
    `name` VARCHAR(100) NOT NULL,
    `age` INT NOT NULL
);
CREATE TABLE `contact_type` (
    `_uid` CHAR(36) NOT NULL PRIMARY KEY,
    `value` VARCHAR(100) NOT NULL
);
CREATE TABLE `person_contact` (
    `_uid` CHAR(36) NOT NULL PRIMARY KEY,
    `_created` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `_updated` DATETIME(3) NULL,
    `_disabled` DATETIME(3) NULL,
    `is_default` TINYINT NOT NULL DEFAULT 0,
    `value` TEXT NOT NULL,
    `contact_type_uid` CHAR(36) NOT NULL,
    `person_uid` CHAR(36) NOT NULL,
    FOREIGN KEY (`contact_type_uid`) REFERENCES `contact_type` (`_uid`),
    FOREIGN KEY (`person_uid`) REFERENCES `person` (`_uid`)
);

To import the data into ksqldb I created a connector like this:

CREATE SOURCE CONNECTOR "source-mysql" WITH (
  "connector.class"='io.confluent.connect.jdbc.JdbcSourceConnector',
  "connection.url"='jdbc:mysql://mysql:3306/db',
  "connection.user"='root',
  "connection.password"='root',
  "mode"='bulk',
  "topic.prefix"='source-mysql-'
);

And then I created the source's pointing to the topic's like this:

CREATE STREAM "source-mysql-contact_type" (
  "_uid" STRING,
  "value" STRING
) WITH (
  KAFKA_TOPIC='source-mysql-contact_type',
  VALUE_FORMAT='AVRO'
);

Next I'm trying to create a table from the STREAM as in the example below:

CREATE TABLE "table-mysql-contact_type" WITH (
  KAFKA_TOPIC='table-mysql-contact_type',
  VALUE_FORMAT='AVRO'
) AS SELECT
  "_uid",
  LATEST_BY_OFFSET("value") AS "value"
FROM "source-mysql-contact_type"
GROUP BY "_uid"
EMIT CHANGES;

The problem is that with this query I can't define the PRIMARY KEY "_uid" as it is in MySQL.

I also tried to create the table before and do the insert like this:

CREATE TABLE "table-mysql-contact_type" (
  "_uid" STRING PRIMARY KEY,
  "value" STRING
) WITH (
  KAFKA_TOPIC='table-mysql-contact_type',
  VALUE_FORMAT='AVRO'
);
INSERT INTO "table-mysql-contact_type"
SELECT
  "_uid",
  LATEST_BY_OFFSET("value") AS "value"
FROM "source-mysql-contact_type"
GROUP BY "_uid"
EMIT CHANGES;

But I'm getting the message:

Exception while preparing statement: INSERT INTO can only be used to insert
into a stream. table-mysql-contact_type is a table.

What do I need to do to be able to create a TABLE that receives data from a STREAM but that I can define the PRIMARY KEY of it?


问:
How can user add other users in a react app using firebase
Is it possible a logged in user in a web app to register another user, take the new user id and add it on real-time database. The question is how an 'admin' user can add / manipulate more users.
Thank you!</p>


问:
backwars supremum augmented dickey fuller test in python
hello I wanted to code the backwards supremum augmented dickey fuller test in python. My math is super rusty, so I am not really sure if I got the idea 100% right.
It also results in some errors, where I am not sure how to fix them, not because I don't understand the errors, but more that I don't understand 100% what I am supposed to do here and I don't want to mess things up even further. Could someone help me?</p>
```<code># logP : a pandas series containing log-prices
# minSL: the minimum sample length, used by the final regression
# constant: the regression's time trend component
#     'nc': no time trend, only constant
#     'ct': a constant plus a linear time trend
#     'ctt': a constant plus a second-degree polynomail time trend
# lags: the number of lags used in the ADF specification

import pandas as pd
import numpy as np

def get_bsadf(logP, minSL, constant, lags):
    """
    sadf's inner loop
    """
    y, x= getYX(logP, constant = constant, lags=lags)
    startPoints, bsadf, allADF = range(0, y.shape[0] + lags - minSL + 1), None, []
    for start in startPoints:
        y_, x_ = y[start:], x[start:]
        bMean_, bStd_ = getBetas(y_, x_)
        bMean_, bStd_ = bMean_[0, 0], bStd_[0, 0] ** .5
        allADF.append(bMean_ / bStd_)
        if allADF[-1] > bsadf:
            bsadf = allADF[-1]
    out = {'Time': logP.index[-1], 'gsadf': bsadf}
    return out

def lagDF(series, lags):
    """
    applies lags to series
    """
    df1 = pd.DataFrame()
    if isinstance(lags, int):
        lags = range(lags + 1)
    else:
        lags = [int(lag) for lag in lags]
    for lag in lags:
        df_ = series.shift(lag).copy(deep = True)
        df_.name = str(series.name) + '_' + str(lag)
        df1 = df1.join(df_, how = 'outer')
    return df1

def getYX(series, constant, lags):
    """
    prepares the numpy objects for the recursive tests
    """
    series_ = series.diff().dropna()
    x = lagDF(series_, lags).dropna()
    x.iloc[:, 0] = series.values[-x.shape[0] -1: -1, 0] # lagged level
    y = series_.iloc[-x.shape[0]:].values
    if constant != 'nc':
        x = np.append(x, np.ones((x.shape[0], 1)), axis = 1)
        if constant[:2] == 'ct':
            trend = np.arange(x.shape[0]).reshape(-1, 1)
            x = np.append(x, trend, axis = 1)
        if constant == 'ctt':
            x = np.append(x, trend ** 2, axis = 1)
    return y, x

def getBetas(y, x):
    """
    actual regression
    """
    xy = np.dot(x.T, y)
    xx = np.dot(x.T, x)
    # Check if xx is invertible
    if np.linalg.matrix_rank(xx) < x.shape[1]:
        # Handle case where xx is not invertible
        pass
    else:
        xxinv = np.linalg.inv(xx)
        bMean = np.dot(xxinv, xy)
        err = y - np.dot(x, bMean)
        bVar = np.dot(err.T, err) / (x.shape[0] - x.shape[1]) * xxinv
        return bMean, bVar

def get_bsadf_test_statistics(logP, minSL, constant, lags):
    """
    Computes the bsadf test statistics for each time point in `logP`.
    """
    test_statistics = []
    for i in range(len(logP)):
        logP_ = logP.iloc[:i+1]
        bsadf = get_bsadf(logP_, minSL, constant, lags)
        test_statistics.append(bsadf)
    return test_statistics
</code>```

Body:
hello I wanted to code the backwards supremum augmented dickey fuller test in python. My math is super rusty, so I am not really sure if I got the idea 100% right.
It also results in some errors, where I am not sure how to fix them, not because I don't understand the errors, but more that I don't understand 100% what I am supposed to do here and I don't want to mess things up even further. Could someone help me?

# logP : a pandas series containing log-prices
# minSL: the minimum sample length, used by the final regression
# constant: the regression's time trend component
#     'nc': no time trend, only constant
#     'ct': a constant plus a linear time trend
#     'ctt': a constant plus a second-degree polynomail time trend
# lags: the number of lags used in the ADF specification

import pandas as pd
import numpy as np

def get_bsadf(logP, minSL, constant, lags):
    """
    sadf's inner loop
    """
    y, x= getYX(logP, constant = constant, lags=lags)
    startPoints, bsadf, allADF = range(0, y.shape[0] + lags - minSL + 1), None, []
    for start in startPoints:
        y_, x_ = y[start:], x[start:]
        bMean_, bStd_ = getBetas(y_, x_)
        bMean_, bStd_ = bMean_[0, 0], bStd_[0, 0] ** .5
        allADF.append(bMean_ / bStd_)
        if allADF[-1] > bsadf:
            bsadf = allADF[-1]
    out = {'Time': logP.index[-1], 'gsadf': bsadf}
    return out

def lagDF(series, lags):
    """
    applies lags to series
    """
    df1 = pd.DataFrame()
    if isinstance(lags, int):
        lags = range(lags + 1)
    else:
        lags = [int(lag) for lag in lags]
    for lag in lags:
        df_ = series.shift(lag).copy(deep = True)
        df_.name = str(series.name) + '_' + str(lag)
        df1 = df1.join(df_, how = 'outer')
    return df1

def getYX(series, constant, lags):
    """
    prepares the numpy objects for the recursive tests
    """
    series_ = series.diff().dropna()
    x = lagDF(series_, lags).dropna()
    x.iloc[:, 0] = series.values[-x.shape[0] -1: -1, 0] # lagged level
    y = series_.iloc[-x.shape[0]:].values
    if constant != 'nc':
        x = np.append(x, np.ones((x.shape[0], 1)), axis = 1)
        if constant[:2] == 'ct':
            trend = np.arange(x.shape[0]).reshape(-1, 1)
            x = np.append(x, trend, axis = 1)
        if constant == 'ctt':
            x = np.append(x, trend ** 2, axis = 1)
    return y, x

def getBetas(y, x):
    """
    actual regression
    """
    xy = np.dot(x.T, y)
    xx = np.dot(x.T, x)
    # Check if xx is invertible
    if np.linalg.matrix_rank(xx) < x.shape[1]:
        # Handle case where xx is not invertible
        pass
    else:
        xxinv = np.linalg.inv(xx)
        bMean = np.dot(xxinv, xy)
        err = y - np.dot(x, bMean)
        bVar = np.dot(err.T, err) / (x.shape[0] - x.shape[1]) * xxinv
        return bMean, bVar

def get_bsadf_test_statistics(logP, minSL, constant, lags):
    """
    Computes the bsadf test statistics for each time point in `logP`.
    """
    test_statistics = []
    for i in range(len(logP)):
        logP_ = logP.iloc[:i+1]
        bsadf = get_bsadf(logP_, minSL, constant, lags)
        test_statistics.append(bsadf)
    return test_statistics


问:
Substring error on last run of string loop
I made this code to make a triangle out of a string that the user inputs.

```<code>import java.util.Scanner;
public class NameTriangle
{
   public static void main(String args[])
   {
      Scanner keyboard = new Scanner(System.in);
      System.out.print("Please enter a word or phrase: ");
      String name = keyboard.nextLine();
      int b = 0;
      int len2 = name.length();
      int sub = 0;
      int count = 0;
      System.out.println("");
      for(int len = name.length(); sub <= len; sub++)
      {
           String namesub = name.substring(sub, len-count);
           int sublen = namesub.length();
           for(int i = len2; b <= count + i - sublen; b += 3)
           {
              System.out.print(" ");
           }
           System.out.println(namesub);
           b = 0;
           count++;
      }
   }
}
</code>```

**It works perfectly until the very last time it loops. When it tries to loop the last time I get this error: **

```<code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 10, end 8, length 18
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3410)
    at java.base/java.lang.String.substring(String.java:1883)
    at NameTriangle.main(NameTriangle.java:16)
</code>```

**I tried to add and subtract 1 from sub and len in the substring and it either crashed on the first loop with the same error as before or offsets the string and loops until it gets to the last loop and results in the same error. I tried messing around with the boolean statement in the first for loop but it ran nothing after I entered the string value.

I think it's very close to working and I'm just overlooking something simple but any help would be appreciated. **

Body:
I made this code to make a triangle out of a string that the user inputs.

import java.util.Scanner;
public class NameTriangle
{
   public static void main(String args[])
   {
      Scanner keyboard = new Scanner(System.in);
      System.out.print("Please enter a word or phrase: ");
      String name = keyboard.nextLine();
      int b = 0;
      int len2 = name.length();
      int sub = 0;
      int count = 0;
      System.out.println("");
      for(int len = name.length(); sub <= len; sub++)
      {
           String namesub = name.substring(sub, len-count);
           int sublen = namesub.length();
           for(int i = len2; b <= count + i - sublen; b += 3)
           {
              System.out.print(" ");
           }
           System.out.println(namesub);
           b = 0;
           count++;
      }
   }
}

**It works perfectly until the very last time it loops. When it tries to loop the last time I get this error: **

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 10, end 8, length 18
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3410)
    at java.base/java.lang.String.substring(String.java:1883)
    at NameTriangle.main(NameTriangle.java:16)

**I tried to add and subtract 1 from sub and len in the substring and it either crashed on the first loop with the same error as before or offsets the string and loops until it gets to the last loop and results in the same error. I tried messing around with the boolean statement in the first for loop but it ran nothing after I entered the string value.

I think it's very close to working and I'm just overlooking something simple but any help would be appreciated. **