问:
jupyter notebook on anaconda - "win32security" kernal error
After a lot of fiddling and installing unistalling anconda I have finally got to this dead end trying to run jupyter notebook from "Anaconda3 2019.07 64bit" with "Python 3.7"  on "windows 8.1 Enterprise 64bit SP0"

The issue is:

jupyter notebook runs fine with NO kernal errors with the default
installation on base env.

when installing the following packages, something causes jupyter
notebook to upgrade which causes kernal errors to show up when
creating new python3 notebook!

packages installed:

conda install -c conda-forge awscli boto3

conda install shapely tensorflow opencv

This is a dump  of the kernel error:

```<code>Traceback (most recent call last):
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\web.py", line 1699, in _execute
    result = await result
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\notebook\services\sessions\handlers.py", line 72, in post
    type=mtype))
  File "C:\Users\sxxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 88, in create_session
    kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 101, in start_kernel_for_session
    self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 209, in wrapper
    yielded = next(result)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 168, in start_kernel
    super(MappingKernelManager, self).start_kernel(**kwargs)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\multikernelmanager.py", line 110, in start_kernel
    km.start_kernel(**kwargs)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\manager.py", line 240, in start_kernel
    self.write_connection_file()
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\connect.py", line 547, in write_connection_file
    kernel_name=self.kernel_name
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\connect.py", line 212, in write_connection_file
    with secure_write(fname) as f:
  File "C:\Users\xxx\.conda\envs\logAna\lib\contextlib.py", line 112, in __enter__
    return next(self.gen)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\connect.py", line 100, in secure_write
    win32_restrict_file_to_user(fname)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\connect.py", line 61, in win32_restrict_file_to_user
    sd = win32security.GetFileSecurity(fname, win32security.DACL_SECURITY_INFORMATION)
pywintypes.error: (50, 'GetFileSecurity', 'The request is not supported.')
</code>```

I have created a new environment installing all packages I need but could not find how to install the same version of jupyter notebook in "base" environment assuming that the new version of jupyter notebook has a bug.

I am relatively new to both Python and Anaconda and not getting much joy with them at the moment following three full days of agony trying all sorts of ways round the problem!

This is the dump from the terminal feed when this error occurs!:

```<code>(base) C:\WINDOWS\system32>activate test

(test) C:\WINDOWS\system32>jupyter lab
[I 15:50:55.678 LabApp] JupyterLab extension loaded from C:\Users\xxx\
.conda\envs\test\lib\site-packages\jupyterlab
[I 15:50:55.678 LabApp] JupyterLab application directory is C:\Users\xxx\.conda\envs\test\share\jupyter\lab
[I 15:50:55.682 LabApp] Serving notebooks from local directory: C:\WINDOWS\syste
m32
[I 15:50:55.682 LabApp] The Jupyter Notebook is running at:
[I 15:50:55.682 LabApp] http://localhost:8888/?token=e2f1c73d291f7e884d3c618eb43
83196c2d75484a0f88d96
[I 15:50:55.682 LabApp]  or http://127.0.0.1:8888/?token=e2f1c73d291f7e884d3c618
eb4383196c2d75484a0f88d96
[I 15:50:55.682 LabApp] Use Control-C to stop this server and shut down all kern
els (twice to skip confirmation).
[C 15:50:55.914 LabApp]

    To access the notebook, open this file in a browser:
        file://A-FILEDATA-COV-P/Profile/xxx/AppData/Roaming/jupyter/ru
ntime/nbserver-8544-open.html
    Or copy and paste one of these URLs:
        http://localhost:8888/?token=e2f1c73d291f7e884d3c618eb4383196c2d75484a0f
88d96
     or http://127.0.0.1:8888/?token=e2f1c73d291f7e884d3c618eb4383196c2d75484a0f
88d96
[W 15:51:04.157 LabApp] Could not determine jupyterlab build status without node
js
[E 15:51:13.236 LabApp] Uncaught exception POST /api/sessions?1569509473167 (::1
)
    HTTPServerRequest(protocol='http', host='localhost:8888', method='POST', uri
='/api/sessions?1569509473167', version='HTTP/1.1', remote_ip='::1')
    Traceback (most recent call last):
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\we
b.py", line 1699, in _execute
        result = await result
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\handlers.py", line 72, in post
        type=mtype))
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\sessionmanager.py", line 88, in create_session
        kernel_id = yield self.start_kernel_for_session(session_id, path, name,
type, kernel_name)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\sessionmanager.py", line 101, in start_kernel_for_session
        self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_na
me)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 209, in wrapper
        yielded = next(result)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\kernels\kernelmanager.py", line 168, in start_kernel
        super(MappingKernelManager, self).start_kernel(**kwargs)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\multikernelmanager.py", line 110, in start_kernel
        km.start_kernel(**kwargs)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\manager.py", line 240, in start_kernel
        self.write_connection_file()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 547, in write_connection_file
        kernel_name=self.kernel_name
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 212, in write_connection_file
        with secure_write(fname) as f:
      File "C:\Users\xxx\.conda\envs\test\lib\contextlib.py", line 112
, in __enter__
        return next(self.gen)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 100, in secure_write
        win32_restrict_file_to_user(fname)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 61, in win32_restrict_file_to_user
        sd = win32security.GetFileSecurity(fname, win32security.DACL_SECURITY_IN
FORMATION)
    pywintypes.error: (50, 'GetFileSecurity', 'The request is not supported.')
[W 15:51:13.245 LabApp] Unhandled error
[E 15:51:13.247 LabApp] {
      "Host": "localhost:8888",
      "Connection": "keep-alive",
      "Content-Length": "97",
      "Authorization": "token e2f1c73d291f7e884d3c618eb4383196c2d75484a0f88d96",

      "Origin": "http://localhost:8888",
      "X-Xsrftoken": "2|e0797587|bfb0295d2cfd16737a016247e6e4c3bb|1569403253",
      "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36
 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36",
      "Content-Type": "application/json",
      "Accept": "*/*",
      "Referer": "http://localhost:8888/lab",
      "Accept-Encoding": "gzip, deflate, br",
      "Accept-Language": "en-US,en;q=0.9",
      "Cookie": "_xsrf=2|e0797587|bfb0295d2cfd16737a016247e6e4c3bb|1569403253; u
sername-localhost-8889=\"2|1:0|10:1569504770|23:username-localhost-8889|44:NGY0Y
jJmZTI2MDZiNGU1ZDk5MTNjYjY3MTcwYjdlMDM=|caa84e45c938a438e74fe746b2d337a2e50d7882
a22c70ec0f114d22aa337feb\"; username-localhost-8888=\"2|1:0|10:1569509473|23:use
rname-localhost-8888|44:MDFkMmNlYjcwYzgxNGY3M2JlYmFjYTA4OTE2MGMwNDI=|d3bdb147f2b
afff4d6e7528326a74e6b7d13199b6f63400e84e2c00af8337dbf\""
    }
[E 15:51:13.248 LabApp] 500 POST /api/sessions?1569509473167 (::1) 69.19ms refer
er=http://localhost:8888/lab
[E 15:51:38.978 LabApp] Uncaught exception POST /api/sessions?1569509497781 (::1
)
    HTTPServerRequest(protocol='http', host='localhost:8888', method='POST', uri
='/api/sessions?1569509497781', version='HTTP/1.1', remote_ip='::1')
    Traceback (most recent call last):
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\we
b.py", line 1699, in _execute
        result = await result
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\handlers.py", line 72, in post
        type=mtype))
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\sessionmanager.py", line 88, in create_session
        kernel_id = yield self.start_kernel_for_session(session_id, path, name,
type, kernel_name)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\sessionmanager.py", line 101, in start_kernel_for_session
        self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_na
me)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 209, in wrapper
        yielded = next(result)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\kernels\kernelmanager.py", line 168, in start_kernel
        super(MappingKernelManager, self).start_kernel(**kwargs)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\multikernelmanager.py", line 110, in start_kernel
        km.start_kernel(**kwargs)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\manager.py", line 240, in start_kernel
        self.write_connection_file()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 547, in write_connection_file
        kernel_name=self.kernel_name
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 212, in write_connection_file
        with secure_write(fname) as f:
      File "C:\Users\xxx\.conda\envs\test\lib\contextlib.py", line 112
, in __enter__
        return next(self.gen)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 100, in secure_write
        win32_restrict_file_to_user(fname)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 61, in win32_restrict_file_to_user
        sd = win32security.GetFileSecurity(fname, win32security.DACL_SECURITY_IN
FORMATION)
    pywintypes.error: (50, 'GetFileSecurity', 'The request is not supported.')
[W 15:51:38.984 LabApp] Unhandled error
[E 15:51:38.985 LabApp] {
      "Host": "localhost:8888",
      "Connection": "keep-alive",
      "Content-Length": "97",
      "Pragma": "no-cache",
      "Cache-Control": "no-cache",
      "Authorization": "token e2f1c73d291f7e884d3c618eb4383196c2d75484a0f88d96",

      "Origin": "http://localhost:8888",
      "X-Xsrftoken": "2|e0797587|bfb0295d2cfd16737a016247e6e4c3bb|1569403253",
      "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36
 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36",
      "Content-Type": "application/json",
      "Accept": "*/*",
      "Referer": "http://localhost:8888/lab",
      "Accept-Encoding": "gzip, deflate, br",
      "Accept-Language": "en-US,en;q=0.9",
      "Cookie": "_xsrf=2|e0797587|bfb0295d2cfd16737a016247e6e4c3bb|1569403253; u
sername-localhost-8889=\"2|1:0|10:1569504770|23:username-localhost-8889|44:NGY0Y
jJmZTI2MDZiNGU1ZDk5MTNjYjY3MTcwYjdlMDM=|caa84e45c938a438e74fe746b2d337a2e50d7882
a22c70ec0f114d22aa337feb\"; username-localhost-8888=\"2|1:0|10:1569509486|23:use
rname-localhost-8888|44:OWMzYTU5MjgzZDQ0NDQ5Zjk3ZDZkYzUzNTE5MDYxMjQ=|fc18aa7b12f
dfb162c64a2236e57c93d1088d13b7ae52fd63a37ffd9e815de38\""
    }
[E 15:51:38.986 LabApp] 500 POST /api/sessions?1569509497781 (::1) 25.07ms refer
er=http://localhost:8888/lab
</code>```

