问:
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False, Dataloader Error, and setting pin_memory=False
I am a beginner trying to evaluate this video object segmentation network paper.

When following the instructions on https://github.com/seoungwugoh/STM

It says the requirements are as follows:-

```<code>python 3.6
pytorch 1.0.1.post2
numpy, opencv, pillow
</code>```

I couldn't get this pytorch version to install, so I installed the conda-forge pytorch version 1.5.

and I run this command in either Windows 10 or Ubuntu 16.04 using Anaconda

```<code>(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ python eval_DAVIS.py -g '1' -s val -y 16 -D ../DAVISSemiSupervisedTrainVal480
</code>```

after doing pip install matplotlib, and pip install tqdm ...

I get the following error message:-

Space-time Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Traceback (most recent call last):

File "eval_DAVIS.py", line 111, in
  model.load_state_dict(torch.load(pth_path))

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 593, in load
  return _legacy_load(opened_file, map_location, pickle_module, **pickle_load_args)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 773, in _legacy_load
  result = unpickler.load()

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 729, in persistent_load

deserialized_objects[root_key] = restore_location(obj, location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 178, in default_restore_location
  result = fn(storage, location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 154, in _cuda_deserialize
    device = validate_cuda_device(location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 138, in validate_cuda_device raise RuntimeError('Attempting to deserialize object on a CUDA '

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU

My Graphics Card Driver, and System and Packages are as follows:-

```<code>(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ nvidia-smi
</code>```

```<code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.64.00    Driver Version: 440.64.00    CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1070    Off  | 00000000:01:00.0  On |                  N/A |
| 26%   34C    P8    10W / 151W |    392MiB /  8118MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1247      G   /usr/lib/xorg/Xorg                           229MiB |
|    0      2239      G   compiz                                       126MiB |
|    0      9385      G   /usr/lib/firefox/firefox                       2MiB |
|    0     11686      G   /proc/self/exe                                30MiB |
+-----------------------------------------------------------------------------+
</code>```

I also tried this

```<code>(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ python -c 'import torch; print(torch.rand(2,3).cuda())'
</code>```

tensor([[0.9178, 0.8239, 0.4761],
        [0.9429, 0.8877, 0.0097]], device='cuda:0')

Which shows that cuda is working here

```<code>(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ conda info
    active environment : STMVOS
    active env location : /home/oneworld/anaconda3/envs/STMVOS
            shell level : 1
       user config file : /home/oneworld/.condarc
 populated config files :
          conda version : 4.8.2
    conda-build version : 3.18.11
         python version : 3.7.6.final.0
       virtual packages : __cuda=10.2
                          __glibc=2.23
       base environment : /home/oneworld/anaconda3  (writable)
           channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /home/oneworld/anaconda3/pkgs
                          /home/oneworld/.conda/pkgs
       envs directories : /home/oneworld/anaconda3/envs
                          /home/oneworld/.conda/envs
               platform : linux-64
             user-agent : conda/4.8.2 requests/2.22.0 CPython/3.7.6 Linux/4.4.0-179-generic ubuntu/16.04.6 glibc/2.23
                UID:GID : 1000:1000
             netrc file : None
           offline mode : False
</code>```

```<code>(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ conda list
</code>```

packages in environment at /home/oneworld/anaconda3/envs/STMVOS:

Name                    Version                   Build  Channel
_libgcc_mutex             0.1                        main

blas                      1.0                         mkl

bzip2                     1.0.8                h516909a_2    conda-forge
ca-certificates           2020.4.5.1           hecc5488_0    conda-forge
cairo                     1.16.0            hcf35c78_1003    conda-forge
certifi                   2020.4.5.1               py38_0

cudatoolkit               10.2.89              hfd86e86_1

cycler                    0.10.0                   pypi_0    pypi
dbus                      1.13.6               he372182_0    conda-forge
expat                     2.2.9                he1b5a44_2    conda-forge
ffmpeg                    4.2.3                h167e202_0    conda-forge
fontconfig                2.13.1            h86ecdb6_1001    conda-forge
freetype                  2.9.1                h8a8886c_1

gettext                   0.19.8.1          hc5be6a0_1002    conda-forge
giflib                    5.2.1                h516909a_2    conda-forge
glib                      2.64.3               h6f030ca_0    conda-forge
gmp                       6.2.0                he1b5a44_2    conda-forge
gnutls                    3.6.5             hd3a4fd2_1002    conda-forge
graphite2                 1.3.13            he1b5a44_1001    conda-forge
gst-plugins-base          1.14.5               h0935bb2_2    conda-forge
gstreamer                 1.14.5               h36ae1b5_2    conda-forge
harfbuzz                  2.4.0                h9f30f68_3    conda-forge
hdf5                      1.10.6          nompi_h3c11f04_100    conda-forge
icu                       64.2                 he1b5a44_1    conda-forge
intel-openmp              2020.1                      217

jasper                    1.900.1           h07fcdf6_1006    conda-forge
jpeg                      9c                h14c3975_1001    conda-forge
kiwisolver                1.2.0                    pypi_0    pypi
lame                      3.100             h14c3975_1001    conda-forge
ld_impl_linux-64          2.33.1               h53a641e_7

libblas                   3.8.0                    15_mkl    conda-forge
libcblas                  3.8.0                    15_mkl    conda-forge
libclang                  9.0.1           default_hde54327_0    conda-forge
libedit                   3.1.20181209         hc058e9b_0

libffi                    3.2.1             he1b5a44_1007    conda-forge
libgcc-ng                 9.1.0                hdf63c60_0

libgfortran-ng            7.3.0                hdf63c60_0

libiconv                  1.15              h516909a_1006    conda-forge
liblapack                 3.8.0                    15_mkl    conda-forge
liblapacke                3.8.0                    15_mkl    conda-forge
libllvm9                  9.0.1                he513fc3_1    conda-forge
libopencv                 4.2.0                    py38_6    conda-forge
libpng                    1.6.37               hbc83047_0

libstdcxx-ng              9.1.0                hdf63c60_0

libtiff                   4.1.0                h2733197_0

libuuid                   2.32.1            h14c3975_1000    conda-forge
libwebp                   1.0.2                h56121f0_5    conda-forge
libxcb                    1.13              h14c3975_1002    conda-forge
libxkbcommon              0.10.0               he1b5a44_0    conda-forge
libxml2                   2.9.10               hee79883_0    conda-forge
matplotlib                3.2.1                    pypi_0    pypi
mkl                       2020.1                      217

mkl-service               2.3.0            py38he904b0f_0

mkl_fft                   1.0.15           py38ha843d7b_0

mkl_random                1.1.1            py38h0573a6f_0

ncurses                   6.2                  he6710b0_1

nettle                    3.4.1             h1bed415_1002    conda-forge
ninja                     1.9.0            py38hfd86e86_0

nspr                      4.25                 he1b5a44_0    conda-forge
nss                       3.47                 he751ad9_0    conda-forge
numpy                     1.18.1           py38h4f9e942_0

numpy-base                1.18.1           py38hde5b4d6_1

olefile                   0.46                       py_0

opencv                    4.2.0                    py38_6    conda-forge
openh264                  2.1.1                h8b12597_0    conda-forge
openssl                   1.1.1g               h516909a_0    conda-forge
pcre                      8.44                 he1b5a44_0    conda-forge
pillow                    7.1.2            py38hb39fc2d_0

pip                       20.0.2                   py38_3

pixman                    0.38.0            h516909a_1003    conda-forge
pthread-stubs             0.4               h14c3975_1001    conda-forge
py-opencv                 4.2.0            py38h23f93f0_6    conda-forge
pyparsing                 2.4.7                    pypi_0    pypi
python                    3.8.1                h0371630_1

python-dateutil           2.8.1                    pypi_0    pypi
python_abi                3.8                      1_cp38    conda-forge
pytorch                   1.5.0           py3.8_cuda10.2.89_cudnn7.6.5_0    pytorch
qt                        5.12.5               hd8c4c69_1    conda-forge
readline                  7.0                  h7b6447c_5

setuptools                46.4.0                   py38_0

six                       1.14.0                   py38_0

sqlite                    3.31.1               h62c20be_1

tk                        8.6.8                hbc83047_0

torchvision               0.6.0                py38_cu102    pytorch
tqdm                      4.46.0                   pypi_0    pypi
wheel                     0.34.2                   py38_0

x264                      1!152.20180806       h14c3975_0    conda-forge
xorg-kbproto              1.0.7             h14c3975_1002    conda-forge
xorg-libice               1.0.10               h516909a_0    conda-forge
xorg-libsm                1.2.3             h84519dc_1000    conda-forge
xorg-libx11               1.6.9                h516909a_0    conda-forge
xorg-libxau               1.0.9                h14c3975_0    conda-forge
xorg-libxdmcp             1.1.3                h516909a_0    conda-forge
xorg-libxext              1.3.4                h516909a_0    conda-forge
xorg-libxrender           0.9.10            h516909a_1002    conda-forge
xorg-renderproto          0.11.1            h14c3975_1002    conda-forge
xorg-xextproto            7.3.0             h14c3975_1002    conda-forge
xorg-xproto               7.0.31            h14c3975_1007    conda-forge
xz                        5.2.5                h7b6447c_0

zlib                      1.2.11               h7b6447c_3

zstd                      1.3.7                h0b5b093_0

The code it gets stuck on in eval_DAVIS.py is as follows:-

```<code>print('Loading weights:', pth_path)
model.load_state_dict(torch.load(pth_path))
</code>```

I am using Ubuntu 16.04, however I tried a similar setup in windows 10 and received the same error messages.

Any help much appreciated.

Kind regards

OneWorld

答:
So because of the error, and recommendation that Python threw up.

```<code>RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU
</code>```

I tried editing the code on line 111 in eval_DAVIS.py from this

```<code>model.load_state_dict(torch.load(pth_path))
</code>```

to this

```<code>model.load_state_dict(torch.load(pth_path, map_location=torch.device('cpu')))
</code>```

and then reran the code.

```<code>(STMVOS) C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS>python eval_DAVIS.py -g '0' -s val -y 17 -D C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\DAVIS2017SemiSupervisedTrainVal480
</code>```

which gets through the weights loading.

```<code>Space-Time Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Start Testing: STM_DAVIS_17val
Space-Time Memory Networks: initialized.
STM : Testing on DAVIS
Space-Time Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Loading weights: STM_weights.pth
</code>```

However, when it starts testing, it has the following error:-

```<code>Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 125, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 265, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 326, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main
    raise RunTimeError('''
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 125, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 265, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 326, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main
    raise RunTimeError('''
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Traceback (most recent call last):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 761, in _try_get_data
    data = self._data_queue.get(OneWorldeout=OneWorldeout)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\queues.py", line 108, in get
    raise Empty
_queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 345, in __next__
    data = self._next_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 841, in _next_data
    idx, data = self._get_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 808, in _get_data
    success, data = self._try_get_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 774, in _try_get_data
    raise RunTimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str))
RunTimeError: DataLoader worker (pid(s) 2412, 15788) exited unexpectedly
</code>```

This was using Anaconda, so the error below is just using windows command console, and pip

```<code>(env) C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS>python eval_DAVIS.py -g '0' -s val -y 17 -D C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\DAVIS2017SemiSupervisedTrainVal480
Space-OneWorlde Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Start Testing: STM_DAVIS_17val
Space-OneWorlde Memory Networks: initialized.
STM : Testing on DAVIS
Space-OneWorlde Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Loading weights: STM_weights.pth
Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 114, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 225, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 112, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\popen_spawn_win32.py", line 46, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    is not going to be frozen to produce an executable.''')
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 114, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 225, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 112, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\popen_spawn_win32.py", line 46, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    is not going to be frozen to produce an executable.''')
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Traceback (most recent call last):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 761, in _try_get_data
    data = self._data_queue.get(Timeout=Timeout)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\queues.py", line 105, in get
    raise Empty
_queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 345, in __next__
    data = self._next_data()
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 841, in _next_data
    idx, data = self._get_data()
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 808, in _get_data
    success, data = self._try_get_data()
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 774, in _try_get_data
    raise RunOneWorldeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str))
RunTimeError: DataLoader worker (pid(s) 11448, 16644) exited unexpectedly
</code>```

I also put this code in a small file called CUDATest.py to test that torch would do a simple matrix multiplication function.

```<code># testing CUDA
import torch
device = torch.cuda.current_device()

n = 10
# 1D inputs, same as torch.dot
a = torch.rand(n).to(device)
b = torch.rand(n).to(device)
result = torch.matmul(a, b) # torch.Size([])

print("matmul result = ", result)
</code>```

I ran the code as follows:-

```<code>(env)C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS>python CUDATest.py
</code>```

The result was as follows:-

```<code>matmul result =  tensor(2.4603, device='cuda:0')
</code>```

This suggests that my CUDA and Pytorch is working fine.

Body:
I am a beginner trying to evaluate this video object segmentation network paper.

When following the instructions on https://github.com/seoungwugoh/STM

It says the requirements are as follows:-

python 3.6
pytorch 1.0.1.post2
numpy, opencv, pillow

I couldn't get this pytorch version to install, so I installed the conda-forge pytorch version 1.5.

and I run this command in either Windows 10 or Ubuntu 16.04 using Anaconda

(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ python eval_DAVIS.py -g '1' -s val -y 16 -D ../DAVISSemiSupervisedTrainVal480

after doing pip install matplotlib, and pip install tqdm ...

I get the following error message:-

Space-time Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Traceback (most recent call last):

File "eval_DAVIS.py", line 111, in
  model.load_state_dict(torch.load(pth_path))

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 593, in load
  return _legacy_load(opened_file, map_location, pickle_module, **pickle_load_args)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 773, in _legacy_load
  result = unpickler.load()

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 729, in persistent_load

deserialized_objects[root_key] = restore_location(obj, location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 178, in default_restore_location
  result = fn(storage, location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 154, in _cuda_deserialize
    device = validate_cuda_device(location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 138, in validate_cuda_device raise RuntimeError('Attempting to deserialize object on a CUDA '

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU

My Graphics Card Driver, and System and Packages are as follows:-

(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ nvidia-smi

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.64.00    Driver Version: 440.64.00    CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1070    Off  | 00000000:01:00.0  On |                  N/A |
| 26%   34C    P8    10W / 151W |    392MiB /  8118MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1247      G   /usr/lib/xorg/Xorg                           229MiB |
|    0      2239      G   compiz                                       126MiB |
|    0      9385      G   /usr/lib/firefox/firefox                       2MiB |
|    0     11686      G   /proc/self/exe                                30MiB |
+-----------------------------------------------------------------------------+

I also tried this

(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ python -c 'import torch; print(torch.rand(2,3).cuda())'

tensor([[0.9178, 0.8239, 0.4761],
        [0.9429, 0.8877, 0.0097]], device='cuda:0')

Which shows that cuda is working here

(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ conda info
    active environment : STMVOS
    active env location : /home/oneworld/anaconda3/envs/STMVOS
            shell level : 1
       user config file : /home/oneworld/.condarc
 populated config files :
          conda version : 4.8.2
    conda-build version : 3.18.11
         python version : 3.7.6.final.0
       virtual packages : __cuda=10.2
                          __glibc=2.23
       base environment : /home/oneworld/anaconda3  (writable)
           channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /home/oneworld/anaconda3/pkgs
                          /home/oneworld/.conda/pkgs
       envs directories : /home/oneworld/anaconda3/envs
                          /home/oneworld/.conda/envs
               platform : linux-64
             user-agent : conda/4.8.2 requests/2.22.0 CPython/3.7.6 Linux/4.4.0-179-generic ubuntu/16.04.6 glibc/2.23
                UID:GID : 1000:1000
             netrc file : None
           offline mode : False

(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ conda list

packages in environment at /home/oneworld/anaconda3/envs/STMVOS:

Name                    Version                   Build  Channel
_libgcc_mutex             0.1                        main

blas                      1.0                         mkl

bzip2                     1.0.8                h516909a_2    conda-forge
ca-certificates           2020.4.5.1           hecc5488_0    conda-forge
cairo                     1.16.0            hcf35c78_1003    conda-forge
certifi                   2020.4.5.1               py38_0

cudatoolkit               10.2.89              hfd86e86_1

cycler                    0.10.0                   pypi_0    pypi
dbus                      1.13.6               he372182_0    conda-forge
expat                     2.2.9                he1b5a44_2    conda-forge
ffmpeg                    4.2.3                h167e202_0    conda-forge
fontconfig                2.13.1            h86ecdb6_1001    conda-forge
freetype                  2.9.1                h8a8886c_1

gettext                   0.19.8.1          hc5be6a0_1002    conda-forge
giflib                    5.2.1                h516909a_2    conda-forge
glib                      2.64.3               h6f030ca_0    conda-forge
gmp                       6.2.0                he1b5a44_2    conda-forge
gnutls                    3.6.5             hd3a4fd2_1002    conda-forge
graphite2                 1.3.13            he1b5a44_1001    conda-forge
gst-plugins-base          1.14.5               h0935bb2_2    conda-forge
gstreamer                 1.14.5               h36ae1b5_2    conda-forge
harfbuzz                  2.4.0                h9f30f68_3    conda-forge
hdf5                      1.10.6          nompi_h3c11f04_100    conda-forge
icu                       64.2                 he1b5a44_1    conda-forge
intel-openmp              2020.1                      217

jasper                    1.900.1           h07fcdf6_1006    conda-forge
jpeg                      9c                h14c3975_1001    conda-forge
kiwisolver                1.2.0                    pypi_0    pypi
lame                      3.100             h14c3975_1001    conda-forge
ld_impl_linux-64          2.33.1               h53a641e_7

libblas                   3.8.0                    15_mkl    conda-forge
libcblas                  3.8.0                    15_mkl    conda-forge
libclang                  9.0.1           default_hde54327_0    conda-forge
libedit                   3.1.20181209         hc058e9b_0

libffi                    3.2.1             he1b5a44_1007    conda-forge
libgcc-ng                 9.1.0                hdf63c60_0

libgfortran-ng            7.3.0                hdf63c60_0

libiconv                  1.15              h516909a_1006    conda-forge
liblapack                 3.8.0                    15_mkl    conda-forge
liblapacke                3.8.0                    15_mkl    conda-forge
libllvm9                  9.0.1                he513fc3_1    conda-forge
libopencv                 4.2.0                    py38_6    conda-forge
libpng                    1.6.37               hbc83047_0

libstdcxx-ng              9.1.0                hdf63c60_0

libtiff                   4.1.0                h2733197_0

libuuid                   2.32.1            h14c3975_1000    conda-forge
libwebp                   1.0.2                h56121f0_5    conda-forge
libxcb                    1.13              h14c3975_1002    conda-forge
libxkbcommon              0.10.0               he1b5a44_0    conda-forge
libxml2                   2.9.10               hee79883_0    conda-forge
matplotlib                3.2.1                    pypi_0    pypi
mkl                       2020.1                      217

mkl-service               2.3.0            py38he904b0f_0

mkl_fft                   1.0.15           py38ha843d7b_0

mkl_random                1.1.1            py38h0573a6f_0

ncurses                   6.2                  he6710b0_1

nettle                    3.4.1             h1bed415_1002    conda-forge
ninja                     1.9.0            py38hfd86e86_0

nspr                      4.25                 he1b5a44_0    conda-forge
nss                       3.47                 he751ad9_0    conda-forge
numpy                     1.18.1           py38h4f9e942_0

numpy-base                1.18.1           py38hde5b4d6_1

olefile                   0.46                       py_0

opencv                    4.2.0                    py38_6    conda-forge
openh264                  2.1.1                h8b12597_0    conda-forge
openssl                   1.1.1g               h516909a_0    conda-forge
pcre                      8.44                 he1b5a44_0    conda-forge
pillow                    7.1.2            py38hb39fc2d_0

pip                       20.0.2                   py38_3

pixman                    0.38.0            h516909a_1003    conda-forge
pthread-stubs             0.4               h14c3975_1001    conda-forge
py-opencv                 4.2.0            py38h23f93f0_6    conda-forge
pyparsing                 2.4.7                    pypi_0    pypi
python                    3.8.1                h0371630_1

python-dateutil           2.8.1                    pypi_0    pypi
python_abi                3.8                      1_cp38    conda-forge
pytorch                   1.5.0           py3.8_cuda10.2.89_cudnn7.6.5_0    pytorch
qt                        5.12.5               hd8c4c69_1    conda-forge
readline                  7.0                  h7b6447c_5

setuptools                46.4.0                   py38_0

six                       1.14.0                   py38_0

sqlite                    3.31.1               h62c20be_1

tk                        8.6.8                hbc83047_0

torchvision               0.6.0                py38_cu102    pytorch
tqdm                      4.46.0                   pypi_0    pypi
wheel                     0.34.2                   py38_0

x264                      1!152.20180806       h14c3975_0    conda-forge
xorg-kbproto              1.0.7             h14c3975_1002    conda-forge
xorg-libice               1.0.10               h516909a_0    conda-forge
xorg-libsm                1.2.3             h84519dc_1000    conda-forge
xorg-libx11               1.6.9                h516909a_0    conda-forge
xorg-libxau               1.0.9                h14c3975_0    conda-forge
xorg-libxdmcp             1.1.3                h516909a_0    conda-forge
xorg-libxext              1.3.4                h516909a_0    conda-forge
xorg-libxrender           0.9.10            h516909a_1002    conda-forge
xorg-renderproto          0.11.1            h14c3975_1002    conda-forge
xorg-xextproto            7.3.0             h14c3975_1002    conda-forge
xorg-xproto               7.0.31            h14c3975_1007    conda-forge
xz                        5.2.5                h7b6447c_0

zlib                      1.2.11               h7b6447c_3

zstd                      1.3.7                h0b5b093_0

The code it gets stuck on in eval_DAVIS.py is as follows:-

print('Loading weights:', pth_path)
model.load_state_dict(torch.load(pth_path))

I am using Ubuntu 16.04, however I tried a similar setup in windows 10 and received the same error messages.

Any help much appreciated.

Kind regards

OneWorld

Body:
So because of the error, and recommendation that Python threw up.

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU

I tried editing the code on line 111 in eval_DAVIS.py from this

model.load_state_dict(torch.load(pth_path))

to this

model.load_state_dict(torch.load(pth_path, map_location=torch.device('cpu')))

and then reran the code.

(STMVOS) C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS>python eval_DAVIS.py -g '0' -s val -y 17 -D C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\DAVIS2017SemiSupervisedTrainVal480

which gets through the weights loading.

Space-Time Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Start Testing: STM_DAVIS_17val
Space-Time Memory Networks: initialized.
STM : Testing on DAVIS
Space-Time Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Loading weights: STM_weights.pth

However, when it starts testing, it has the following error:-

Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 125, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 265, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 326, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main
    raise RunTimeError('''
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 116, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 125, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 236, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 287, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 265, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 97, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\context.py", line 326, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\popen_spawn_win32.py", line 45, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 154, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\spawn.py", line 134, in _check_not_importing_main
    raise RunTimeError('''
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Traceback (most recent call last):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 761, in _try_get_data
    data = self._data_queue.get(OneWorldeout=OneWorldeout)
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\multiprocessing\queues.py", line 108, in get
    raise Empty
_queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 345, in __next__
    data = self._next_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 841, in _next_data
    idx, data = self._get_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 808, in _get_data
    success, data = self._try_get_data()
  File "C:\Users\OneWorld\anaconda3\envs\STMVOS\lib\site-packages\torch\utils\data\dataloader.py", line 774, in _try_get_data
    raise RunTimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str))
RunTimeError: DataLoader worker (pid(s) 2412, 15788) exited unexpectedly

This was using Anaconda, so the error below is just using windows command console, and pip

(env) C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS>python eval_DAVIS.py -g '0' -s val -y 17 -D C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\DAVIS2017SemiSupervisedTrainVal480
Space-OneWorlde Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Start Testing: STM_DAVIS_17val
Space-OneWorlde Memory Networks: initialized.
STM : Testing on DAVIS
Space-OneWorlde Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Loading weights: STM_weights.pth
Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 114, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 225, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 112, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\popen_spawn_win32.py", line 46, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    is not going to be frozen to produce an executable.''')
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Start Testing: STM_DAVIS_17val
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 114, in _main
    prepare(preparation_data)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 225, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 279, in __iter__
    return _MultiProcessingDataLoaderIter(self)
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 719, in __init__
    w.start()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 112, in start
    self._popen = self._Popen(self)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\popen_spawn_win32.py", line 46, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    is not going to be frozen to produce an executable.''')
RunTimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Traceback (most recent call last):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 761, in _try_get_data
    data = self._data_queue.get(Timeout=Timeout)
  File "C:\Users\OneWorld\AppData\Local\Programs\Python\Python37\lib\multiprocessing\queues.py", line 105, in get
    raise Empty
_queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "eval_DAVIS.py", line 117, in <module>
    for seq, V in enumerate(Testloader):
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 345, in __next__
    data = self._next_data()
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 841, in _next_data
    idx, data = self._get_data()
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 808, in _get_data
    success, data = self._try_get_data()
  File "C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS\env\lib\site-packages\torch\utils\data\dataloader.py", line 774, in _try_get_data
    raise RunOneWorldeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(pids_str))
RunTimeError: DataLoader worker (pid(s) 11448, 16644) exited unexpectedly

I also put this code in a small file called CUDATest.py to test that torch would do a simple matrix multiplication function.

# testing CUDA
import torch
device = torch.cuda.current_device()

n = 10
# 1D inputs, same as torch.dot
a = torch.rand(n).to(device)
b = torch.rand(n).to(device)
result = torch.matmul(a, b) # torch.Size([])

print("matmul result = ", result)

I ran the code as follows:-

(env)C:\Users\OneWorld\Documents\DeepLearning\VideoObjectSegmentation\STMVOS>python CUDATest.py

The result was as follows:-

matmul result =  tensor(2.4603, device='cuda:0')

This suggests that my CUDA and Pytorch is working fine.


来源: stackexchange

问:
spring read server name inside cors
I'm trying to allow cors from the same server, with port 3000.

As I don't know where my server is going to be deployed, I tried to access the server name as string than concat it with my desired port.

So here is my approach :

```<code>@SpringBootApplication
public class TestApplication {
    @Autowired
    private HttpServletRequest request;
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        System.out.println(request.getServerName());
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("/**")
                        .allowedOrigins(request.getServerName()+":3000");
            }
        };
    }
}
</code>```

I think these are the highlights of my error message :

```<code>Error creating bean with name 'corsConfigurer'
org.springframework.beans.BeanInstantiationException: Failed to instantiate
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread?
</code>```

答: just use localhost, no need to access server name

ContentLicense: CC BY-SA 4.0

Title: spring read server name inside cors

Body:
I'm trying to allow cors from the same server, with port 3000.

As I don't know where my server is going to be deployed, I tried to access the server name as string than concat it with my desired port.

So here is my approach :

@SpringBootApplication
public class TestApplication {
    @Autowired
    private HttpServletRequest request;
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        System.out.println(request.getServerName());
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("/**")
                        .allowedOrigins(request.getServerName()+":3000");
            }
        };
    }
}

I think these are the highlights of my error message :

Error creating bean with name 'corsConfigurer'
org.springframework.beans.BeanInstantiationException: Failed to instantiate
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread?


问:
PHP mysql_query not returning false
Just learning PHP and I'm having some trouble understanding mysql_query. My understanding is that mysql_query is supposed to return FALSE if the record is not found. However, it seems that it always returns true because "FOUND!" is always the result:

```<code>$q = "SELECT * FROM users WHERE username = 'doesnotexist'";

$r = mysql_query($q);

if (!$q) {
    echo "<p>NOT FOUND!</p>";
} else {
    echo "<p>FOUND!</p>";
}

mysql_close();
</code>```

Thanks in advance for any light you can shed.

答:
Ok i have worked out the answer to this.

This is the version for updating a database that tells you if a record was valid.

```<code>$updatequery = "update `mydb` set `userid` = '$arr[0]', `name` = '$arr[1]' where `age` = '$arr[2]'";

$updatequeryresult= mysql_query($updatequery);

$howmanyupdatedrecords = mysql_affected_rows();

if ($howmanyupdatedrecords == 0) {
echo("The update didn't update any records as no one matched an age of " .$arr[2]");
}
</code>```

This will iterate through the DB updating all people with the specified age, if the age does not exist in the DB a message will be displayed showing you the age that does not exist. Also something to note, even if the mysql query matches a record, it won't update the record if the data already matches what it is being updated to. This causes the script to return "no one matched an age" even though there are people who did match. Can only attribute that to a bug in mysql. I told MySQL to update the information I don't see why it should take it upon itself to not bother doing as i told it. ;)

OwnerDisplayName: noobaroonie

ContentLicense: CC BY-SA 2.5

Title: PHP mysql_query not returning false

Body:
Just learning PHP and I'm having some trouble understanding mysql_query. My understanding is that mysql_query is supposed to return FALSE if the record is not found. However, it seems that it always returns true because "FOUND!" is always the result:

$q = "SELECT * FROM users WHERE username = 'doesnotexist'";

$r = mysql_query($q);

if (!$q) {
    echo "
NOT FOUND!
";
} else {
    echo "
FOUND!
";
}

mysql_close();

Thanks in advance for any light you can shed.

Body:
Ok i have worked out the answer to this.

This is the version for updating a database that tells you if a record was valid.

$updatequery = "update `mydb` set `userid` = '$arr[0]', `name` = '$arr[1]' where `age` = '$arr[2]'";

$updatequeryresult= mysql_query($updatequery);

$howmanyupdatedrecords = mysql_affected_rows();

if ($howmanyupdatedrecords == 0) {
echo("The update didn't update any records as no one matched an age of " .$arr[2]");
}

This will iterate through the DB updating all people with the specified age, if the age does not exist in the DB a message will be displayed showing you the age that does not exist. Also something to note, even if the mysql query matches a record, it won't update the record if the data already matches what it is being updated to. This causes the script to return "no one matched an age" even though there are people who did match. Can only attribute that to a bug in mysql. I told MySQL to update the information I don't see why it should take it upon itself to not bother doing as i told it. ;)

ContentLicense: CC BY-SA 3.0


问:
How to replace variable in tinymce using template_replace_values?
I want to replace value using template_replace_values in tinymce. I have added
Name: {$username}, StaffID: {$staffid}
 in textarea and template_replace_values:{username: "Jack Black",staffid: "991234"} in tinymce.init. When I run the code, the variable not replaced with value. It still showing the variable.

// Initialize TinyMCE
tinymce.init({
  selector: "textarea", // change this value according to your HTML
  plugins: "template",
  template_replace_values:
  {
    username: "Jack Black",
    staffid: "991234"
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html class="no-js" lang="">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Preview TinyMCE variable plugin</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdn.tinymce.com/4/tinymce.js"></script>
</head>
<body>
  <form method="post">
    <textarea rows="18">
   <p>Name: {$username}, StaffID: {$staffid}</p>
 </textarea>
  </form>
</body>
</html></code>```

I follow the example shown in documentation.Is the variable declaration {$staffid} with braces and dollar sign incorrect?

答:
The template_replace_values option happens when you insert content into the editor via a template (using the template plugin).  It does not perform any sort of global find/replace of values as the editor is first initialized.

In your example above you have some "default" content in the textarea that will be loaded into the editor as it is initialized.  As that content is not inserted via a template the setting you reference won't impact the content.

I have created a fiddle that shows how the template plugin works:

http://fiddle.tinymce.com/1khaab

If you use the Insert menu and select Insert template... you will see that the HTML of the template is inserted and the replacement takes place.

Body:
I want to replace value using template_replace_values in tinymce. I have added
Name: {$username}, StaffID: {$staffid}
 in textarea and template_replace_values:{username: "Jack Black",staffid: "991234"} in tinymce.init. When I run the code, the variable not replaced with value. It still showing the variable.

// Initialize TinyMCE
tinymce.init({
  selector: "textarea", // change this value according to your HTML
  plugins: "template",
  template_replace_values:
  {
    username: "Jack Black",
    staffid: "991234"
  }
});

<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Preview TinyMCE variable plugin</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <form method="post">
    <textarea rows="18">

Name: {$username}, StaffID: {$staffid}

 </textarea>
  </form>

I follow the example shown in documentation.Is the variable declaration {$staffid} with braces and dollar sign incorrect?


问:
insert NULL if input value is empty in C# to SQL server database
I need to insert some values to database by using SQL command how if it has some column with empty, So it should indicate as 'NULL' value and rest view with actual values.

I tried with this query but it didn't work

```<code>    insert into details values NULLIF('SomeRecord','') AS [Null]
</code>```

答:
You want to insert a null column value. if string is empty? Not insert null column name.
I'd think you should be able to use the CASE WHEN feature to do what you want.

Perhaps something like this?

```<code>INSERT INTO details VALUES (CASE WHEN LEN(stringCol) = 0 THEN NULL ELSE stringCol END);
</code>```

Assuming you want to set details.stringCol to the specified value, or null if empty.

Body:
I need to insert some values to database by using SQL command how if it has some column with empty, So it should indicate as 'NULL' value and rest view with actual values.

I tried with this query but it didn't work

    insert into details values NULLIF('SomeRecord','') AS [Null]

Body:
You want to insert a null column value. if string is empty? Not insert null column name.
I'd think you should be able to use the CASE WHEN feature to do what you want.

Perhaps something like this?

INSERT INTO details VALUES (CASE WHEN LEN(stringCol) = 0 THEN NULL ELSE stringCol END);

Assuming you want to set details.stringCol to the specified value, or null if empty.


问:
maxHeight does not work on RecyclerView
I've a DialogFragment.

Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxHeight="280dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/line/>

    <View
        android:id="@+id/line"
        android:layout_width="wrap_content"
        android:layout_height="1dp"
        android:background="@color/black"/>

</android.support.constraint.ConstraintLayout>
</code>```

I want to initially "wrap recycler view content" (height), but it cannot exceed 280dp. It seems that android:maxHeight has no effect what-so-ever.

答:
If you want to achieve this using the XML file, here are the steps.
This is for androidx component. First you need to implement a beta version in your gradle file

```<code>implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta6'
</code>```

After this, use the following code to create a recyclerView with max height of 240dp

```<code> <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
   >
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintHeight_max="240dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Title: maxHeight does not work on RecyclerView

Body:
I've a DialogFragment.

Layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxHeight="280dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/line/>

    <View
        android:id="@+id/line"
        android:layout_width="wrap_content"
        android:layout_height="1dp"
        android:background="@color/black"/>

</android.support.constraint.ConstraintLayout>

I want to initially "wrap recycler view content" (height), but it cannot exceed 280dp. It seems that android:maxHeight has no effect what-so-ever.

Body:
If you want to achieve this using the XML file, here are the steps.
This is for androidx component. First you need to implement a beta version in your gradle file

implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta6'

After this, use the following code to create a recyclerView with max height of 240dp

 <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
   >
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintHeight_max="240dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 </androidx.constraintlayout.widget.ConstraintLayout>


问:
TypeError: firebase.storage is not a function
Following this example, I keep getting the error:

```<code> TypeError: firebase.storage is not a function
</code>```

From this line in my code:

```<code>var storageRef = firebase.storage().ref();
</code>```

(And when I simply try to initialize storage from the storage guide, linked from firebase's npm site, I get the same error.)

In my Node.js project, I'm including the following libraries:

const firebase = require('firebase');

var admin = require('firebase-admin');

const fs = require('fs');

Up to this point, I've successfully been able to read from and write to the firebase database, creating a reference to the database with var db = admin.database(), then var ref = db.ref("/")... So I know I've configured Firebase and firebase-database correctly. But I'm stuck on storage, and have tried both admin.storage().ref() and firebase.storage().ref(), and firebase.storage().ref("/") with the same error message.

I've also tried:

```<code>var storage = firbase.storage();
var storageRef = storage.ref();
</code>```

and

```<code>const app = firebase.initializeApp(config);
var storage = app.storage();
</code>```

and with ref()'s void argument () and with "/"... but have the same message, yet to no avail.

I'm using:

"firebase": "^3.6.4"

"firebase-admin": "^4.0.4"

Node.js : v6.9.1

What must I do to successfully create a reference to storage?

答:
I was able to use firebase.storage(), but it took some time to figure it out. It only works when importing like this:

```<code>//Importing
const firebase = require('firebase')
require('firebase/storage')

//Calling the function (You can call it normally then)
const storageRef = firebase.storage().ref();
</code>```

I'm serious, whenever trying to import as firebase.storage() or doing anything different it wouldn't work! Hope it helps some of you guys.

Body:
Following this example, I keep getting the error:

 TypeError: firebase.storage is not a function

From this line in my code:

var storageRef = firebase.storage().ref();

(And when I simply try to initialize storage from the storage guide, linked from firebase's npm site, I get the same error.)

In my Node.js project, I'm including the following libraries:

const firebase = require('firebase');

var admin = require('firebase-admin');

const fs = require('fs');

Up to this point, I've successfully been able to read from and write to the firebase database, creating a reference to the database with var db = admin.database(), then var ref = db.ref("/")... So I know I've configured Firebase and firebase-database correctly. But I'm stuck on storage, and have tried both admin.storage().ref() and firebase.storage().ref(), and firebase.storage().ref("/") with the same error message.

I've also tried:

var storage = firbase.storage();
var storageRef = storage.ref();

and

const app = firebase.initializeApp(config);
var storage = app.storage();

and with ref()'s void argument () and with "/"... but have the same message, yet to no avail.

I'm using:

"firebase": "^3.6.4"

"firebase-admin": "^4.0.4"

Node.js : v6.9.1

What must I do to successfully create a reference to storage?

Body:
I was able to use firebase.storage(), but it took some time to figure it out. It only works when importing like this:

//Importing
const firebase = require('firebase')
require('firebase/storage')

//Calling the function (You can call it normally then)
const storageRef = firebase.storage().ref();

I'm serious, whenever trying to import as firebase.storage() or doing anything different it wouldn't work! Hope it helps some of you guys.


问:
How to dump type hierarchy of a C/C++ compilation unit in LLVM
I want to dump the type hierarchy of a C/C++ compilation unit in LLVM. For example, consider this C code:

```<code>struct S {
  int a[3];
  char *s;
};

struct T {
  float f;
  struct S t;
};
</code>```

I want to get a type hierarchy graph like this:

答:
First, the type hierarchy is not such a thing.  It doesn't have tree form, there are unrelated types that can be linked together in absolutely no form... and there are recursive definitions that will make your tree to become a graph (you can get very complicated ones).  There's nothing in the compiler, but to detect programming errors and to create the code that your program will use... Some have a program lister, that beautifies your code in some way, but in general you get a much harder listing to parse.  Information (semantic, structural) gets lost in the compiling process.

So the only way to do what you want is to parse the source code in order to do what you want.

Body:
I want to dump the type hierarchy of a C/C++ compilation unit in LLVM. For example, consider this C code:

struct S {
  int a[3];
  char *s;
};

struct T {
  float f;
  struct S t;
};

I want to get a type hierarchy graph like this:


问:
C# Image AS3 ByteArray
I'm looking for the conventer from normal image in C# to AMF3 ByteArray. The image format is JPG, I'm using FluorineFX library to serialize and de-serliazize AMF3 Data.

I need to get image ByteArray in C# from JPG because I'm using this to my flash game, and I don't know how to serialize image to AMF3 ByteArray. There isn't much info on FluorineFX neither AMF3 C# ByteArray.

答:
According to old FluorineFX Documentation if you want to convert image to byte array you need to use byte[] (variable types ending with [] are arrays) or FluorineFx.AMF3.ByteArray.
byte[] Example code:</p>

```<code>public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}
</code>```

Title: C# Image AS3 ByteArray

Body:
According to old FluorineFX Documentation if you want to convert image to byte array you need to use byte[] (variable types ending with [] are arrays) or FluorineFx.AMF3.ByteArray.
byte[] Example code:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}


问:
How to get parameters on Reach Router
I've a little problem with reach router, using react hooks. I need capture the params of the route in the browser
I tried with props of the native documentation in the web of reach router but that is not giving me the param, the route is this:
http://localhost:8080/home?init=true

How to capture that variable "init"?

答:
In no time, most of us will be redoing this everytime, so it's best to create a custom hook just to do this.</p>
```<code>// A custom hook that builds on useLocation to parse
// the query string for you.
export const useQuery = queryParam => {
  const search = new URLSearchParams(useLocation().search);
  return search.get(queryParam);
};
</code>```

Title: How to get parameters on Reach Router

Body:
In no time, most of us will be redoing this everytime, so it's best to create a custom hook just to do this.

// A custom hook that builds on useLocation to parse
// the query string for you.
export const useQuery = queryParam => {
  const search = new URLSearchParams(useLocation().search);
  return search.get(queryParam);
};


问:
DDEV and D8, httpClient used for internal request fails to connect
I've a multisite installation of Drupal 8, the "main" website expose some REST webservices, locally i've some troubles on testing them, because there's no way for the various sites to see each other, when i try to do something like that

```<code>try {
  $response = $this->httpClient->get($this->baseUri . '/myendpoint', [
    'headers' => [
      'Accept' => 'application/json',
      'Content-type' => 'application/hal+json',
    ],
    'query' => [
      '_format' => 'json',
      'myparameters'  => 'value'
    ],
  ]);
  $results = $this->serializer->decode($response->getBody(), 'json');
}
catch (RequestException $e) {
  $this->logger->warning($e->getMessage());
}
return $results;
</code>```

I always receive a timeout and there's no way i can make it work, i've my main website with the usual url project.ddev.site (and $this->baseUri is https://myproject.ddev.site ) and all the other websites are in the form  subsite.ddev.local
If i ssh in the project and run ping myproject.ddev.site i see 172.19.0.6
I don't understand why they cannot see each other...

答:
Just for other people who can have a similar problem: my issue was with xdebug i have it with the autoconnect, so when the request from the subsite to the main site was made, it get stuck somewhere (phpstorm didn't stop anywhere by the way) so it made the request time out.

By disabling, or configuring only for the subdomain, and avoiding it to accept the external connenction from unconfigured servers (in phpstorm) it started working, still have to do some work as i need to debug "both sides" of the request, but in this way i can work with that...

I've not thought before to try disabling xdebug because actually it didn't came into my mind...

Body:
I've a multisite installation of Drupal 8, the "main" website expose some REST webservices, locally i've some troubles on testing them, because there's no way for the various sites to see each other, when i try to do something like that

try {
  $response = $this->httpClient->get($this->baseUri . '/myendpoint', [
    'headers' => [
      'Accept' => 'application/json',
      'Content-type' => 'application/hal+json',
    ],
    'query' => [
      '_format' => 'json',
      'myparameters'  => 'value'
    ],
  ]);
  $results = $this->serializer->decode($response->getBody(), 'json');
}
catch (RequestException $e) {
  $this->logger->warning($e->getMessage());
}
return $results;

I always receive a timeout and there's no way i can make it work, i've my main website with the usual url project.ddev.site (and $this->baseUri is https://myproject.ddev.site ) and all the other websites are in the form  subsite.ddev.local
If i ssh in the project and run ping myproject.ddev.site i see 172.19.0.6
I don't understand why they cannot see each other...


问:
Value is correct when logged in Console but is undefined when using in variable
I fetched data from an API which gave me an object. When I tried to console log a specific value from the data i worked fine but when i tried using it as a variable i'm getting an error:

Cannot Read property from '.....' of undefined.

I'm using ReactJS.

This Is the Code Where I'm trying to access the value

```<code>
import React, { useContext, useState } from "react";
import ApexContext from "../context/apexContext";

const Overview = () => {
  const apexContext = useContext(ApexContext);

  const { gamer } = apexContext;

  const test = () => {
    console.log(gamer.platformInfo.platformSlug);
  };

  return (
    <div>
      <div>
        <img
          src="https://trackercdn.com/cdn/apex.tracker.gg/ranks/gold4.png"
          alt="Rank"
        />
        <h2>Active Legend: {gamer.platformInfo.platformSlug}</h2>
      </div>
      <div className="ui raised very padded text container segment">
        <button className="ui button" onClick={test}>
          Test
        </button>
      </div>
    </div>
  );
};

export default Overview;
</code>```

I am Using Context BTW.
Here IS the Code in which gamer object is being stored as an object

```<code>import React, { useReducer } from "react";
import Axios from "axios";
import ApexContext from "./apexContext";
import ApexReducer from "./apexReducer";
import {
  METADATA,
  PLATFORM_INFO,
  STATS,
  LOADING_TRUE,
  LOADING_FALSE,
  GAMER,
} from "./types";

const ApexState = (props) => {
  const InitialState = {
    metadata: {},
    platformInfo: {},
    overallStats: {},
    loading: false,
    gamer: {},
  };

  // Iniialize Reducer
  const [state, dispatch] = useReducer(ApexReducer, InitialState);

  // Finding The Specific Gamer Details
  const getGamer = async (platform, gamerId) => {
    dispatch({
      type: LOADING_TRUE,
    });

    const res = await Axios.get(
      `http://localhost:5000/api/v2/profile/${platform}/${gamerId}`
    );

    dispatch({
      type: GAMER,
      payload: res.data.data,
    });

    dispatch({
      type: LOADING_FALSE,
    });
  };

  return (
    <ApexContext.Provider
      value={{
        // loading: state.loading,
        // activeLegend: state.metadata.activeLegendName,
        // platformInfo: state.platformInfo,
        // overallStats: state.overallStats,
        gamer: state.gamer,
        getGamer,
      }}
    >
      {props.children}
    </ApexContext.Provider>
  );
};

export default ApexState;
</code>```

答:
The reason of that issue is your gamer object is arriving asynchronously from the API. Once you run the test function with onClick trigger the data already arrived.

Try checking for null values as:

```<code><h2>Active Legend: { gamer && gamer.platformInfo.platformSlug }</h2>
</code>```

In this way, it will try to access platformInfo property once gamer has a different value from null or undefined.

Body:
I fetched data from an API which gave me an object. When I tried to console log a specific value from the data i worked fine but when i tried using it as a variable i'm getting an error:

Cannot Read property from '.....' of undefined.

I'm using ReactJS.

This Is the Code Where I'm trying to access the value

import React, { useContext, useState } from "react";
import ApexContext from "../context/apexContext";

const Overview = () => {
  const apexContext = useContext(ApexContext);

  const { gamer } = apexContext;

  const test = () => {
    console.log(gamer.platformInfo.platformSlug);
  };

  return (

Active Legend: {gamer.platformInfo.platformSlug}

        <button className="ui button" onClick={test}>
          Test
        </button>

  );
};

export default Overview;

I am Using Context BTW.
Here IS the Code in which gamer object is being stored as an object

import React, { useReducer } from "react";
import Axios from "axios";
import ApexContext from "./apexContext";
import ApexReducer from "./apexReducer";
import {
  METADATA,
  PLATFORM_INFO,
  STATS,
  LOADING_TRUE,
  LOADING_FALSE,
  GAMER,
} from "./types";

const ApexState = (props) => {
  const InitialState = {
    metadata: {},
    platformInfo: {},
    overallStats: {},
    loading: false,
    gamer: {},
  };

  // Iniialize Reducer
  const [state, dispatch] = useReducer(ApexReducer, InitialState);

  // Finding The Specific Gamer Details
  const getGamer = async (platform, gamerId) => {
    dispatch({
      type: LOADING_TRUE,
    });

    const res = await Axios.get(
      `http://localhost:5000/api/v2/profile/${platform}/${gamerId}`
    );

    dispatch({
      type: GAMER,
      payload: res.data.data,
    });

    dispatch({
      type: LOADING_FALSE,
    });
  };

  return (
    <ApexContext.Provider
      value={{
        // loading: state.loading,
        // activeLegend: state.metadata.activeLegendName,
        // platformInfo: state.platformInfo,
        // overallStats: state.overallStats,
        gamer: state.gamer,
        getGamer,
      }}
    >
      {props.children}
    </ApexContext.Provider>
  );
};

export default ApexState;

Body:
The reason of that issue is your gamer object is arriving asynchronously from the API. Once you run the test function with onClick trigger the data already arrived.

Try checking for null values as:

<h2>Active Legend: { gamer && gamer.platformInfo.platformSlug }</h2>

In this way, it will try to access platformInfo property once gamer has a different value from null or undefined.