答:
I tried downgrading the jupyter notebook to 5.3.1 and it worked for me.</p>

```<code>pip install jupyter-client==5.3.1
</code>```

Body:
After a lot of fiddling and installing unistalling anconda I have finally got to this dead end trying to run jupyter notebook from "Anaconda3 2019.07 64bit" with "Python 3.7"  on "windows 8.1 Enterprise 64bit SP0"

The issue is:

jupyter notebook runs fine with NO kernal errors with the default
installation on base env.

when installing the following packages, something causes jupyter
notebook to upgrade which causes kernal errors to show up when
creating new python3 notebook!

packages installed:

conda install -c conda-forge awscli boto3

conda install shapely tensorflow opencv

This is a dump  of the kernel error:

Traceback (most recent call last):
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\web.py", line 1699, in _execute
    result = await result
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\notebook\services\sessions\handlers.py", line 72, in post
    type=mtype))
  File "C:\Users\sxxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 88, in create_session
    kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 101, in start_kernel_for_session
    self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\tornado\gen.py", line 209, in wrapper
    yielded = next(result)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 168, in start_kernel
    super(MappingKernelManager, self).start_kernel(**kwargs)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\multikernelmanager.py", line 110, in start_kernel
    km.start_kernel(**kwargs)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\manager.py", line 240, in start_kernel
    self.write_connection_file()
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\connect.py", line 547, in write_connection_file
    kernel_name=self.kernel_name
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\connect.py", line 212, in write_connection_file
    with secure_write(fname) as f:
  File "C:\Users\xxx\.conda\envs\logAna\lib\contextlib.py", line 112, in __enter__
    return next(self.gen)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\connect.py", line 100, in secure_write
    win32_restrict_file_to_user(fname)
  File "C:\Users\xxx\.conda\envs\logAna\lib\site-packages\jupyter_client\connect.py", line 61, in win32_restrict_file_to_user
    sd = win32security.GetFileSecurity(fname, win32security.DACL_SECURITY_INFORMATION)
pywintypes.error: (50, 'GetFileSecurity', 'The request is not supported.')

I have created a new environment installing all packages I need but could not find how to install the same version of jupyter notebook in "base" environment assuming that the new version of jupyter notebook has a bug.

I am relatively new to both Python and Anaconda and not getting much joy with them at the moment following three full days of agony trying all sorts of ways round the problem!

This is the dump from the terminal feed when this error occurs!:

(base) C:\WINDOWS\system32>activate test

(test) C:\WINDOWS\system32>jupyter lab
[I 15:50:55.678 LabApp] JupyterLab extension loaded from C:\Users\xxx\
.conda\envs\test\lib\site-packages\jupyterlab
[I 15:50:55.678 LabApp] JupyterLab application directory is C:\Users\xxx\.conda\envs\test\share\jupyter\lab
[I 15:50:55.682 LabApp] Serving notebooks from local directory: C:\WINDOWS\syste
m32
[I 15:50:55.682 LabApp] The Jupyter Notebook is running at:
[I 15:50:55.682 LabApp] http://localhost:8888/?token=e2f1c73d291f7e884d3c618eb43
83196c2d75484a0f88d96
[I 15:50:55.682 LabApp]  or http://127.0.0.1:8888/?token=e2f1c73d291f7e884d3c618
eb4383196c2d75484a0f88d96
[I 15:50:55.682 LabApp] Use Control-C to stop this server and shut down all kern
els (twice to skip confirmation).
[C 15:50:55.914 LabApp]

    To access the notebook, open this file in a browser:
        file://A-FILEDATA-COV-P/Profile/xxx/AppData/Roaming/jupyter/ru
ntime/nbserver-8544-open.html
    Or copy and paste one of these URLs:
        http://localhost:8888/?token=e2f1c73d291f7e884d3c618eb4383196c2d75484a0f
88d96
     or http://127.0.0.1:8888/?token=e2f1c73d291f7e884d3c618eb4383196c2d75484a0f
88d96
[W 15:51:04.157 LabApp] Could not determine jupyterlab build status without node
js
[E 15:51:13.236 LabApp] Uncaught exception POST /api/sessions?1569509473167 (::1
)
    HTTPServerRequest(protocol='http', host='localhost:8888', method='POST', uri
='/api/sessions?1569509473167', version='HTTP/1.1', remote_ip='::1')
    Traceback (most recent call last):
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\we
b.py", line 1699, in _execute
        result = await result
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\handlers.py", line 72, in post
        type=mtype))
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\sessionmanager.py", line 88, in create_session
        kernel_id = yield self.start_kernel_for_session(session_id, path, name,
type, kernel_name)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\sessionmanager.py", line 101, in start_kernel_for_session
        self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_na
me)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 209, in wrapper
        yielded = next(result)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\kernels\kernelmanager.py", line 168, in start_kernel
        super(MappingKernelManager, self).start_kernel(**kwargs)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\multikernelmanager.py", line 110, in start_kernel
        km.start_kernel(**kwargs)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\manager.py", line 240, in start_kernel
        self.write_connection_file()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 547, in write_connection_file
        kernel_name=self.kernel_name
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 212, in write_connection_file
        with secure_write(fname) as f:
      File "C:\Users\xxx\.conda\envs\test\lib\contextlib.py", line 112
, in __enter__
        return next(self.gen)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 100, in secure_write
        win32_restrict_file_to_user(fname)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 61, in win32_restrict_file_to_user
        sd = win32security.GetFileSecurity(fname, win32security.DACL_SECURITY_IN
FORMATION)
    pywintypes.error: (50, 'GetFileSecurity', 'The request is not supported.')
[W 15:51:13.245 LabApp] Unhandled error
[E 15:51:13.247 LabApp] {
      "Host": "localhost:8888",
      "Connection": "keep-alive",
      "Content-Length": "97",
      "Authorization": "token e2f1c73d291f7e884d3c618eb4383196c2d75484a0f88d96",

      "Origin": "http://localhost:8888",
      "X-Xsrftoken": "2|e0797587|bfb0295d2cfd16737a016247e6e4c3bb|1569403253",
      "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36
 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36",
      "Content-Type": "application/json",
      "Accept": "*/*",
      "Referer": "http://localhost:8888/lab",
      "Accept-Encoding": "gzip, deflate, br",
      "Accept-Language": "en-US,en;q=0.9",
      "Cookie": "_xsrf=2|e0797587|bfb0295d2cfd16737a016247e6e4c3bb|1569403253; u
sername-localhost-8889=\"2|1:0|10:1569504770|23:username-localhost-8889|44:NGY0Y
jJmZTI2MDZiNGU1ZDk5MTNjYjY3MTcwYjdlMDM=|caa84e45c938a438e74fe746b2d337a2e50d7882
a22c70ec0f114d22aa337feb\"; username-localhost-8888=\"2|1:0|10:1569509473|23:use
rname-localhost-8888|44:MDFkMmNlYjcwYzgxNGY3M2JlYmFjYTA4OTE2MGMwNDI=|d3bdb147f2b
afff4d6e7528326a74e6b7d13199b6f63400e84e2c00af8337dbf\""
    }
[E 15:51:13.248 LabApp] 500 POST /api/sessions?1569509473167 (::1) 69.19ms refer
er=http://localhost:8888/lab
[E 15:51:38.978 LabApp] Uncaught exception POST /api/sessions?1569509497781 (::1
)
    HTTPServerRequest(protocol='http', host='localhost:8888', method='POST', uri
='/api/sessions?1569509497781', version='HTTP/1.1', remote_ip='::1')
    Traceback (most recent call last):
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\we
b.py", line 1699, in _execute
        result = await result
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\handlers.py", line 72, in post
        type=mtype))
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\sessionmanager.py", line 88, in create_session
        kernel_id = yield self.start_kernel_for_session(session_id, path, name,
type, kernel_name)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 742, in run
        yielded = self.gen.throw(*exc_info)  # type: ignore
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\sessions\sessionmanager.py", line 101, in start_kernel_for_session
        self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_na
me)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 735, in run
        value = future.result()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\tornado\ge
n.py", line 209, in wrapper
        yielded = next(result)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\notebook\s
ervices\kernels\kernelmanager.py", line 168, in start_kernel
        super(MappingKernelManager, self).start_kernel(**kwargs)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\multikernelmanager.py", line 110, in start_kernel
        km.start_kernel(**kwargs)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\manager.py", line 240, in start_kernel
        self.write_connection_file()
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 547, in write_connection_file
        kernel_name=self.kernel_name
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 212, in write_connection_file
        with secure_write(fname) as f:
      File "C:\Users\xxx\.conda\envs\test\lib\contextlib.py", line 112
, in __enter__
        return next(self.gen)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 100, in secure_write
        win32_restrict_file_to_user(fname)
      File "C:\Users\xxx\.conda\envs\test\lib\site-packages\jupyter_cl
ient\connect.py", line 61, in win32_restrict_file_to_user
        sd = win32security.GetFileSecurity(fname, win32security.DACL_SECURITY_IN
FORMATION)
    pywintypes.error: (50, 'GetFileSecurity', 'The request is not supported.')
[W 15:51:38.984 LabApp] Unhandled error
[E 15:51:38.985 LabApp] {
      "Host": "localhost:8888",
      "Connection": "keep-alive",
      "Content-Length": "97",
      "Pragma": "no-cache",
      "Cache-Control": "no-cache",
      "Authorization": "token e2f1c73d291f7e884d3c618eb4383196c2d75484a0f88d96",

      "Origin": "http://localhost:8888",
      "X-Xsrftoken": "2|e0797587|bfb0295d2cfd16737a016247e6e4c3bb|1569403253",
      "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36
 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36",
      "Content-Type": "application/json",
      "Accept": "*/*",
      "Referer": "http://localhost:8888/lab",
      "Accept-Encoding": "gzip, deflate, br",
      "Accept-Language": "en-US,en;q=0.9",
      "Cookie": "_xsrf=2|e0797587|bfb0295d2cfd16737a016247e6e4c3bb|1569403253; u
sername-localhost-8889=\"2|1:0|10:1569504770|23:username-localhost-8889|44:NGY0Y
jJmZTI2MDZiNGU1ZDk5MTNjYjY3MTcwYjdlMDM=|caa84e45c938a438e74fe746b2d337a2e50d7882
a22c70ec0f114d22aa337feb\"; username-localhost-8888=\"2|1:0|10:1569509486|23:use
rname-localhost-8888|44:OWMzYTU5MjgzZDQ0NDQ5Zjk3ZDZkYzUzNTE5MDYxMjQ=|fc18aa7b12f
dfb162c64a2236e57c93d1088d13b7ae52fd63a37ffd9e815de38\""
    }
[E 15:51:38.986 LabApp] 500 POST /api/sessions?1569509497781 (::1) 25.07ms refer
er=http://localhost:8888/lab

Body:
I tried downgrading the jupyter notebook to 5.3.1 and it worked for me.

pip install jupyter-client==5.3.1


来源: stackexchange

问:
How to use initial solution in pulp (python)
Community,

I have the next problem I want to do a improvement heuristic (Fix and Optimize) and I need to use the initial solution to start, my problem is MIP having binary and continuous variables. I asked him how I would do to use the previous solution as an initial and how I leave some of those variables unfix for your optimization.

Ps: I use --> prob.solve(CPLEX_PY(timeLimit = '3600', epgap = 0.001))

Thanks.

答:
with docplex python API you can do this :

```<code>from docplex.mp.model import Model

mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*460 + nbbus30*360)

mdl.get_cplex().MIP_starts.read("c:/file.mst")

sol=mdl.solve(log_output=True)

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)
</code>```

Full example at https://github.com/AlexFleischerParis/zoodocplex/blob/master/zooreadMST.py

Or you can use APIs

```<code>from docplex.mp.model import Model

mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)

warmstart=mdl.new_solution()
warmstart.add_var_value(nbbus40,8)
warmstart.add_var_value(nbbus30,0)
mdl.add_mip_start(warmstart)

sol=mdl.solve(log_output=True)

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)
</code>```

in https://github.com/AlexFleischerParis/zoodocplex/blob/master/zoowarmstartapi.py

ContentLicense: CC BY-SA 4.0

Body:
with docplex python API you can do this :

from docplex.mp.model import Model

mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*460 + nbbus30*360)

mdl.get_cplex().MIP_starts.read("c:/file.mst")

sol=mdl.solve(log_output=True)

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)

Full example at https://github.com/AlexFleischerParis/zoodocplex/blob/master/zooreadMST.py

Or you can use APIs

from docplex.mp.model import Model

mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)

warmstart=mdl.new_solution()
warmstart.add_var_value(nbbus40,8)
warmstart.add_var_value(nbbus30,0)
mdl.add_mip_start(warmstart)

sol=mdl.solve(log_output=True)

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)

in https://github.com/AlexFleischerParis/zoodocplex/blob/master/zoowarmstartapi.py


问:
Need advice on how to create deploy spring-cloud-dataflow apps in several dedicated servers to create an stream
I am trying to use spring-cloud-dataflow to create streams over an existing set of servers. It is not a production environment, I am aware of the fault tolerance issues with the "local" deployer.

I have in the past created this infrastructure by:

1-Created a "scdf-server" by implementing the provided interface (ui and shell worked fine with no changes) . This server forward the request to an application (2) running on each server using REST calls

2-On each server I have an application that encapsulates the local deployer and receives the REST calls from the server passing the along to the encapsulated local deployer.

This approach worked perfectly, but now I need some of the new features in the new SCDF version and with the introduction of skipper I am not sure this is the best approach, or if it is even possible, need advice.

TIA

答:
Looks like you have already explored the code to have better insights on how things are implemented.

As you stated, the local deployer implementation is never meant for production deployments. Hence, the SCDF team has dev-centric design goals on local deployer implementation and also limited its scope on extensions as well.

Given this, the way you designed your setup based on the needs, going with the Skipper server embedded into each app wouldn't work as Skipper server is expected to have a 1-on-1 relationship with SCDF server. Moreover, Skipper server also maintains a local State machine that might go stale when you have a different instance of Skipper server that listens to the same SCDF server. This makes the whole design very complex indeed.


问:
How can I determine a line code in jQuery is done
I have a code that sends a request to API for download an excel file.
I want to show a waiting animation to stop when the download is completed. I use this code for download excel file:

```<code>$('#t_ExcelExport')
 .button()
 .click(function () {
    var isApproved = localStorage.getItem('t_Filter_Caption_User_Value');
    let url = PeywebRootPath + 'Security/User/ToExcel?isApproved=' + isApproved;
    $.Waiting();
    window.location = url;
)};
</code>```

how can I determine the line code that window.location = is done and I should stop showing waiting animation?

答:
I found a Method to solve this case:

After complete server side download. Add a cookie with the name 'fileDownloadCompletedToken'

On client side check cookie exist 'fileDownloadCompletedToken'

If cookie exist; stop showing waiting animation and remove cookie 'fileDownloadCompletedToken'

My complete code:

```<code>$('#t_ExcelExport')
  .button()
    .click(function () {
      var isApproved = localStorage.getItem('t_Filter_Caption_User_Value');
      let url = PeywebRootPath + 'Security/User/ToExcel?isApproved=' + isApproved;
      $.Waiting();
      window.location = url;

      window.setInterval(function () {
      if ($.cookie('fileDownloadCompletedToken') != null)
        $.Waiting({ show: false });
        $.cookie("fileDownloadCompletedToken", null, { path: '/' });
      }, 1000);
    });
</code>```

Body:
I have a code that sends a request to API for download an excel file.
I want to show a waiting animation to stop when the download is completed. I use this code for download excel file:

$('#t_ExcelExport')
 .button()
 .click(function () {
    var isApproved = localStorage.getItem('t_Filter_Caption_User_Value');
    let url = PeywebRootPath + 'Security/User/ToExcel?isApproved=' + isApproved;
    $.Waiting();
    window.location = url;
)};

how can I determine the line code that window.location = is done and I should stop showing waiting animation?

Body:
I found a Method to solve this case:

After complete server side download. Add a cookie with the name 'fileDownloadCompletedToken'

On client side check cookie exist 'fileDownloadCompletedToken'

If cookie exist; stop showing waiting animation and remove cookie 'fileDownloadCompletedToken'

My complete code:

$('#t_ExcelExport')
  .button()
    .click(function () {
      var isApproved = localStorage.getItem('t_Filter_Caption_User_Value');
      let url = PeywebRootPath + 'Security/User/ToExcel?isApproved=' + isApproved;
      $.Waiting();
      window.location = url;

      window.setInterval(function () {
      if ($.cookie('fileDownloadCompletedToken') != null)
        $.Waiting({ show: false });
        $.cookie("fileDownloadCompletedToken", null, { path: '/' });
      }, 1000);
    });


问:
When the image is saved , the image gets rotated by 90 degrees.Using CameraX
```<code>  private void startCamera() {

        CameraX.unbindAll();

        Rational aspectRatio = new Rational (textureView.getWidth(), textureView.getHeight());
        Size screen = new Size(textureView.getWidth(), textureView.getHeight()); //size of the screen

        PreviewConfig pConfig = new PreviewConfig.Builder()
                                    .setTargetAspectRatio(aspectRatio)
                                    .setTargetResolution(screen)
                                    .setLensFacing(CameraX.LensFacing.BACK)
                                    .build();
        Preview preview = new Preview(pConfig);

        preview.setOnPreviewOutputUpdateListener(
                new Preview.OnPreviewOutputUpdateListener() {
                    @Override
                    public void onUpdated(Preview.PreviewOutput output){
                        ViewGroup parent = (ViewGroup) textureView.getParent();
                        parent.removeView(textureView);
                        parent.addView(textureView, 0);

                        textureView.setSurfaceTexture(output.getSurfaceTexture());

                        int a=output.getRotationDegrees();
                        Log.d( TAG , "output Rota3: " + String.valueOf( a) );

                        updateTransform();
                    }
                });
        ImageCaptureConfig imageCaptureConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
                .setTargetRotation((getWindowManager().getDefaultDisplay().getRotation())).setFlashMode( FlashMode.OFF ).build();
              imgCap = new ImageCapture(imageCaptureConfig);

        imgCapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              File file = new File(Environment.getExternalStorageDirectory() + "/" + "IMG_" +System.currentTimeMillis() + ".png");
                imgCap.takePicture(file, new ImageCapture.OnImageSavedListener() {

                    @Override
                    public void onImageSaved(@NonNull File file) {
                        String msg = "Pic captured at " + file.getAbsolutePath();
                        Toast.makeText(getBaseContext(), msg,Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(@NonNull ImageCapture.UseCaseError useCaseError, @NonNull String message, @Nullable Throwable cause) {
                        String msg = "Pic capture failed : " + message;
                        Toast.makeText(getBaseContext(), msg,Toast.LENGTH_LONG).show();
                        if(cause != null){
                            cause.printStackTrace();
                        }
                    }
                });
            }
        });
        CameraX.bindToLifecycle((LifecycleOwner)this, preview, imgCap);
    }

    private void updateTransform(){
        Matrix mx = new Matrix();
        float w = textureView.getMeasuredWidth();
        float h = textureView.getMeasuredHeight();

        float cX = w / 2f;
        float cY = h / 2f;

        int rotationDgr;
        int rotation = (int)textureView.getRotation();
        Log.d( TAG , "rotation: " + rotation );

        switch(rotation){
            case Surface.ROTATION_0:
                rotationDgr = 0;
                break;
            case Surface.ROTATION_90:
                rotationDgr = 90;
                break;
            case Surface.ROTATION_180:
                rotationDgr = 180;
                break;
            case Surface.ROTATION_270:
                rotationDgr = 270;
                break;
            default:
                return;
        }

        Log.d( TAG , "rotationDGR: " + rotationDgr );
        mx.postRotate((float)rotationDgr, cX, cY);
        textureView.setTransform(mx);
    }
</code>```

Used CameraX.
Working on application to capture the image and get it saved after capturing.
But unfortunately, I am, getting orientation 0 as the value of getting TargetRotaion() always in every device. Even in the 90 degree rotated image devices.

The problem is image gets rotated on getting saved.
I tried some solutions suggested on StackOverflow but couldn't get the problem resolved.

答:
Use this class `
public class DeviceOrientation {

```<code>private static final String TAG = "CameraExif";

// Returns the degrees in clockwise. Values are 0, 90, 180, or 270.
public static int getOrientation(byte[] jpeg) {
    if (jpeg == null) {
        return 0;
    }

    int offset = 0;
    int length = 0;

    // ISO/IEC 10918-1:1993(E)
    while (offset + 3 < jpeg.length && (jpeg[offset++] & 0xFF) == 0xFF) {
        int marker = jpeg[offset] & 0xFF;

        // Check if the marker is a padding.
        if (marker == 0xFF) {
            continue;
        }
        offset++;

        // Check if the marker is SOI or TEM.
        if (marker == 0xD8 || marker == 0x01) {
            continue;
        }
        // Check if the marker is EOI or SOS.
        if (marker == 0xD9 || marker == 0xDA) {
            break;
        }

        // Get the length and check if it is reasonable.
        length = pack(jpeg, offset, 2, false);
        if (length < 2 || offset + length > jpeg.length) {
            Log.e(TAG, "Invalid length");
            return 0;
        }

        // Break if the marker is EXIF in APP1.
        if (marker == 0xE1 && length >= 8 &&
                pack(jpeg, offset + 2, 4, false) == 0x45786966 &&
                pack(jpeg, offset + 6, 2, false) == 0) {
            offset += 8;
            length -= 8;
            break;
        }

        // Skip other markers.
        offset += length;
        length = 0;
    }

    // JEITA CP-3451 DeviceOrientation Version 2.2
    if (length > 8) {
        // Identify the byte order.
        int tag = pack(jpeg, offset, 4, false);
        if (tag != 0x49492A00 && tag != 0x4D4D002A) {
            Log.e(TAG, "Invalid byte order");
            return 0;
        }
        boolean littleEndian = (tag == 0x49492A00);

        // Get the offset and check if it is reasonable.
        int count = pack(jpeg, offset + 4, 4, littleEndian) + 2;
        if (count < 10 || count > length) {
            Log.e(TAG, "Invalid offset");
            return 0;
        }
        offset += count;
        length -= count;

        // Get the count and go through all the elements.
        count = pack(jpeg, offset - 2, 2, littleEndian);
        while (count-- > 0 && length >= 12) {
            // Get the tag and check if it is orientation.
            tag = pack(jpeg, offset, 2, littleEndian);
            if (tag == 0x0112) {
                // We do not really care about type and count, do we?
                int orientation = pack(jpeg, offset + 8, 2, littleEndian);
                switch (orientation) {
                    case 1:
                        return 0;
                    case 3:
                        return 180;
                    case 6:
                        return 90;
                    case 8:
                        return 270;
                }
                Log.i(TAG, "Unsupported orientation");
                return 0;
            }
            offset += 12;
            length -= 12;
        }
    }

    Log.i(TAG, "Orientation not found");
    return 0;
}

private static int pack(byte[] bytes, int offset, int length,
                        boolean littleEndian) {
    int step = 1;
    if (littleEndian) {
        offset += length - 1;
        step = -1;
    }
    int value = 0;
    while (length-- > 0) {
        value = (value << 8) | (bytes[offset] & 0xFF);
        offset += step;
    }
    return value;
}
</code>```

}`

and use this method in after taking photo

```<code>  int orientation = DeviceOrientation.getOrientation(bytes);
</code>```

Body:
  private void startCamera() {

        CameraX.unbindAll();

        Rational aspectRatio = new Rational (textureView.getWidth(), textureView.getHeight());
        Size screen = new Size(textureView.getWidth(), textureView.getHeight()); //size of the screen

        PreviewConfig pConfig = new PreviewConfig.Builder()
                                    .setTargetAspectRatio(aspectRatio)
                                    .setTargetResolution(screen)
                                    .setLensFacing(CameraX.LensFacing.BACK)
                                    .build();
        Preview preview = new Preview(pConfig);

        preview.setOnPreviewOutputUpdateListener(
                new Preview.OnPreviewOutputUpdateListener() {
                    @Override
                    public void onUpdated(Preview.PreviewOutput output){
                        ViewGroup parent = (ViewGroup) textureView.getParent();
                        parent.removeView(textureView);
                        parent.addView(textureView, 0);

                        textureView.setSurfaceTexture(output.getSurfaceTexture());

                        int a=output.getRotationDegrees();
                        Log.d( TAG , "output Rota3: " + String.valueOf( a) );

                        updateTransform();
                    }
                });
        ImageCaptureConfig imageCaptureConfig = new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
                .setTargetRotation((getWindowManager().getDefaultDisplay().getRotation())).setFlashMode( FlashMode.OFF ).build();
              imgCap = new ImageCapture(imageCaptureConfig);

        imgCapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              File file = new File(Environment.getExternalStorageDirectory() + "/" + "IMG_" +System.currentTimeMillis() + ".png");
                imgCap.takePicture(file, new ImageCapture.OnImageSavedListener() {

                    @Override
                    public void onImageSaved(@NonNull File file) {
                        String msg = "Pic captured at " + file.getAbsolutePath();
                        Toast.makeText(getBaseContext(), msg,Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(@NonNull ImageCapture.UseCaseError useCaseError, @NonNull String message, @Nullable Throwable cause) {
                        String msg = "Pic capture failed : " + message;
                        Toast.makeText(getBaseContext(), msg,Toast.LENGTH_LONG).show();
                        if(cause != null){
                            cause.printStackTrace();
                        }
                    }
                });
            }
        });
        CameraX.bindToLifecycle((LifecycleOwner)this, preview, imgCap);
    }

    private void updateTransform(){
        Matrix mx = new Matrix();
        float w = textureView.getMeasuredWidth();
        float h = textureView.getMeasuredHeight();

        float cX = w / 2f;
        float cY = h / 2f;

        int rotationDgr;
        int rotation = (int)textureView.getRotation();
        Log.d( TAG , "rotation: " + rotation );

        switch(rotation){
            case Surface.ROTATION_0:
                rotationDgr = 0;
                break;
            case Surface.ROTATION_90:
                rotationDgr = 90;
                break;
            case Surface.ROTATION_180:
                rotationDgr = 180;
                break;
            case Surface.ROTATION_270:
                rotationDgr = 270;
                break;
            default:
                return;
        }

        Log.d( TAG , "rotationDGR: " + rotationDgr );
        mx.postRotate((float)rotationDgr, cX, cY);
        textureView.setTransform(mx);
    }

Used CameraX.
Working on application to capture the image and get it saved after capturing.
But unfortunately, I am, getting orientation 0 as the value of getting TargetRotaion() always in every device. Even in the 90 degree rotated image devices.

The problem is image gets rotated on getting saved.
I tried some solutions suggested on StackOverflow but couldn't get the problem resolved.

Body:
Use this class `
public class DeviceOrientation {

private static final String TAG = "CameraExif";

// Returns the degrees in clockwise. Values are 0, 90, 180, or 270.
public static int getOrientation(byte[] jpeg) {
    if (jpeg == null) {
        return 0;
    }

    int offset = 0;
    int length = 0;

    // ISO/IEC 10918-1:1993(E)
    while (offset + 3 < jpeg.length && (jpeg[offset++] & 0xFF) == 0xFF) {
        int marker = jpeg[offset] & 0xFF;

        // Check if the marker is a padding.
        if (marker == 0xFF) {
            continue;
        }
        offset++;

        // Check if the marker is SOI or TEM.
        if (marker == 0xD8 || marker == 0x01) {
            continue;
        }
        // Check if the marker is EOI or SOS.
        if (marker == 0xD9 || marker == 0xDA) {
            break;
        }

        // Get the length and check if it is reasonable.
        length = pack(jpeg, offset, 2, false);
        if (length < 2 || offset + length > jpeg.length) {
            Log.e(TAG, "Invalid length");
            return 0;
        }

        // Break if the marker is EXIF in APP1.
        if (marker == 0xE1 && length >= 8 &&
                pack(jpeg, offset + 2, 4, false) == 0x45786966 &&
                pack(jpeg, offset + 6, 2, false) == 0) {
            offset += 8;
            length -= 8;
            break;
        }

        // Skip other markers.
        offset += length;
        length = 0;
    }

    // JEITA CP-3451 DeviceOrientation Version 2.2
    if (length > 8) {
        // Identify the byte order.
        int tag = pack(jpeg, offset, 4, false);
        if (tag != 0x49492A00 && tag != 0x4D4D002A) {
            Log.e(TAG, "Invalid byte order");
            return 0;
        }
        boolean littleEndian = (tag == 0x49492A00);

        // Get the offset and check if it is reasonable.
        int count = pack(jpeg, offset + 4, 4, littleEndian) + 2;
        if (count < 10 || count > length) {
            Log.e(TAG, "Invalid offset");
            return 0;
        }
        offset += count;
        length -= count;

        // Get the count and go through all the elements.
        count = pack(jpeg, offset - 2, 2, littleEndian);
        while (count-- > 0 && length >= 12) {
            // Get the tag and check if it is orientation.
            tag = pack(jpeg, offset, 2, littleEndian);
            if (tag == 0x0112) {
                // We do not really care about type and count, do we?
                int orientation = pack(jpeg, offset + 8, 2, littleEndian);
                switch (orientation) {
                    case 1:
                        return 0;
                    case 3:
                        return 180;
                    case 6:
                        return 90;
                    case 8:
                        return 270;
                }
                Log.i(TAG, "Unsupported orientation");
                return 0;
            }
            offset += 12;
            length -= 12;
        }
    }

    Log.i(TAG, "Orientation not found");
    return 0;
}

private static int pack(byte[] bytes, int offset, int length,
                        boolean littleEndian) {
    int step = 1;
    if (littleEndian) {
        offset += length - 1;
        step = -1;
    }
    int value = 0;
    while (length-- > 0) {
        value = (value << 8) | (bytes[offset] & 0xFF);
        offset += step;
    }
    return value;
}

}`

and use this method in after taking photo

  int orientation = DeviceOrientation.getOrientation(bytes);


问:
Oracle "replace" function alternative in PostgreSQL with 2 arguments?

Select REPLACE('123123tech', '123')
  From Dual;
```

Above is Oracle code but when I am going to find its alternative in PostgreSQL can't find a suitable function for that. PostgreSQL REPLACE function takes 3 arguments. I want a function who can take 2 arguments. Any solution ?

答:
The way to do this in Postgresql is Select REPLACE('123123tech', '123','').

Best regards,

Bjarni

Body:
Select REPLACE('123123tech', '123')
  From Dual;

Above is Oracle code but when I am going to find its alternative in PostgreSQL can't find a suitable function for that. PostgreSQL REPLACE function takes 3 arguments. I want a function who can take 2 arguments. Any solution ?


问:
How to make a loop with increment of time period in PL/SQL
In my Oracle database there is a session table with user's login date and time. With this query I can get number of users who logged in (opened their session) within given time period - for example logged in January:

```<code>SELECT
    COUNT(DISTINCT ses_username)
FROM
    sessions
WHERE
    to_char(ses_start_date, 'YYYY-MM-DD HH24:MI:SS') BETWEEN '2019-01-01 00:00:00' AND '2019-01-31 23:59:59'
</code>```

How to make a loop in PL/SQL that give me the count but by days per month or by hours per month or by hours per day or even quarter of an hour (15 minutes) by day.

EDIT:

Session table format is

```<code>ses_id  ses_start_date          ses_username
============================================
786895  2019-01-01 15:39:10     USER_1
786896  2019-01-01 15:39:11     USER_1
786897  2019-01-01 16:38:39     USER_1
786898  2019-01-01 16:38:40     USER_1
786899  2019-01-02 06:44:20     USER_2
786900  2019-01-02 06:44:21     USER_2
786901  2019-01-02 06:50:10     USER_3
786902  2019-01-02 06:50:11     USER_3
786903  2019-01-02 06:50:28     USER_4
786904  2019-01-02 06:50:30     USER_4
...
</code>```

And I need to know how many unique usernames was logged in within every day in month or within every hour or within every 15 minutes per day.

答:
I am not sure, what you mean by looping in your question. But Yes, If you want to see data day-wise then you can use the GROUP BY and COUNT as following:

```<code>SELECT
    TRUNC(ses_start_date) AS SESSION_DAY,
    COUNT(DISTINCT ses_username)
FROM
    sessions
WHERE
   TRUNC(ses_start_date) BETWEEN DATE '2019-01-01' AND DATE '2019-01-31'
   GROUP BY TRUNC(ses_start_date)
</code>```

Note: Do not convert date to char and compare. Dates can be compared directly as shown in the example.

Cheers!!

Body:
In my Oracle database there is a session table with user's login date and time. With this query I can get number of users who logged in (opened their session) within given time period - for example logged in January:

SELECT
    COUNT(DISTINCT ses_username)
FROM
    sessions
WHERE
    to_char(ses_start_date, 'YYYY-MM-DD HH24:MI:SS') BETWEEN '2019-01-01 00:00:00' AND '2019-01-31 23:59:59'

How to make a loop in PL/SQL that give me the count but by days per month or by hours per month or by hours per day or even quarter of an hour (15 minutes) by day.

EDIT:

Session table format is

ses_id  ses_start_date          ses_username
============================================
786895  2019-01-01 15:39:10     USER_1
786896  2019-01-01 15:39:11     USER_1
786897  2019-01-01 16:38:39     USER_1
786898  2019-01-01 16:38:40     USER_1
786899  2019-01-02 06:44:20     USER_2
786900  2019-01-02 06:44:21     USER_2
786901  2019-01-02 06:50:10     USER_3
786902  2019-01-02 06:50:11     USER_3
786903  2019-01-02 06:50:28     USER_4
786904  2019-01-02 06:50:30     USER_4
...

And I need to know how many unique usernames was logged in within every day in month or within every hour or within every 15 minutes per day.

Body:
I am not sure, what you mean by looping in your question. But Yes, If you want to see data day-wise then you can use the GROUP BY and COUNT as following:

SELECT
    TRUNC(ses_start_date) AS SESSION_DAY,
    COUNT(DISTINCT ses_username)
FROM
    sessions
WHERE
   TRUNC(ses_start_date) BETWEEN DATE '2019-01-01' AND DATE '2019-01-31'
   GROUP BY TRUNC(ses_start_date)

Note: Do not convert date to char and compare. Dates can be compared directly as shown in the example.

Cheers!!


问:
Configure Autohotkey to edit scripts with Notepad++
I have my default editor for .ahk files set to Notepad++ Portable on my work laptop, but selecting Edit This Script opens files in the standard Windows Notepad.

A post on the AHK forums suggests editing the registry, but I don't see any entries under HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Edit\Command.

How can I configure AutoHotkey to edit scripts with Notepad++?

答:
For AHK version 2, changing the registry didn't work for me (I tried both Computer\HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Edit\Command and Computer\HKEY_CLASSES_ROOT\.ahk\Shell\Edit\Command), but this did it for me. It adds two menu items to the AHK tray menu after a divider:

```<code>EditWithNotepadPlusPlus(*)
{
    Run "C:\Program Files\Notepad++\notepad++.exe " A_ScriptFullPath
}
EditWithVsCode(*)
{
    Run "C:\Program Files\Microsoft VS Code\Code.exe " A_ScriptFullPath
}
A_TrayMenu.Add()
A_TrayMenu.Add("Edit with VS Code", EditWithVsCode)
A_TrayMenu.Add("Edit with Notepad++", EditWithNotepadPlusPlus)
return
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For AHK version 2, changing the registry didn't work for me (I tried both Computer\HKEY_CLASSES_ROOT\AutoHotkeyScript\Shell\Edit\Command and Computer\HKEY_CLASSES_ROOT\.ahk\Shell\Edit\Command), but this did it for me. It adds two menu items to the AHK tray menu after a divider:

EditWithNotepadPlusPlus(*)
{
    Run "C:\Program Files\Notepad++\notepad++.exe " A_ScriptFullPath
}
EditWithVsCode(*)
{
    Run "C:\Program Files\Microsoft VS Code\Code.exe " A_ScriptFullPath
}
A_TrayMenu.Add()
A_TrayMenu.Add("Edit with VS Code", EditWithVsCode)
A_TrayMenu.Add("Edit with Notepad++", EditWithNotepadPlusPlus)
return


问:
How to separate regex values?
the user makes a selection and I want to test if the selection is valid. So e.g.

```<code> preg_match("/(test1/test2|test3)/", $value)
</code>```

The problem is that one value is test1/test2, but each test is treated as a single value.  Any idea how to change that to have test1/test2 as a single value?

Eg:

```<code>test1/test2,
test3
</code>```

答:
Do you really need a regex here? How about:

```<code> $value = 'test1';
 $valid = in_array( $value, array( 'test1', 'test2', 'test3' ), true );
</code>```

That seems less intensive, but functional.

Title: How to separate regex values?

Body:
the user makes a selection and I want to test if the selection is valid. So e.g.

 preg_match("/(test1/test2|test3)/", $value)

The problem is that one value is test1/test2, but each test is treated as a single value.  Any idea how to change that to have test1/test2 as a single value?

Eg:

test1/test2,
test3

Body:
Do you really need a regex here? How about:

 $value = 'test1';
 $valid = in_array( $value, array( 'test1', 'test2', 'test3' ), true );

That seems less intensive, but functional.


问:
Display and check for multiple key in php echo
I am trying to output a key value from JSON data and want to check for multiple keys.

I want to display the title of a movie and or tv show.

```<code>                        if($channel=="multi" AND !empty($movies)){
                        foreach ($movies as $movie) {
                            if(!empty($movie['poster_path'])){
                                echo '<div class="mov">
                            <a href="'.$movie['media_type'].'/'.$movie['id'].'">
                                <img src="https://image.tmdb.org/t/p/w185'.$movie['poster_path'].'">
                                <h2 class="title">'.$movie['title'].'</h2>
                            </a>
                        </div>';
                            }
                        }
                    }
</code>```

whereas
'.$movie['title'].'
 also needs to check for
'.$movie['name'].'

How can I check for both 'title' and 'name' in the same go?

I am pretty new to all this and learning on the go. So please correct me as well if there are any mistakes in my coding!

答:
If you're trying to get $movie['title'] or $movie['name'] (because you're unsure what the variable will be called) you can use an if statement. (This is not a pretty way of writing it -- but it is the clearest way).

```<code> if($channel=="multi" AND !empty($movies)){
   foreach ($movies as $movie) {
     if(!empty($movie['poster_path'])){
       echo '<div class="mov">
             <a href="'.$movie['media_type'].'/'.$movie['id'].'">
               <img src="https://image.tmdb.org/t/p/w185'.$movie['poster_path'].'">
               <h2 class="title">';

               //AN IF STATEMENT TO CHOOSE EITHER TITLE OR MOVIE
               if(!empty($movie['title']) {
                 echo $movie['title'];
               } else {
                 echo $movie['name'];
               }

              echo .'</h2>
              </a>
              </div>';
     }
   }
 }
</code>```

Alternatively, you could also make $movie['title'] equal to $movie['name'] if it is not blank.

```<code> if($channel=="multi" AND !empty($movies)){
   foreach ($movies as $movie) {
     if(!empty($movie['poster_path'])){
    // MAKE MOVIE TITLE = MOVIE NAME IF IT IS NOT BLANK
     if(!empty($movie['name'])){
       $movie['title'] = $movie['name'];
     }
       echo '<div class="mov">
             <a href="'.$movie['media_type'].'/'.$movie['id'].'">
               <img src="https://image.tmdb.org/t/p/w185'.$movie['poster_path'].'">
               <h2 class="title">'.
                 $movie['title'].
              '</h2>
              </a>
              </div>';
     }
   }
 }
</code>```

There are usually many ways to solve a problem. Think through the logic. If this than that. If not this, than that instead.

Body:
I am trying to output a key value from JSON data and want to check for multiple keys.

I want to display the title of a movie and or tv show.

                        if($channel=="multi" AND !empty($movies)){
                        foreach ($movies as $movie) {
                            if(!empty($movie['poster_path'])){
                                echo '

'.$movie['title'].'

';
                            }
                        }
                    }

whereas
'.$movie['title'].'
 also needs to check for
'.$movie['name'].'

How can I check for both 'title' and 'name' in the same go?

I am pretty new to all this and learning on the go. So please correct me as well if there are any mistakes in my coding!

Body:
If you're trying to get $movie['title'] or $movie['name'] (because you're unsure what the variable will be called) you can use an if statement. (This is not a pretty way of writing it -- but it is the clearest way).

 if($channel=="multi" AND !empty($movies)){
   foreach ($movies as $movie) {
     if(!empty($movie['poster_path'])){
       echo '<div class="mov">
             <a href="'.$movie['media_type'].'/'.$movie['id'].'">
               <img src="https://image.tmdb.org/t/p/w185'.$movie['poster_path'].'">
               <h2 class="title">';

               //AN IF STATEMENT TO CHOOSE EITHER TITLE OR MOVIE
               if(!empty($movie['title']) {
                 echo $movie['title'];
               } else {
                 echo $movie['name'];
               }

              echo .'</h2>
              </a>
              </div>';
     }
   }
 }

Alternatively, you could also make $movie['title'] equal to $movie['name'] if it is not blank.

 if($channel=="multi" AND !empty($movies)){
   foreach ($movies as $movie) {
     if(!empty($movie['poster_path'])){
    // MAKE MOVIE TITLE = MOVIE NAME IF IT IS NOT BLANK
     if(!empty($movie['name'])){
       $movie['title'] = $movie['name'];
     }
       echo '<div class="mov">
             <a href="'.$movie['media_type'].'/'.$movie['id'].'">
               <img src="https://image.tmdb.org/t/p/w185'.$movie['poster_path'].'">
               <h2 class="title">'.
                 $movie['title'].
              '</h2>
              </a>
              </div>';
     }
   }
 }

There are usually many ways to solve a problem. Think through the logic. If this than that. If not this, than that instead.


问:
Can someone explain me this while loop what means?
```<code>while (a = b)
   ;
</code>```

I know that it will probably not be anything so complex but I don't understand what it will become

答:
```<code>void stringCAT(char *s1, char *s2)
{
    while(*s1 != '\0')
    {
        s1++;
    }

    for(; *s1 = *s2; s1++,s2++)
    {
        ;
    }
}
</code>```

The for loop includes your answer. The middle of for statement is condition like inside a while(). This for loop runs until *s2= '\0' and copies data from s2 to s1 at the same time. This is valid for the type of char.

Body:
while (a = b)
   ;

I know that it will probably not be anything so complex but I don't understand what it will become

Body:
void stringCAT(char *s1, char *s2)
{
    while(*s1 != '\0')
    {
        s1++;
    }

    for(; *s1 = *s2; s1++,s2++)
    {
        ;
    }
}

The for loop includes your answer. The middle of for statement is condition like inside a while(). This for loop runs until *s2= '\0' and copies data from s2 to s1 at the same time. This is valid for the type of char.


问:
Extra white space below table view using search bar Swift Xcode
I have a UITableView, When i'm scrolling down to the bottom there is extra white space almost in a size of a full cell at the bottom,
in that ViewController i have a search bar iv'e added this way:

On ViewDidLoad:

```<code>searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
searchController.searchBar.setValue("ביטול", forKey:"_cancelButtonText")
searchController.searchBar.placeholder = "חפש כאן..."
let searchTextField = searchController.searchBar.value(forKey: "_searchField") as! UITextField
searchTextField.textAlignment = NSTextAlignment.right

if #available(iOS 9.0, *) {
    searchController.searchBar.semanticContentAttribute = .forceRightToLeft
}
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.white]
if #available(iOS 9.0, *) {
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(attributes, for: .normal)
}
tableOrder.tableHeaderView = searchController.searchBar
</code>```

Iv'e found out that if i'm taking off the search bar code, The table view appearance is all good and when i'm bringing back the code that extra white space is coming back.

I've try to change the content insets value to none with no success.

Iv'e try to tic off the adjust scroll view insets from the ViewController

Iv'e checked the constraints to make sure they all good.

How can i make that white space to disappear ?

答:
You can try 2 ways to fix this problem:
1st:

```<code>tableView.contentInset = UIEdgeInsetsMake(0, 0, -29, 0);
</code>```

2nd:

```<code>tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNonzeroMagnitude))
</code>```

Or just:

```<code>tableView.tableFooterView = UIView()
</code>```

Body:
I have a UITableView, When i'm scrolling down to the bottom there is extra white space almost in a size of a full cell at the bottom,
in that ViewController i have a search bar iv'e added this way:

On ViewDidLoad:

searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
searchController.searchBar.setValue("ביטול", forKey:"_cancelButtonText")
searchController.searchBar.placeholder = "חפש כאן..."
let searchTextField = searchController.searchBar.value(forKey: "_searchField") as! UITextField
searchTextField.textAlignment = NSTextAlignment.right

if #available(iOS 9.0, *) {
    searchController.searchBar.semanticContentAttribute = .forceRightToLeft
}
let attributes = [NSAttributedStringKey.foregroundColor : UIColor.white]
if #available(iOS 9.0, *) {
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(attributes, for: .normal)
}
tableOrder.tableHeaderView = searchController.searchBar

Iv'e found out that if i'm taking off the search bar code, The table view appearance is all good and when i'm bringing back the code that extra white space is coming back.

I've try to change the content insets value to none with no success.

Iv'e try to tic off the adjust scroll view insets from the ViewController

Iv'e checked the constraints to make sure they all good.

How can i make that white space to disappear ?

Body:
You can try 2 ways to fix this problem:
1st:

tableView.contentInset = UIEdgeInsetsMake(0, 0, -29, 0);

2nd:

tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNonzeroMagnitude))

Or just:

tableView.tableFooterView = UIView()


问:
Trying to get property of non-object when display value of json response in Laravel
i try to display the value of json response . Its work well when I dd   @php dd( $user->irel__com_access_level->ID); @endphp inside blade view but when i try to display at table it return error which is

Trying to get property of non-object

My code display in table

```<code>     @foreach($content as $user)
      <td>{{ $user->irel__com_access_level->ID }}</td>
     @endforeach
</code>```

Here is my json response ....i want to display ID which is inside irel__com_access_level

```<code>{
    "data": [
        {

        {
            "ID": "banana",
            "PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g=",
            "NICK_NAME": "BANANA NANA NA",
            "PWD_INVALID_HIT": "0",
            "PWD_CREATE_DT": "2019/09/06 16:44:40",
            "INSTITUTION_ID": "C01",
            "ACL_ID": "L03",
            "LOGIN_DT": "                   ",
            "LOGIN_STS_ID": "N",
            "STS_ID": "C03",
            "TYPE_ID": "U00",
            "UPD_ID": "asmidah",
            "UPD_DT": "2019/09/06 16:44:40",
            "EMAIL_ID": "banana@gmail.com",
            "PHONE_NO_ID": "0",
            "HP_ID": "0101234567               ",
            "CRT_DATE_DELETED": "2019/09/06 16:44:40",
            "irel__com_access_level": {
                "ID": "L03",       // i want to display this
                "DESCRIPTION": "2NDLEVEL",
                "IS_CREATE": "N",
                "IS_READ": "Y",
                "IS_UPDATE": "Y",
                "IS_DELETE": "N",
                "STS_ID": "R01",
                "UPD_ID": "shukrimb",
                "UPD_DT": "2012/09/13 13:28:25"
           }
</code>```

my controller

```<code> private $client;

    public function __construct(){

        $this->client = new Client(['base_uri' => 'http://172.19.52.6/api/configuration/getUserIndex']);

    }

    public function index()
    {

        $response =  $this->client->get('getUserIndex');
         $content = json_decode($response->getBody());

         return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data]);

</code>```

i want to display ID which is inside irel__com_access_level in json response

答:
Just already solved this answer by adding isset </p>

```<code> <td>    @if(isset($user->irel__com_access_level))

         @if(trim($user->ACL_ID) == trim($user->irel__com_access_level->ID))
              {{ $user->irel__com_access_level->DESCRIPTION }}
         @endif

        @endif

     </td>
</code>```

Body:
i try to display the value of json response . Its work well when I dd   @php dd( $user->irel__com_access_level->ID); @endphp inside blade view but when i try to display at table it return error which is

Trying to get property of non-object

My code display in table

     @foreach($content as $user)
      {{ $user->irel__com_access_level->ID }}
     @endforeach

Here is my json response ....i want to display ID which is inside irel__com_access_level

{
    "data": [
        {

        {
            "ID": "banana",
            "PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g=",
            "NICK_NAME": "BANANA NANA NA",
            "PWD_INVALID_HIT": "0",
            "PWD_CREATE_DT": "2019/09/06 16:44:40",
            "INSTITUTION_ID": "C01",
            "ACL_ID": "L03",
            "LOGIN_DT": "                   ",
            "LOGIN_STS_ID": "N",
            "STS_ID": "C03",
            "TYPE_ID": "U00",
            "UPD_ID": "asmidah",
            "UPD_DT": "2019/09/06 16:44:40",
            "EMAIL_ID": "banana@gmail.com",
            "PHONE_NO_ID": "0",
            "HP_ID": "0101234567               ",
            "CRT_DATE_DELETED": "2019/09/06 16:44:40",
            "irel__com_access_level": {
                "ID": "L03",       // i want to display this
                "DESCRIPTION": "2NDLEVEL",
                "IS_CREATE": "N",
                "IS_READ": "Y",
                "IS_UPDATE": "Y",
                "IS_DELETE": "N",
                "STS_ID": "R01",
                "UPD_ID": "shukrimb",
                "UPD_DT": "2012/09/13 13:28:25"
           }

my controller

 private $client;

    public function __construct(){

        $this->client = new Client(['base_uri' => 'http://172.19.52.6/api/configuration/getUserIndex']);

    }

    public function index()
    {

        $response =  $this->client->get('getUserIndex');
         $content = json_decode($response->getBody());

         return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data]);

i want to display ID which is inside irel__com_access_level in json response

Body:
Just already solved this answer by adding isset

 <td>    @if(isset($user->irel__com_access_level))

         @if(trim($user->ACL_ID) == trim($user->irel__com_access_level->ID))
              {{ $user->irel__com_access_level->DESCRIPTION }}
         @endif

        @endif

     </td>


问:
Interrupting a script called within another script in tkinter
I have a program (say p1.py) which calls another python script (say p2.py) on click of a button. I would like to have a button which stops the execution of the p2.py but all the buttons freeze when it is running.

The only way to stop it is to use a keyboard interrupt in the console. I have read about the after() function but do I have to implement it in p1 or p2? Or is there any other way to do it without the after() function?

```<code>import tkinter
import os

window = tkinter.Tk()
window.title("Detecting")

def clicked():
    os.system('python extract_frames.py')

bt = tkinter.Button(window,text="Start",command=clicked)
bt.pack()

stop = tkinter.Button(window,text="Stop",command="break")     #also what command should I use for the interrupt?
stop.pack()

window.geometry('400x400')
window.mainloop()
</code>```

答:
You should use subprocess.Popen() instead of os.system():

```<code>import tkinter
import subprocess

proc = None

def clicked():
    global proc
    proc = subprocess.Popen(['python', 'extract_frames.py'])

def kill_task():
    if proc and proc.poll() is None:
        print('killing process ...')
        proc.kill()

window = tkinter.Tk()
window.geometry('400x400')
window.title("Detecting")

bt = tkinter.Button(window, text="Start", command=clicked)
bt.pack()

stop = tkinter.Button(window, text="Stop", command=kill_task)
stop.pack()

window.mainloop()
</code>```

Body:
I have a program (say p1.py) which calls another python script (say p2.py) on click of a button. I would like to have a button which stops the execution of the p2.py but all the buttons freeze when it is running.

The only way to stop it is to use a keyboard interrupt in the console. I have read about the after() function but do I have to implement it in p1 or p2? Or is there any other way to do it without the after() function?

import tkinter
import os

window = tkinter.Tk()
window.title("Detecting")

def clicked():
    os.system('python extract_frames.py')

bt = tkinter.Button(window,text="Start",command=clicked)
bt.pack()

stop = tkinter.Button(window,text="Stop",command="break")     #also what command should I use for the interrupt?
stop.pack()

window.geometry('400x400')
window.mainloop()

Body:
You should use subprocess.Popen() instead of os.system():

import tkinter
import subprocess

proc = None

def clicked():
    global proc
    proc = subprocess.Popen(['python', 'extract_frames.py'])

def kill_task():
    if proc and proc.poll() is None:
        print('killing process ...')
        proc.kill()

window = tkinter.Tk()
window.geometry('400x400')
window.title("Detecting")

bt = tkinter.Button(window, text="Start", command=clicked)
bt.pack()

stop = tkinter.Button(window, text="Stop", command=kill_task)
stop.pack()

window.mainloop()


问:
JsonMappingException: Type id handling not implemented, with enableDefaultTyping and custom serializer
I use Java 9, Jackson-core and jackson-databind 2.5.5
I would like to use custom serialization with the DefaultTyping.NON_FINAL option for writing class names in Json.

if I delete the default typing NON_FINAL, everything works.

When I add the NON_FINAL option, my custom serializer "MySerializer" is called and I have the exception JsonMappingException: Type id handling not implemented

```<code>public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enableDefaultTyping();
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(new MySerializer());

        objectMapper.registerModule(simpleModule);

        System.out.println(objectMapper.writeValueAsString(new MyObject(1)));
    }
}

public class MyObject {
    private int a = 0;

    public MyObject() {
    }

    public MyObject(int a) {
        this.a = a;
    }

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }
}

public class MySerializer extends StdSerializer<MyObject> {
    protected MySerializer() {
        super(MyObject.class);
    }

    public void serialize(MyObject myObject, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeNumberField("newNameForFieldA", myObject.getA());
        jsonGenerator.writeEndObject();
    }
}

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.5</version>
        </dependency>
    </dependencies>
</code>```

the result without NON_FINAL default typing :

{"newNameForFieldA":1}

the exception :

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Type id handling not implemented for type com.test.jackson.main2.MyObject (by serializer of type com.test.jackson.main2.MySerializer)
    at com.fasterxml.jackson.databind.SerializerProvider.mappingException(SerializerProvider.java:1047)
    at com.fasterxml.jackson.databind.JsonSerializer.serializeWithType(JsonSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer.serialize(TypeWrappedSerializer.java:32)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:129)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3387)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2781)
    at com.test.jackson.main2.Main.main(Main.java:18)

答:
When DefaultTyping.NON_FINAL is enable, the objectMapper will use the method "serializeWithType" defined in the class "JsonSerializer" to do the serialiaztion works if a custom serializer is defined.

So to solve the problem, you need to override the method "serializeWithType".

Body:
I use Java 9, Jackson-core and jackson-databind 2.5.5
I would like to use custom serialization with the DefaultTyping.NON_FINAL option for writing class names in Json.

if I delete the default typing NON_FINAL, everything works.

When I add the NON_FINAL option, my custom serializer "MySerializer" is called and I have the exception JsonMappingException: Type id handling not implemented

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enableDefaultTyping();
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(new MySerializer());

        objectMapper.registerModule(simpleModule);

        System.out.println(objectMapper.writeValueAsString(new MyObject(1)));
    }
}

public class MyObject {
    private int a = 0;

    public MyObject() {
    }

    public MyObject(int a) {
        this.a = a;
    }

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }
}

public class MySerializer extends StdSerializer<MyObject> {
    protected MySerializer() {
        super(MyObject.class);
    }

    public void serialize(MyObject myObject, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeNumberField("newNameForFieldA", myObject.getA());
        jsonGenerator.writeEndObject();
    }
}

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.5</version>
        </dependency>
    </dependencies>

the result without NON_FINAL default typing :

{"newNameForFieldA":1}

the exception :

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Type id handling not implemented for type com.test.jackson.main2.MyObject (by serializer of type com.test.jackson.main2.MySerializer)
    at com.fasterxml.jackson.databind.SerializerProvider.mappingException(SerializerProvider.java:1047)
    at com.fasterxml.jackson.databind.JsonSerializer.serializeWithType(JsonSerializer.java:142)
    at com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer.serialize(TypeWrappedSerializer.java:32)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:129)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3387)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2781)
    at com.test.jackson.main2.Main.main(Main.java:18)


问:
How this c++ code runs without definition of function
Can anyone explain the logic behind the working of defined function in this program. This gives the correct output in this case even after commenting the whole logic of function.</p>

```<code>#include <iostream>
using namespace std;
void swap(int *a, int *b)
{ /*
int temp=0;
 temp= *a;
 *a= *b;
 *b=temp;
*/
}
int main()
{
    int x, y;
    cout << "This program is the demo of function call by pointer \n\n";
    cout << "Enter the value of x & y \n";
    cout << "x: ";
    cin >> x;
    cout << "y: ";
    cin >> y;
    cout << "Value befor swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    swap(x, y);
    cout << "Value after swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    return 0;
}
</code>```

答:
swap is ambiguous between your definition and std::swap.
If you want to keep the using namespace std you need to encapsulate your method declaration in a class or a namespace and call YourNamespaceOrClass::swap(a, b) explicitely

Body:
Can anyone explain the logic behind the working of defined function in this program. This gives the correct output in this case even after commenting the whole logic of function.

#include <iostream>
using namespace std;
void swap(int *a, int *b)
{ /*
int temp=0;
 temp= *a;
 *a= *b;
 *b=temp;
*/
}
int main()
{
    int x, y;
    cout << "This program is the demo of function call by pointer \n\n";
    cout << "Enter the value of x & y \n";
    cout << "x: ";
    cin >> x;
    cout << "y: ";
    cin >> y;
    cout << "Value befor swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    swap(x, y);
    cout << "Value after swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    return 0;
}


问:
how to test Cloud Functions for Firebase locally on pc
Today Firebase released its brand new product Cloud Functions for Firebase and I just created a hello world function and deploy it on my existing firebase project.

It looks like it bundles all dependencies and upload it to firebase just like aws lambda function does. But it takes too much time to be done even on minor changes in code and also need a good connectivity of internet . If you are offline for some reason, you are just in dark what code you are writing until you have a way to execute and test that functions offline on your local machine.

Is there any way to test Cloud Functions for Firebase locally?

答:
>> Is there any way to test Cloud Functions for Firebase locally?

You can use the following command to start a firebase shell (execute in your functions directory):

```<code>npm run build && firebase functions:shell
</code>```

You can invoke your functions in the shell like so:

```<code>helloWorld()
</code>```

Refer this link for more information.

Body:
>> Is there any way to test Cloud Functions for Firebase locally?

You can use the following command to start a firebase shell (execute in your functions directory):

npm run build && firebase functions:shell

You can invoke your functions in the shell like so:

helloWorld()

Refer this link for more information.


问:
Execute a function "before each" method of the same class in java
I have several methods in a class that require a boolean to be set to true in order to execute correctly.

I could write the if statement in each method, but it is not convenient if I or someone else wants to ad another method. I or he could forget about the check.

Is there a way in java to execute a method before each other methods (exactly like JUnit does with @BeforeEach ) in a class ?

Edit: Lots of very interesting techniques/answers/concepts proposed. I'll be in touch when I've understood them. Thanks.

答: Considering my use case, it was a bit overkill to use AOP or other concepts. So I basically did a check in each functions.</p>


问:
Navigation Drawer For multiple Activities Without Selecting Navigation Drawer activity
I am new to android. I would like to implement a navigation drawer consisting of a list of items, which when clicked opens a new activity. Basically a navigation drawer across all the activities. When I select an item from the navigation drawer that particular activity opens.navigation drawer code is implemented by taking empty activity. I would like to implement navigation drawer functionality in all activities that activities are taken as empty activity in that activities already have some functionality along with this functionality the navigation drawer functionality also works. Please help me.

This is activity_header File

```<code><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer"
tools:context=".MainActivity">
<android.support.design.widget.NavigationView
    app:headerLayout="@layout/header"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:background="@color/white"
    app:menu="@menu/drawermenu"
    android:layout_gravity="start"
    android:id="@+id/navigationView"
    >
   </android.support.design.widget.NavigationView>
 </android.support.v4.widget.DrawerLayout>
</code>```

This is My Main Activity

```<code><GridView xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/gridview"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:columnWidth="90dp"
   android:numColumns="2"
   android:verticalSpacing="10dp"
   android:horizontalSpacing="10dp"
   android:stretchMode="columnWidth"
   android:gravity="center"
   android:layout_marginTop="30dp"/>
</code>```

This is Header Activity java code

```<code>public class HeaderActivity extends AppCompatActivity {

protected DrawerLayout myDrawerLayout;
protected ActionBarDrawerToggle toggle;
protected NavigationView navigationView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_header);

    myDrawerLayout=(DrawerLayout)findViewById(R.id.drawer);
    navigationView=(NavigationView) findViewById(R.id.navigationView);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

            Log.e("log_cat", "Error Response" + "Error");

            switch (menuItem.getItemId())
            {
                case R.id.dashboard:
                    Toast.makeText(HeaderActivity.this,"Dashboard Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.devotional:
                    Toast.makeText(HeaderActivity.this,"devotional Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.inspiration:
                    Toast.makeText(HeaderActivity.this,"inspiration Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.happy:
                    Toast.makeText(HeaderActivity.this,"happy Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.sad:
                    Toast.makeText(HeaderActivity.this,"sad Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.love:
                    Toast.makeText(HeaderActivity.this,"love Clicked",Toast.LENGTH_LONG).show();
                    break;

            }
            return false;
        }
    });
    toggle = new ActionBarDrawerToggle(
            this,
            myDrawerLayout,
            R.string.open,
            R.string.close
    ) {
        public void onDrawerClosed(View view) {
            //Snackbar.make(view, R.string.drawer_close, Snackbar.LENGTH_SHORT).show();
        }

        public void onDrawerOpened(View drawerView) {
            //Snackbar.make(drawerView, R.string.drawer_open, Snackbar.LENGTH_SHORT).show();
        }
    };
    myDrawerLayout.addDrawerListener(toggle);
    toggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // gridview.setAdapter(i);

}

@Override
public boolean onOptionsItemSelected (MenuItem item) {
    if (toggle.onOptionsItemSelected (item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);

}
</code>```

}

This is My main activity java code

public class MainActivity extends HeaderActivity  {

```<code>GridView grid;
public static String[] osNameList = {
        "Devotional",
        "Inspirational",
        "Happy",
        "Sad",
        "Love"

} ;
public static int[] osImages = {
        R.drawable.devotional,
        R.drawable.inspirational,
        R.drawable.happy,
        R.drawable.sad,
        R.drawable.love

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getLayoutInflater().inflate(R.layout.activity_main, myDrawerLayout);
    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this, osNameList, osImages));

}
</code>```

}

In this code setNavigationItemSelectedListener is not working in mainactivity but setOnClickListener on Grid is working. When we click on any navigation menu element it move to that activity.

答: there is two way to implement the drawer in all activity you can use fragment or you can create a  NavigationDrawer into base activity and implement this where you want. Same Navigation Drawer in different Activities </p>

Body:
I am new to android. I would like to implement a navigation drawer consisting of a list of items, which when clicked opens a new activity. Basically a navigation drawer across all the activities. When I select an item from the navigation drawer that particular activity opens.navigation drawer code is implemented by taking empty activity. I would like to implement navigation drawer functionality in all activities that activities are taken as empty activity in that activities already have some functionality along with this functionality the navigation drawer functionality also works. Please help me.

This is activity_header File

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer"
tools:context=".MainActivity">
<android.support.design.widget.NavigationView
    app:headerLayout="@layout/header"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:background="@color/white"
    app:menu="@menu/drawermenu"
    android:layout_gravity="start"
    android:id="@+id/navigationView"
    >
   </android.support.design.widget.NavigationView>
 </android.support.v4.widget.DrawerLayout>

This is My Main Activity

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/gridview"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:columnWidth="90dp"
   android:numColumns="2"
   android:verticalSpacing="10dp"
   android:horizontalSpacing="10dp"
   android:stretchMode="columnWidth"
   android:gravity="center"
   android:layout_marginTop="30dp"/>

This is Header Activity java code

public class HeaderActivity extends AppCompatActivity {

protected DrawerLayout myDrawerLayout;
protected ActionBarDrawerToggle toggle;
protected NavigationView navigationView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_header);

    myDrawerLayout=(DrawerLayout)findViewById(R.id.drawer);
    navigationView=(NavigationView) findViewById(R.id.navigationView);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

            Log.e("log_cat", "Error Response" + "Error");

            switch (menuItem.getItemId())
            {
                case R.id.dashboard:
                    Toast.makeText(HeaderActivity.this,"Dashboard Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.devotional:
                    Toast.makeText(HeaderActivity.this,"devotional Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.inspiration:
                    Toast.makeText(HeaderActivity.this,"inspiration Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.happy:
                    Toast.makeText(HeaderActivity.this,"happy Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.sad:
                    Toast.makeText(HeaderActivity.this,"sad Clicked",Toast.LENGTH_LONG).show();
                    break;

                case R.id.love:
                    Toast.makeText(HeaderActivity.this,"love Clicked",Toast.LENGTH_LONG).show();
                    break;

            }
            return false;
        }
    });
    toggle = new ActionBarDrawerToggle(
            this,
            myDrawerLayout,
            R.string.open,
            R.string.close
    ) {
        public void onDrawerClosed(View view) {
            //Snackbar.make(view, R.string.drawer_close, Snackbar.LENGTH_SHORT).show();
        }

        public void onDrawerOpened(View drawerView) {
            //Snackbar.make(drawerView, R.string.drawer_open, Snackbar.LENGTH_SHORT).show();
        }
    };
    myDrawerLayout.addDrawerListener(toggle);
    toggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // gridview.setAdapter(i);

}

@Override
public boolean onOptionsItemSelected (MenuItem item) {
    if (toggle.onOptionsItemSelected (item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);

}

}

This is My main activity java code

public class MainActivity extends HeaderActivity  {

GridView grid;
public static String[] osNameList = {
        "Devotional",
        "Inspirational",
        "Happy",
        "Sad",
        "Love"

} ;
public static int[] osImages = {
        R.drawable.devotional,
        R.drawable.inspirational,
        R.drawable.happy,
        R.drawable.sad,
        R.drawable.love

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getLayoutInflater().inflate(R.layout.activity_main, myDrawerLayout);
    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this, osNameList, osImages));

}

}

In this code setNavigationItemSelectedListener is not working in mainactivity but setOnClickListener on Grid is working. When we click on any navigation menu element it move to that activity.