qid
int64
2
74.7M
question
stringlengths
31
65.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
4
63.3k
response_k
stringlengths
4
60.5k
50,149,562
With old Jupyter notebooks, I could create interactive plots via: ``` import matplotlib.pyplot as plt %matplotlib notebook x = [1,2,3] y = [4,5,6] plt.figure() plt.plot(x,y) ``` However, in JupyterLab, this gives an error: ``` JavaScript output is disabled in JupyterLab ``` I have also tried the magic (with [`jupyter-matplotlib`](https://github.com/matplotlib/jupyter-matplotlib "jupyter-matplotlib") installed): ``` %matplotlib ipympl ``` But that just returns: ``` FigureCanvasNbAgg() ``` Inline plots work, but they are not interactive plots: ``` %matplotlib inline ```
2018/05/03
[ "https://Stackoverflow.com/questions/50149562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233329/" ]
As per [Georgy's suggestion](https://stackoverflow.com/questions/50149562/jupyterlab-interactive-plot#comment87317234_50149562), this was caused by Node.js not being installed.
Summary ======= In a complex setup, where `jupyter-lab` process and the Jupyter/IPython kernel process are running in different Python virtual environments, pay attention to Jupyter-related Python package and Jupyter extension (e.g. `ipympl`, `jupyter-matplotlib`) versions and their compatibility between the environments. And even in single Python virtual environment make sure you comply with the [`ipympl` compatibility table](https://github.com/matplotlib/ipympl/blob/0.6.3/README.md#install-an-old-jupyterlab-extension). Example ======= A couple of examples how to run JupyterLab. Simple(st) ---------- The simplest cross-platform way to run JupyterLab, I guess, is running it from a Docker container. You can build and run JupyterLab 3 container like this. ``` docker run --name jupyter -it -p 8888:8888 \ # This line on a Linux- and non-user-namespaced Docker will "share" # the directory between Docker host and container, and run from the user. -u 1000 -v $HOME/Documents/notebooks:/tmp/notebooks \ -e HOME=/tmp/jupyter python:3.8 bash -c " mkdir /tmp/jupyter; \ pip install --user 'jupyterlab < 4' 'ipympl < 0.8' pandas matplotlib; \ /tmp/jupyter/.local/bin/jupyter lab --ip=0.0.0.0 --port 8888 \ --no-browser --notebook-dir /tmp/notebooks; " ``` When it finishes (and it'll take a while), the bottommost lines in the terminal should be something like. ``` To access the server, open this file in a browser: ... http://127.0.0.1:8888/lab?token=abcdef... ``` You can just click on that link and JupyterLab should open in your browser. Once you shut down the JupyterLab instance the container will stop. You can restart it with `docker start -ai jupyter`. [![jupyterlab 3](https://i.stack.imgur.com/H7MVm.png)](https://i.stack.imgur.com/H7MVm.png) Complex ------- This [GitHub Gist](https://gist.github.com/saaj/455ac4e9986da06c0b44901d42525dc5) illustrates the idea how to build a Python virtual environment with JupyterLab 2 and also building all required extensions with Nodejs in the container, without installing Nodejs on host system. With JupyterLab 3 and [pre-build extensions](https://jupyterlab.readthedocs.io/en/stable/getting_started/changelog.html#prebuilt-extensions) this approach gets less relevant. Context ======= I was scratching my head today while debugging the `%matplotlib widget` not working in JupyterLab 2. I have separate pre-built JupyterLab venv (as described above) which powers local JupyterLab as Chromium "app mode" (i.e. `c.LabApp.browser = 'chromium-browser --app=%s'` in the config), and a few IPython kernels from simple Python venvs with specific dependencies (rarely change) and an application exposing itself as an IPython kernel. The issue with the interactive "widget" mode manifested in different ways. For instance, having * in JupyterLab "host" venv: jupyter-matplotlib v0.7.4 extension and `ipympl==0.6.3` * in the kernel venv: `ipympl==0.7.0` and `matplotlib==3.4.2` In the browser console I had these errors: * `Error: Module jupyter-matplotlib, semver range ^0.9.0 is not registered as a widget module` * `Error: Could not create a model.` * `Could not instantiate widget` In the JupyterLab UI: * `%matplotlib widget` succeeds on restart * Charts stuck in "Loading widget..." * Nothing on re-run of the cell with chart output * On previous attempts `%matplotlib widget` could raise something like `KeyError: '97acd0c8fb504a2288834b349003b4ae'` On downgrade of `ipympl==0.6.3` in the kernel venv in the browser console: * `Could not instantiate widget` * `Exception opening new comm` * `Error: Could not create a model.` * `Module jupyter-matplotlib, semver range ^0.8.3 is not registered as a widget module` Once I made the packages/extensions according to [`ipympl` compatibility table](https://github.com/matplotlib/ipympl/blob/0.6.3/README.md#install-an-old-jupyterlab-extension): * in JupyterLab "host" venv: jupyter-matplotlib v0.8.3 extension, `ipympl==0.6.3` * in the kernel venv: `ipympl==0.6.3`, `matplotlib==3.3.4` It more or less works as expected. Well, there are verious minor glitches like except I put `%matplotlib widget` per cell with chart, say on restart, the first chart "accumulates" all the contents of all the charts in the notebook. With `%matplotlib widget` per cell, only one chart is "active" at a time. And on restart only last widget is rendered (but manual re-run of a cell remediates).
50,149,562
With old Jupyter notebooks, I could create interactive plots via: ``` import matplotlib.pyplot as plt %matplotlib notebook x = [1,2,3] y = [4,5,6] plt.figure() plt.plot(x,y) ``` However, in JupyterLab, this gives an error: ``` JavaScript output is disabled in JupyterLab ``` I have also tried the magic (with [`jupyter-matplotlib`](https://github.com/matplotlib/jupyter-matplotlib "jupyter-matplotlib") installed): ``` %matplotlib ipympl ``` But that just returns: ``` FigureCanvasNbAgg() ``` Inline plots work, but they are not interactive plots: ``` %matplotlib inline ```
2018/05/03
[ "https://Stackoverflow.com/questions/50149562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233329/" ]
As per [Georgy's suggestion](https://stackoverflow.com/questions/50149562/jupyterlab-interactive-plot#comment87317234_50149562), this was caused by Node.js not being installed.
Steps for JupyterLab 3.\* ========================= I had previously used [Mateen](https://stackoverflow.com/users/365102/mateen-ulhaq)'s [answer](https://stackoverflow.com/a/55848505/10705616) several times, but when I tried them with JupyterLab 3.0.7 I found that `jupyter labextension install @jupyter-widgets/jupyterlab-manager` returned an error and I had broken widgets. After a lot of headaches and googling I thought I would post the solution for anyone else who finds themselves here. The steps are now simplified, and I was able to get back to working interactive plots with the following: 1. `pip install jupyterlab` 2. `pip install ipympl` 3. Decorate with `%matplotlib widget` Step 2 will automatically take care of the rest of the dependencies, including the replacements for (the now depreciated?) `@jupyter-widgets/jupyterlab-manager` Hope this saves someone else some time!
50,149,562
With old Jupyter notebooks, I could create interactive plots via: ``` import matplotlib.pyplot as plt %matplotlib notebook x = [1,2,3] y = [4,5,6] plt.figure() plt.plot(x,y) ``` However, in JupyterLab, this gives an error: ``` JavaScript output is disabled in JupyterLab ``` I have also tried the magic (with [`jupyter-matplotlib`](https://github.com/matplotlib/jupyter-matplotlib "jupyter-matplotlib") installed): ``` %matplotlib ipympl ``` But that just returns: ``` FigureCanvasNbAgg() ``` Inline plots work, but they are not interactive plots: ``` %matplotlib inline ```
2018/05/03
[ "https://Stackoverflow.com/questions/50149562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233329/" ]
Steps for JupyterLab 3.\* ========================= I had previously used [Mateen](https://stackoverflow.com/users/365102/mateen-ulhaq)'s [answer](https://stackoverflow.com/a/55848505/10705616) several times, but when I tried them with JupyterLab 3.0.7 I found that `jupyter labextension install @jupyter-widgets/jupyterlab-manager` returned an error and I had broken widgets. After a lot of headaches and googling I thought I would post the solution for anyone else who finds themselves here. The steps are now simplified, and I was able to get back to working interactive plots with the following: 1. `pip install jupyterlab` 2. `pip install ipympl` 3. Decorate with `%matplotlib widget` Step 2 will automatically take care of the rest of the dependencies, including the replacements for (the now depreciated?) `@jupyter-widgets/jupyterlab-manager` Hope this saves someone else some time!
Summary ======= In a complex setup, where `jupyter-lab` process and the Jupyter/IPython kernel process are running in different Python virtual environments, pay attention to Jupyter-related Python package and Jupyter extension (e.g. `ipympl`, `jupyter-matplotlib`) versions and their compatibility between the environments. And even in single Python virtual environment make sure you comply with the [`ipympl` compatibility table](https://github.com/matplotlib/ipympl/blob/0.6.3/README.md#install-an-old-jupyterlab-extension). Example ======= A couple of examples how to run JupyterLab. Simple(st) ---------- The simplest cross-platform way to run JupyterLab, I guess, is running it from a Docker container. You can build and run JupyterLab 3 container like this. ``` docker run --name jupyter -it -p 8888:8888 \ # This line on a Linux- and non-user-namespaced Docker will "share" # the directory between Docker host and container, and run from the user. -u 1000 -v $HOME/Documents/notebooks:/tmp/notebooks \ -e HOME=/tmp/jupyter python:3.8 bash -c " mkdir /tmp/jupyter; \ pip install --user 'jupyterlab < 4' 'ipympl < 0.8' pandas matplotlib; \ /tmp/jupyter/.local/bin/jupyter lab --ip=0.0.0.0 --port 8888 \ --no-browser --notebook-dir /tmp/notebooks; " ``` When it finishes (and it'll take a while), the bottommost lines in the terminal should be something like. ``` To access the server, open this file in a browser: ... http://127.0.0.1:8888/lab?token=abcdef... ``` You can just click on that link and JupyterLab should open in your browser. Once you shut down the JupyterLab instance the container will stop. You can restart it with `docker start -ai jupyter`. [![jupyterlab 3](https://i.stack.imgur.com/H7MVm.png)](https://i.stack.imgur.com/H7MVm.png) Complex ------- This [GitHub Gist](https://gist.github.com/saaj/455ac4e9986da06c0b44901d42525dc5) illustrates the idea how to build a Python virtual environment with JupyterLab 2 and also building all required extensions with Nodejs in the container, without installing Nodejs on host system. With JupyterLab 3 and [pre-build extensions](https://jupyterlab.readthedocs.io/en/stable/getting_started/changelog.html#prebuilt-extensions) this approach gets less relevant. Context ======= I was scratching my head today while debugging the `%matplotlib widget` not working in JupyterLab 2. I have separate pre-built JupyterLab venv (as described above) which powers local JupyterLab as Chromium "app mode" (i.e. `c.LabApp.browser = 'chromium-browser --app=%s'` in the config), and a few IPython kernels from simple Python venvs with specific dependencies (rarely change) and an application exposing itself as an IPython kernel. The issue with the interactive "widget" mode manifested in different ways. For instance, having * in JupyterLab "host" venv: jupyter-matplotlib v0.7.4 extension and `ipympl==0.6.3` * in the kernel venv: `ipympl==0.7.0` and `matplotlib==3.4.2` In the browser console I had these errors: * `Error: Module jupyter-matplotlib, semver range ^0.9.0 is not registered as a widget module` * `Error: Could not create a model.` * `Could not instantiate widget` In the JupyterLab UI: * `%matplotlib widget` succeeds on restart * Charts stuck in "Loading widget..." * Nothing on re-run of the cell with chart output * On previous attempts `%matplotlib widget` could raise something like `KeyError: '97acd0c8fb504a2288834b349003b4ae'` On downgrade of `ipympl==0.6.3` in the kernel venv in the browser console: * `Could not instantiate widget` * `Exception opening new comm` * `Error: Could not create a model.` * `Module jupyter-matplotlib, semver range ^0.8.3 is not registered as a widget module` Once I made the packages/extensions according to [`ipympl` compatibility table](https://github.com/matplotlib/ipympl/blob/0.6.3/README.md#install-an-old-jupyterlab-extension): * in JupyterLab "host" venv: jupyter-matplotlib v0.8.3 extension, `ipympl==0.6.3` * in the kernel venv: `ipympl==0.6.3`, `matplotlib==3.3.4` It more or less works as expected. Well, there are verious minor glitches like except I put `%matplotlib widget` per cell with chart, say on restart, the first chart "accumulates" all the contents of all the charts in the notebook. With `%matplotlib widget` per cell, only one chart is "active" at a time. And on restart only last widget is rendered (but manual re-run of a cell remediates).
50,149,562
With old Jupyter notebooks, I could create interactive plots via: ``` import matplotlib.pyplot as plt %matplotlib notebook x = [1,2,3] y = [4,5,6] plt.figure() plt.plot(x,y) ``` However, in JupyterLab, this gives an error: ``` JavaScript output is disabled in JupyterLab ``` I have also tried the magic (with [`jupyter-matplotlib`](https://github.com/matplotlib/jupyter-matplotlib "jupyter-matplotlib") installed): ``` %matplotlib ipympl ``` But that just returns: ``` FigureCanvasNbAgg() ``` Inline plots work, but they are not interactive plots: ``` %matplotlib inline ```
2018/05/03
[ "https://Stackoverflow.com/questions/50149562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233329/" ]
To enable the jupyter-matplotlib backend, use the matplotlib Jupyter magic: ``` %matplotlib widget import matplotlib.pyplot as plt plt.figure() x = [1,2,3] y = [4,5,6] plt.plot(x,y) ``` More info here [jupyter-matplotlib on GitHub](https://github.com/matplotlib/jupyter-matplotlib) [![Screenshot Jupyter Lab](https://i.stack.imgur.com/Gwgiz.png)](https://i.stack.imgur.com/Gwgiz.png)
This [solution](https://www.allendowney.com/blog/2019/07/25/matplotlib-animation-in-jupyter/) works in jupyterlab ``` import numpy as np import matplotlib.pyplot as plt from IPython.display import clear_output n = 10 a = np.zeros((n, n)) plt.figure() for i in range(n): plt.imshow(a) plt.show() a[i, i] = 1 clear_output(wait=True) ```
50,149,562
With old Jupyter notebooks, I could create interactive plots via: ``` import matplotlib.pyplot as plt %matplotlib notebook x = [1,2,3] y = [4,5,6] plt.figure() plt.plot(x,y) ``` However, in JupyterLab, this gives an error: ``` JavaScript output is disabled in JupyterLab ``` I have also tried the magic (with [`jupyter-matplotlib`](https://github.com/matplotlib/jupyter-matplotlib "jupyter-matplotlib") installed): ``` %matplotlib ipympl ``` But that just returns: ``` FigureCanvasNbAgg() ``` Inline plots work, but they are not interactive plots: ``` %matplotlib inline ```
2018/05/03
[ "https://Stackoverflow.com/questions/50149562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233329/" ]
JupyterLab 3.0+ --------------- 1. Install `jupyterlab` and `ipympl`. For `pip` users: ``` pip install --upgrade jupyterlab ipympl ``` For `conda` users: ``` conda update -c conda-forge jupyterlab ipympl ``` 2. Restart JupyterLab. 3. Decorate the cell containing plotting code with the header: ``` %matplotlib widget # plotting code goes here ``` JupyterLab 2.0 -------------- 1. Install `nodejs`, e.g. `conda install -c conda-forge nodejs`. 2. Install `ipympl`, e.g. `conda install -c conda-forge ipympl`. 3. [Optional, but recommended.] Update JupyterLab, e.g. `conda update -c conda-forge jupyterlab==2.2.9==py_0`. 4. [Optional, but recommended.] For a local user installation, run: `export JUPYTERLAB_DIR="$HOME/.local/share/jupyter/lab"`. 5. Install extensions: ``` jupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter labextension install jupyter-matplotlib ``` 6. Enable widgets: `jupyter nbextension enable --py widgetsnbextension`. 7. Restart JupyterLab. 8. Decorate with `%matplotlib widget`.
To enable the jupyter-matplotlib backend, use the matplotlib Jupyter magic: ``` %matplotlib widget import matplotlib.pyplot as plt plt.figure() x = [1,2,3] y = [4,5,6] plt.plot(x,y) ``` More info here [jupyter-matplotlib on GitHub](https://github.com/matplotlib/jupyter-matplotlib) [![Screenshot Jupyter Lab](https://i.stack.imgur.com/Gwgiz.png)](https://i.stack.imgur.com/Gwgiz.png)
50,149,562
With old Jupyter notebooks, I could create interactive plots via: ``` import matplotlib.pyplot as plt %matplotlib notebook x = [1,2,3] y = [4,5,6] plt.figure() plt.plot(x,y) ``` However, in JupyterLab, this gives an error: ``` JavaScript output is disabled in JupyterLab ``` I have also tried the magic (with [`jupyter-matplotlib`](https://github.com/matplotlib/jupyter-matplotlib "jupyter-matplotlib") installed): ``` %matplotlib ipympl ``` But that just returns: ``` FigureCanvasNbAgg() ``` Inline plots work, but they are not interactive plots: ``` %matplotlib inline ```
2018/05/03
[ "https://Stackoverflow.com/questions/50149562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233329/" ]
To enable the jupyter-matplotlib backend, use the matplotlib Jupyter magic: ``` %matplotlib widget import matplotlib.pyplot as plt plt.figure() x = [1,2,3] y = [4,5,6] plt.plot(x,y) ``` More info here [jupyter-matplotlib on GitHub](https://github.com/matplotlib/jupyter-matplotlib) [![Screenshot Jupyter Lab](https://i.stack.imgur.com/Gwgiz.png)](https://i.stack.imgur.com/Gwgiz.png)
Summary ======= In a complex setup, where `jupyter-lab` process and the Jupyter/IPython kernel process are running in different Python virtual environments, pay attention to Jupyter-related Python package and Jupyter extension (e.g. `ipympl`, `jupyter-matplotlib`) versions and their compatibility between the environments. And even in single Python virtual environment make sure you comply with the [`ipympl` compatibility table](https://github.com/matplotlib/ipympl/blob/0.6.3/README.md#install-an-old-jupyterlab-extension). Example ======= A couple of examples how to run JupyterLab. Simple(st) ---------- The simplest cross-platform way to run JupyterLab, I guess, is running it from a Docker container. You can build and run JupyterLab 3 container like this. ``` docker run --name jupyter -it -p 8888:8888 \ # This line on a Linux- and non-user-namespaced Docker will "share" # the directory between Docker host and container, and run from the user. -u 1000 -v $HOME/Documents/notebooks:/tmp/notebooks \ -e HOME=/tmp/jupyter python:3.8 bash -c " mkdir /tmp/jupyter; \ pip install --user 'jupyterlab < 4' 'ipympl < 0.8' pandas matplotlib; \ /tmp/jupyter/.local/bin/jupyter lab --ip=0.0.0.0 --port 8888 \ --no-browser --notebook-dir /tmp/notebooks; " ``` When it finishes (and it'll take a while), the bottommost lines in the terminal should be something like. ``` To access the server, open this file in a browser: ... http://127.0.0.1:8888/lab?token=abcdef... ``` You can just click on that link and JupyterLab should open in your browser. Once you shut down the JupyterLab instance the container will stop. You can restart it with `docker start -ai jupyter`. [![jupyterlab 3](https://i.stack.imgur.com/H7MVm.png)](https://i.stack.imgur.com/H7MVm.png) Complex ------- This [GitHub Gist](https://gist.github.com/saaj/455ac4e9986da06c0b44901d42525dc5) illustrates the idea how to build a Python virtual environment with JupyterLab 2 and also building all required extensions with Nodejs in the container, without installing Nodejs on host system. With JupyterLab 3 and [pre-build extensions](https://jupyterlab.readthedocs.io/en/stable/getting_started/changelog.html#prebuilt-extensions) this approach gets less relevant. Context ======= I was scratching my head today while debugging the `%matplotlib widget` not working in JupyterLab 2. I have separate pre-built JupyterLab venv (as described above) which powers local JupyterLab as Chromium "app mode" (i.e. `c.LabApp.browser = 'chromium-browser --app=%s'` in the config), and a few IPython kernels from simple Python venvs with specific dependencies (rarely change) and an application exposing itself as an IPython kernel. The issue with the interactive "widget" mode manifested in different ways. For instance, having * in JupyterLab "host" venv: jupyter-matplotlib v0.7.4 extension and `ipympl==0.6.3` * in the kernel venv: `ipympl==0.7.0` and `matplotlib==3.4.2` In the browser console I had these errors: * `Error: Module jupyter-matplotlib, semver range ^0.9.0 is not registered as a widget module` * `Error: Could not create a model.` * `Could not instantiate widget` In the JupyterLab UI: * `%matplotlib widget` succeeds on restart * Charts stuck in "Loading widget..." * Nothing on re-run of the cell with chart output * On previous attempts `%matplotlib widget` could raise something like `KeyError: '97acd0c8fb504a2288834b349003b4ae'` On downgrade of `ipympl==0.6.3` in the kernel venv in the browser console: * `Could not instantiate widget` * `Exception opening new comm` * `Error: Could not create a model.` * `Module jupyter-matplotlib, semver range ^0.8.3 is not registered as a widget module` Once I made the packages/extensions according to [`ipympl` compatibility table](https://github.com/matplotlib/ipympl/blob/0.6.3/README.md#install-an-old-jupyterlab-extension): * in JupyterLab "host" venv: jupyter-matplotlib v0.8.3 extension, `ipympl==0.6.3` * in the kernel venv: `ipympl==0.6.3`, `matplotlib==3.3.4` It more or less works as expected. Well, there are verious minor glitches like except I put `%matplotlib widget` per cell with chart, say on restart, the first chart "accumulates" all the contents of all the charts in the notebook. With `%matplotlib widget` per cell, only one chart is "active" at a time. And on restart only last widget is rendered (but manual re-run of a cell remediates).
50,149,562
With old Jupyter notebooks, I could create interactive plots via: ``` import matplotlib.pyplot as plt %matplotlib notebook x = [1,2,3] y = [4,5,6] plt.figure() plt.plot(x,y) ``` However, in JupyterLab, this gives an error: ``` JavaScript output is disabled in JupyterLab ``` I have also tried the magic (with [`jupyter-matplotlib`](https://github.com/matplotlib/jupyter-matplotlib "jupyter-matplotlib") installed): ``` %matplotlib ipympl ``` But that just returns: ``` FigureCanvasNbAgg() ``` Inline plots work, but they are not interactive plots: ``` %matplotlib inline ```
2018/05/03
[ "https://Stackoverflow.com/questions/50149562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233329/" ]
JupyterLab 3.0+ --------------- 1. Install `jupyterlab` and `ipympl`. For `pip` users: ``` pip install --upgrade jupyterlab ipympl ``` For `conda` users: ``` conda update -c conda-forge jupyterlab ipympl ``` 2. Restart JupyterLab. 3. Decorate the cell containing plotting code with the header: ``` %matplotlib widget # plotting code goes here ``` JupyterLab 2.0 -------------- 1. Install `nodejs`, e.g. `conda install -c conda-forge nodejs`. 2. Install `ipympl`, e.g. `conda install -c conda-forge ipympl`. 3. [Optional, but recommended.] Update JupyterLab, e.g. `conda update -c conda-forge jupyterlab==2.2.9==py_0`. 4. [Optional, but recommended.] For a local user installation, run: `export JUPYTERLAB_DIR="$HOME/.local/share/jupyter/lab"`. 5. Install extensions: ``` jupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter labextension install jupyter-matplotlib ``` 6. Enable widgets: `jupyter nbextension enable --py widgetsnbextension`. 7. Restart JupyterLab. 8. Decorate with `%matplotlib widget`.
As per [Georgy's suggestion](https://stackoverflow.com/questions/50149562/jupyterlab-interactive-plot#comment87317234_50149562), this was caused by Node.js not being installed.
50,149,562
With old Jupyter notebooks, I could create interactive plots via: ``` import matplotlib.pyplot as plt %matplotlib notebook x = [1,2,3] y = [4,5,6] plt.figure() plt.plot(x,y) ``` However, in JupyterLab, this gives an error: ``` JavaScript output is disabled in JupyterLab ``` I have also tried the magic (with [`jupyter-matplotlib`](https://github.com/matplotlib/jupyter-matplotlib "jupyter-matplotlib") installed): ``` %matplotlib ipympl ``` But that just returns: ``` FigureCanvasNbAgg() ``` Inline plots work, but they are not interactive plots: ``` %matplotlib inline ```
2018/05/03
[ "https://Stackoverflow.com/questions/50149562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233329/" ]
JupyterLab 3.0+ --------------- 1. Install `jupyterlab` and `ipympl`. For `pip` users: ``` pip install --upgrade jupyterlab ipympl ``` For `conda` users: ``` conda update -c conda-forge jupyterlab ipympl ``` 2. Restart JupyterLab. 3. Decorate the cell containing plotting code with the header: ``` %matplotlib widget # plotting code goes here ``` JupyterLab 2.0 -------------- 1. Install `nodejs`, e.g. `conda install -c conda-forge nodejs`. 2. Install `ipympl`, e.g. `conda install -c conda-forge ipympl`. 3. [Optional, but recommended.] Update JupyterLab, e.g. `conda update -c conda-forge jupyterlab==2.2.9==py_0`. 4. [Optional, but recommended.] For a local user installation, run: `export JUPYTERLAB_DIR="$HOME/.local/share/jupyter/lab"`. 5. Install extensions: ``` jupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter labextension install jupyter-matplotlib ``` 6. Enable widgets: `jupyter nbextension enable --py widgetsnbextension`. 7. Restart JupyterLab. 8. Decorate with `%matplotlib widget`.
This [solution](https://www.allendowney.com/blog/2019/07/25/matplotlib-animation-in-jupyter/) works in jupyterlab ``` import numpy as np import matplotlib.pyplot as plt from IPython.display import clear_output n = 10 a = np.zeros((n, n)) plt.figure() for i in range(n): plt.imshow(a) plt.show() a[i, i] = 1 clear_output(wait=True) ```
50,149,562
With old Jupyter notebooks, I could create interactive plots via: ``` import matplotlib.pyplot as plt %matplotlib notebook x = [1,2,3] y = [4,5,6] plt.figure() plt.plot(x,y) ``` However, in JupyterLab, this gives an error: ``` JavaScript output is disabled in JupyterLab ``` I have also tried the magic (with [`jupyter-matplotlib`](https://github.com/matplotlib/jupyter-matplotlib "jupyter-matplotlib") installed): ``` %matplotlib ipympl ``` But that just returns: ``` FigureCanvasNbAgg() ``` Inline plots work, but they are not interactive plots: ``` %matplotlib inline ```
2018/05/03
[ "https://Stackoverflow.com/questions/50149562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233329/" ]
JupyterLab 3.0+ --------------- 1. Install `jupyterlab` and `ipympl`. For `pip` users: ``` pip install --upgrade jupyterlab ipympl ``` For `conda` users: ``` conda update -c conda-forge jupyterlab ipympl ``` 2. Restart JupyterLab. 3. Decorate the cell containing plotting code with the header: ``` %matplotlib widget # plotting code goes here ``` JupyterLab 2.0 -------------- 1. Install `nodejs`, e.g. `conda install -c conda-forge nodejs`. 2. Install `ipympl`, e.g. `conda install -c conda-forge ipympl`. 3. [Optional, but recommended.] Update JupyterLab, e.g. `conda update -c conda-forge jupyterlab==2.2.9==py_0`. 4. [Optional, but recommended.] For a local user installation, run: `export JUPYTERLAB_DIR="$HOME/.local/share/jupyter/lab"`. 5. Install extensions: ``` jupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter labextension install jupyter-matplotlib ``` 6. Enable widgets: `jupyter nbextension enable --py widgetsnbextension`. 7. Restart JupyterLab. 8. Decorate with `%matplotlib widget`.
Steps for JupyterLab 3.\* ========================= I had previously used [Mateen](https://stackoverflow.com/users/365102/mateen-ulhaq)'s [answer](https://stackoverflow.com/a/55848505/10705616) several times, but when I tried them with JupyterLab 3.0.7 I found that `jupyter labextension install @jupyter-widgets/jupyterlab-manager` returned an error and I had broken widgets. After a lot of headaches and googling I thought I would post the solution for anyone else who finds themselves here. The steps are now simplified, and I was able to get back to working interactive plots with the following: 1. `pip install jupyterlab` 2. `pip install ipympl` 3. Decorate with `%matplotlib widget` Step 2 will automatically take care of the rest of the dependencies, including the replacements for (the now depreciated?) `@jupyter-widgets/jupyterlab-manager` Hope this saves someone else some time!
12,725,968
This is driving me nuts, I have been through every article I have seen on Google and here and two days later, 101 variants later I am still no further forward. The success 201 works perfectly, I get an alert with bound items. The 404 doesn't work at all, no matter what I try the ErrorDesc is always undefined. I have got it working that it can hit this 404 function with a fixed string, but I want the user to know why there is an error. I have used fiddler to look at the request and response. It looks fine, both the request and response are well formed JSON: Raw Request: ``` {"Bedrooms":"3","BuildingsAD":"Yes","BuildingsMD":"No","BulidingSI":"100000","ContentsAD":"No","ContentsMD":"No","ContentsPOL":"No","ContentsSI":"5000","EffectiveDate":"03/10/2012 23:40:10","EL":"N","MD":"No","NCD":"1","POL":"No","PropType":"Terraced","RiskPostcode":"SW19 1TS","SchemeRef":"20","TA":"No","TenantTheft":"No","TenantType":"Professional","Theft":"No","TransactionDate":"03/10/2012 23:40:10","VolExcess":"250","YearBuilt":"2000 +","ErrorDesc":"123"} Raw Response: {"RatingId":"f5733e9d-bc9d-4026-8d5f-ce4f750a3a42","SchemeRef":"20","EffectiveDate":"03/10/2012 23:40:10","TransactionDate":"03/10/2012 23:40:10","Bedrooms":"3","BuildingsAD":"Yes","BuildingsMD":"No","BulidingSI":"100000","ContentsAD":"No","ContentsMD":"No","ContentsPOL":"No","ContentsSI":"5000","EL":"N","MD":"No","NCD":"1","POL":"No","PropType":"Terraced","RiskPostcode":"SW19 1TS","TA":"No","TenantTheft":"No","TenantType":"Professional","Theft":"No","VolExcess":"250","YearBuilt":"2000 +","Error":true,"ErrorDesc":"Rating Sheet not found"} <script type="text/javascript"> function CalcRating() { //create a Json object based on data entered by user var RatingItems = { AD: $("#AD").val(), AdminFee: $("#AdminFee").val(), Bedrooms: $("#Bedrooms").val(), BuildingsAD: $("#BuildingsAD").val(), BuildingsMD: $("#BuildingsMD").val(), BuildingsPremium: $("#BuildingsPremium").val(), BulidingSI: $("#BulidingSI").val(), ContentsAD: $("#ContentsAD").val(), ContentsMD: $("#ContentsMD").val(), ContentsPOL: $("#ContentsPOL").val(), ContentsPremium: $("#ContentsPremium").val(), ContentsSI: $("#ContentsSI").val(), EffectiveDate: $("#EffectiveDate").val(), EL: $("#EL").val(), IPT: $("#IPT").val(), MD: $("#MD").val(), NCD: $("#NCD").val(), POL: $("#POL").val(), PropType: $("#PropType").val(), RatingId: $("#RatingId").val(), RiskPostcode: $("#RiskPostcode").val(), SchemeRef: $("#SchemeRef").val(), TA: $("#TA").val(), TenantTheft: $("#TenantTheft").val(), TenantType: $("#TenantType").val(), Theft: $("#Theft").val(), TransactionDate: $("#TransactionDate").val(), TotalPremium: $("#TotalPremium").val(), VolExcess: $("#VolExcess").val(), YearBuilt: $("#YearBuilt").val(), ErrorDesc: "123" }; //call jQuery Ajax method which calls Json.stringify method to convert //the Json object into string and send it with post method $.ajax({ url: "/api/qsletpropertyom", data: JSON.stringify(RatingItems), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (result) { alert("Total Premium: " + result.TotalPremium + ", Total Buildings Premium " + result.BuildingsPremium + ", Total Contents Cover " + result.ContentsPremium + ", Admin Fee " + result.AdminFee); }, 404: function (result1) { alert(result.ErrorDesc); }, 500: function (result2) { alert("Unknown Error"); } } }); } ``` Please let me know the error of my ways!!
2012/10/04
[ "https://Stackoverflow.com/questions/12725968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/909301/" ]
Also you will have to modify the string format like this ``` sendData += "name=hello"; sendData += "&ox_score=10"; sendData += "&between_score=10"; sendData += "&order_score=10"; sendData += "&total_score=30"; ``` i.e add '&'
I you have data like this ``` "num":"8","name":"","ox_score":"","between_score":"","order_score":"","total_score":"" ``` than you should use ``` $newdata=json_decode($_POST['data']); $name=$newdata->name; $ox_store=$newdara->ox_score; //and more... ```
41,279,579
I am new to Python-Flask and am trying to use MySQLDB to conenct to the database. However, I am unable to determine how to check if the query executed by the cursor is successful or if it failed. In the code below, can someone please advise how I can go about the condition in the if statement? c is a cursor to a database and it is connecting successfully, so I excluded it from the code below. ``` qry = "SELECT count(*) FROM users where username = (%s)" % (username) try: x = c.execute(qry) #Is this correct? Doe execute command return a value? if <<*Check if the query executed successfully*>>: return 'Success' else: return 'Failure' except Exception as e: return 'Failure' ```
2016/12/22
[ "https://Stackoverflow.com/questions/41279579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7115797/" ]
`c.execute(qry)` in your case won't return anything. So, You can't use it for `if` statement. However, You could use `fetchall()` or `fetchone()` to check if there are some results for your query. It would look something like this: ``` qry = "SELECT count(*) FROM users where username = (%s)" % (username) try: c.execute(qry) #Is this correct? Doe execute command return a value? user = c.fetchone() if user: return 'Success' else: return 'Failure' except Exception as e: return 'Failure' ```
You already have the means for detecting the failure in the code you have posted. If something goes wrong with the query, Python will raise an exception, which you can catch. Although it's worth noting that you should never catch a bare Exception, and you should certainly never hide what that exception is; catch the relevant MySQLdb exceptions, eg `MySQLdb.Error`.
7,503,191
I save two versions of user input in the following sequence: 1. Untrusted user enters raw markdown. 2. Raw markdown is stored in one table. 3. A copy of the raw markdown is converted into HTML. 4. HTML is sanitized and persisted, and is displayed upon request. 5. The raw markdown version is only displayed when users edit a entry; it's loaded into a textarea of a form. Is there any risk in loading raw markdown (which could potentially contain unsafe HTML) into a textarea? It would never be displayed outside of a textarea. I can't sanitize the markdown because it would result in inconsistencies between the markdown and HTML versions I'm saving. FYI: I always sanitize SQL, regardless of what I'm saving to the DB.
2011/09/21
[ "https://Stackoverflow.com/questions/7503191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/276959/" ]
It depends how you're "loading" it into the `textarea`. If you're doing it server-side through simple string concatenation, e.g. in php, ``` $output = '<textarea>' + $markdown + '</textarea>'; ``` ...then there is absolutely a risk, because that markdown could very easily close out the `textarea` and embed whatever else it wants. If you're using some sort of a component framework (e.g., ASP.NET), then you should be protected as long as you use a safe API method, such as `MyTextArea.Value = markdown;`. If you're doing it client-side, it also depends on how you're doing this. You would be safe if you used something like jQuery's `.val()` setter, but could still expose yourself to XSS vulnerabilities through other approaches. In short, the general answer is yes, depending on how you're actually creating and populating the `textarea`.
Are you at least doing SQL sanitation? When you INSERT or UPDATE the data, are you using some type of DAO that escapes the SQL or, if using Java, using a Prepared Statement where you set the arguments? You must **always** sanitize things before they go into the DB. Otherwise people could add a stray ``` '); --Malicious procedure here. ``` ..into a request. There are some security risks to leaving unsanitized input in the text box; mainly if the user is infected with something that's injecting Javascript, it will show up for him or her each time. Why even save that? Then you're giving your user a totally inconsistent view from what they enter to what is displayed? They won't match up. It's best to clean the input so when they user views it again he or she *can clearly see* that the offending HTML was removed for security.
7,503,191
I save two versions of user input in the following sequence: 1. Untrusted user enters raw markdown. 2. Raw markdown is stored in one table. 3. A copy of the raw markdown is converted into HTML. 4. HTML is sanitized and persisted, and is displayed upon request. 5. The raw markdown version is only displayed when users edit a entry; it's loaded into a textarea of a form. Is there any risk in loading raw markdown (which could potentially contain unsafe HTML) into a textarea? It would never be displayed outside of a textarea. I can't sanitize the markdown because it would result in inconsistencies between the markdown and HTML versions I'm saving. FYI: I always sanitize SQL, regardless of what I'm saving to the DB.
2011/09/21
[ "https://Stackoverflow.com/questions/7503191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/276959/" ]
It depends how you're "loading" it into the `textarea`. If you're doing it server-side through simple string concatenation, e.g. in php, ``` $output = '<textarea>' + $markdown + '</textarea>'; ``` ...then there is absolutely a risk, because that markdown could very easily close out the `textarea` and embed whatever else it wants. If you're using some sort of a component framework (e.g., ASP.NET), then you should be protected as long as you use a safe API method, such as `MyTextArea.Value = markdown;`. If you're doing it client-side, it also depends on how you're doing this. You would be safe if you used something like jQuery's `.val()` setter, but could still expose yourself to XSS vulnerabilities through other approaches. In short, the general answer is yes, depending on how you're actually creating and populating the `textarea`.
You don't have to sanitize it there, just take care of correctly escaping HTML special characters such as < and >. For instance, Stackoverflow allows you to post HTML code in your posts, it does not remove anything. This is achieved by encoding, not sanitizing.
7,503,191
I save two versions of user input in the following sequence: 1. Untrusted user enters raw markdown. 2. Raw markdown is stored in one table. 3. A copy of the raw markdown is converted into HTML. 4. HTML is sanitized and persisted, and is displayed upon request. 5. The raw markdown version is only displayed when users edit a entry; it's loaded into a textarea of a form. Is there any risk in loading raw markdown (which could potentially contain unsafe HTML) into a textarea? It would never be displayed outside of a textarea. I can't sanitize the markdown because it would result in inconsistencies between the markdown and HTML versions I'm saving. FYI: I always sanitize SQL, regardless of what I'm saving to the DB.
2011/09/21
[ "https://Stackoverflow.com/questions/7503191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/276959/" ]
You don't have to sanitize it there, just take care of correctly escaping HTML special characters such as < and >. For instance, Stackoverflow allows you to post HTML code in your posts, it does not remove anything. This is achieved by encoding, not sanitizing.
Are you at least doing SQL sanitation? When you INSERT or UPDATE the data, are you using some type of DAO that escapes the SQL or, if using Java, using a Prepared Statement where you set the arguments? You must **always** sanitize things before they go into the DB. Otherwise people could add a stray ``` '); --Malicious procedure here. ``` ..into a request. There are some security risks to leaving unsanitized input in the text box; mainly if the user is infected with something that's injecting Javascript, it will show up for him or her each time. Why even save that? Then you're giving your user a totally inconsistent view from what they enter to what is displayed? They won't match up. It's best to clean the input so when they user views it again he or she *can clearly see* that the offending HTML was removed for security.
61,912,659
I have a website deployed using docker image inside google compute instance. I'm unable to update the google cloud instance with a new image. Updating the compute instance with new docker image and running the container changes nothing. Here are the steps I take to update the google compute instance: ``` docker build -t vue_app -f deploy/web/Dockerfile . --tag gcr.io/namesapi-1581010760883/vue-app:v1 docker push gcr.io/namesapi-1581010760883/vue-app:v1 gcloud compute instances update-container --container-image=gcr.io/namesapi-1581010760883/vue-app:v1 vue-app-vm ``` So in the first line I build the image containing the website and http-server. I ran it locally and can confirm the image is working and contains all the changes I expect. Next line is pushing the image to google cloud and the final third line is supposed to update an existing google compute instance with the new image. After running this none of the changes are reflected in the instance. I visit the website hosted on the instance and see that nothing has changed. I've done these same steps many times and it all worked fine up until recently. What am I missing?
2020/05/20
[ "https://Stackoverflow.com/questions/61912659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4233305/" ]
Solved the issue. For future reference running the following ``` gcloud compute instances update-container --container-image=gcr.io/namesapi-1581010760883/vue-app:v1 vue-app-vm ``` does not replace the existing image on the instance, instead it creates a new image. So after some time the instance accumulate a number of images: ``` REPOSITORY TAG IMAGE ID CREATED SIZE gcr.io/namesapi-1581010760883/vue-app v1 d21bd8939323 9 days ago 394MB gcr.io/namesapi-1581010760883/vue-app <none> c136b1c9e0d4 13 days ago 387MB gcr.io/namesapi-1581010760883/vue-app <none> b1b11f2c9678 4 weeks ago 385MB gcr.io/namesapi-1581010760883/vue-app <none> a5ef94db2438 4 weeks ago 385MB gcr.io/namesapi-1581010760883/vue-app <none> 23b52253c060 6 weeks ago 385MB gcr.io/namesapi-1581010760883/vue-app <none> cb03925836a7 2 months ago 384MB gcr.io/gce-containers/konlet v.0.9-latest da64965a2b28 19 months ago 73.4MB gcr.io/stackdriver-agents/stackdriver-logging-agent 0.2-1.5.33-1-1 fcfafd404600 22 months ago 548MB ``` I think what happened in my case was the compute instance ran out of disk space and new image was not pushed when running the above command. Google cloud API did not raise a warning or anything, which is why this was tricky to understand. Solved this by logging into the instance manually and removing old images, then repeating the steps in the original question.
Thanks @RaidasGrisk ! This problem is insane You can create your instance with a startup-script which will clean your unused docker images : ```sh gcloud compute instances create-with-container my-instance \ --machine-type f1-micro \ --metadata startup-script='#! /bin/bash # Clear old Docker images docker image prune -af' \ --zone us-central1-a \ --container-image gcr.io/my-project/my-image ``` Also, you can remove unused Docker images from your own machine with gcloud client : ```sh # Only the first time gcloud compute config-ssh gcloud compute ssh --verbosity=debug my-instance --command "docker image prune -af" ```
72,467,285
I have been updating a KQL query for use in reviewing NSG Flow Logs to separate the columns for Public/External IP addresses. However the data within each cell of the column contains additional information that needs to be parsed out so my excel addin can run NSLOOKUP against each cell and looking for additional insights. Later I would like to use the parse operator (<https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/parseoperator>) to separate this information to determine what that external IP address belongs to through nslookup, resolve-dnsname, whois , or other means. However currently I am attempting to parse out the column, but is not comma delimited and instead uses a single space and multiple pipes. Below is my query and I would like to add a parse to this to either have a comma delimited string in a single cell *[ for PublicIP (combination of Source and Destination), PublicSourceIP, and PublicDestIP. ]* or break it out into multiple rows. How would parse be best used to separate this information, or is there a better operator to use to carry this out? ``` For Example the content could look like this "20.xx.xx.xx|1|0|0|0|0|0 78.xxx.xxx.xxx|1|0|0|0|0|0" AzureNetworkAnalytics_CL | where SubType_s == 'FlowLog' and (FASchemaVersion_s == '1'or FASchemaVersion_s == '2') | extend NSG = NSGList_s, Rule = NSGRule_s,Protocol=L4Protocol_s, Hits = (AllowedInFlows_d + AllowedOutFlows_d + DeniedInFlows_d + DeniedOutFlows_d) | project-away NSGList_s, NSGRule_s | project TimeGenerated, NSG, Rule, SourceIP = SrcIP_s, DestinationIP = DestIP_s, DestinationPort = DestPort_d, FlowStatus = FlowStatus_s, FlowDirection = FlowDirection_s, Protocol=L4Protocol_s, PublicIP=PublicIPs_s,PublicSourceIP = SrcPublicIPs_s,PublicDestIP=DestPublicIPs_s // ## IP Address Filtering ## | where isnotempty(PublicIP) **| parse kind = regex PublicIP with * "|1|0|0|0|0|0" ipnfo ' ' * | project ipnfo** // ## port filtering | where DestinationPort == '443' ```
2022/06/01
[ "https://Stackoverflow.com/questions/72467285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19251264/" ]
Based on [extract\_all()](https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/extractallfunction) followed by [strcat\_array()](https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/strcat-arrayfunction) or [mv-expand](https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/mvexpandoperator) ``` let AzureNetworkAnalytics_CL = datatable (RecordId:int, PublicIPs_s:string) [ 1 ,"51.105.236.244|2|0|0|0|0|0 51.124.32.246|12|0|0|0|0|0 51.124.57.242|1|0|0|0|0|0" ,2 ,"20.44.17.10|6|0|0|0|0|0 20.150.38.228|1|0|0|0|0|0 20.150.70.36|2|0|0|0|0|0 20.190.151.9|2|0|0|0|0|0 20.190.151.134|1|0|0|0|0|0 20.190.154.137|1|0|0|0|0|0 65.55.44.109|2|0|0|0|0|0" ,3 ,"20.150.70.36|1|0|0|0|0|0 52.183.220.149|1|0|0|0|0|0 52.239.152.234|2|0|0|0|0|0 52.239.169.68|1|0|0|0|0|0" ]; // Option 1 AzureNetworkAnalytics_CL | project RecordId, PublicIPs = strcat_array(extract_all("(?:^| )([^|]+)", PublicIPs_s),','); // Option 2 AzureNetworkAnalytics_CL | mv-expand with_itemindex=i PublicIP = extract_all("(?:^| )([^|]+)", PublicIPs_s) to typeof(string) | project RecordId, i = i+1, PublicIP ``` [Fiddle](https://dataexplorer.azure.com/clusters/help/databases/Samples?query=H4sIAAAAAAAAA42SXW%20CMBSG70n4Dw03QmSVtny6mMXsymTZzG6NEoRu64ZASp268ONXdCg4XUYvSHk4Lw89J6UCjL/WnD5Sscn5xziL0p1gcRneP4ARSCIh1zKlQH%20mcc6TSTJkmTDBdL1MWTyZlmE5LAVn2auhKjNVAfWFgKk5CCLLgZi4ENt2hSurWaBG2IYES%20JW6AJyPIlwhU5EO0SbWEZjC9o2RJ78QOW2iuVz5FiQ%20BBjv13cEE9Ct6NSg6CGCAbXACL2r7A9kg7E6yDXgY6zl7M6cY09OdifXNrFDobIJ9JdvmAH5wiTQNbV97PD/EFuAF3/7MTmt6oyGICnQrA8A0hVrnVaVSpQ8PydxgI0fW71WA6C7HEciTDiPNrpdCt4FMtdmuqafjdcVMDQZ4tq3je0zmgYZs/sGR0L/LfF6vOGbosoS8CGibeQCbpiWUK3I3bMlTb/FwAiB2JX0PxFP47ppX9lMpX10an4Gw5hqc8ZAwAA) **Option 1** | RecordId | PublicIPs | | --- | --- | | 1 | 51.105.236.244,51.124.32.246,51.124.57.242 | | 2 | 20.44.17.10,20.150.38.228,20.150.70.36,20.190.151.9,20.190.151.134,20.190.154.137,65.55.44.109 | | 3 | 20.150.70.36,52.183.220.149,52.239.152.234,52.239.169.68 | **Option 2** | RecordId | i | PublicIP | | --- | --- | --- | | 1 | 1 | 51.105.236.244 | | 1 | 2 | 51.124.32.246 | | 1 | 3 | 51.124.57.242 | | 2 | 1 | 20.44.17.10 | | 2 | 2 | 20.150.38.228 | | 2 | 3 | 20.150.70.36 | | 2 | 4 | 20.190.151.9 | | 2 | 5 | 20.190.151.134 | | 2 | 6 | 20.190.154.137 | | 2 | 7 | 65.55.44.109 | | 3 | 1 | 20.150.70.36 | | 3 | 2 | 52.183.220.149 | | 3 | 3 | 52.239.152.234 | | 3 | 4 | 52.239.169.68 |
David answers your question. I would just like to add that I worked on the raw [NSG Flow Logs](https://learn.microsoft.com/en-us/azure/network-watcher/network-watcher-nsg-flow-logging-overview) and parsed them using kql in this way: The raw JSON: ``` {"records":[{"time":"2022-05-02T04:00:48.7788837Z","systemId":"x","macAddress":"x","category":"NetworkSecurityGroupFlowEvent","resourceId":"/SUBSCRIPTIONS/x/RESOURCEGROUPS/x/PROVIDERS/MICROSOFT.NETWORK/NETWORKSECURITYGROUPS/x","operationName":"NetworkSecurityGroupFlowEvents","properties":{"Version":2,"flows":[{"rule":"DefaultRule_DenyAllInBound","flows":[{"mac":"x","flowTuples":["1651463988,0.0.0.0,192.168.1.6,49944,8008,T,I,D,B,,,,"]}]}]}}]} ``` kql parsing: ``` | mv-expand records | evaluate bag_unpack(records) | extend flows = properties.flows | mv-expand flows | evaluate bag_unpack(flows) | mv-expand flows | extend flowz = flows.flowTuples | mv-expand flowz | extend result=split(tostring(flowz), ",") | extend source_ip=tostring(result[1]) | extend destination_ip=tostring(result[2]) | extend source_port=tostring(result[3]) | extend destination_port=tostring(result[4]) | extend protocol=tostring(result[5]) | extend traffic_flow=tostring(result[6]) | extend traffic_decision=tostring(result[7]) | extend flow_state=tostring(result[8]) | extend packets_src_to_dst=tostring(result[9]) | extend bytes_src_to_dst=tostring(result[10]) | extend packets_dst_to_src=tostring(result[11]) | extend bytes_dst_to_src=tostring(result[12]) ```
15,593,870
I am trying to return a sum from an array and for some reason it's not displaying. I tried various things but for some reason it's not returning the sum of the array. When I call `tableSum(sum)` from the console, it returns it, but it's not happening in the JavaScript. Here is my code: ``` var tableSum = function () { 'use strict'; var sum = 0, i; for (i = 0; i < numberArray.length; i += 1) { sum += numberArray[i]; } return sum; document.getElementById('sum').innerHTML = sum; }; ``` HTML: ``` <table border="1"> <tr> <td style = "text-align:right;">Sum:</td> <td style="width:100px" id = "sum">&#160;</td> </tr> ```
2013/03/24
[ "https://Stackoverflow.com/questions/15593870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2175788/" ]
``` >>> text = 'a man a plan a canal panama' >>> x = ''.join(text.split()) >>> x == x[::-1] True ```
Outline ======= A phrase is a palindrome if the i'th character is the same as the len-i'th character. Since the series is a mirror image, you haveto go only as far as the middle. To get the effect you are looking for,you can normalize on whitespace, punctuation, and string case before calculating whether a string is a palindrome or not.. Code ==== ``` from string import punctuation def is_palindrome(s):     return all(s[i] == s[-(i + 1)] for i in range(len(s)//2)) def normalized_palindrome(s):     return is_palindrome("".join(c for c in s.replace(" ","").lower() if c not in punctuation)) ``` You can also use `zip` and `reversed` to iterate pairwise over letters: ``` def is_palindrome(s): return all(a == b for a, b in zip(s, reversed(s))) ``` Of course, that does not stop in the middle. Test ==== ``` >>> tests = [ ... "able was I ere I saw Elba", ... "a man, a plan, a canal: Panama!", ... "Was it Eliot's toilet I saw?", ... ] >>> >>> for test in tests: ... print normalized_palindrome(test) ... True True True ``` Your code ========= As for your original, it's correct by me: ``` >>> s = "able was I ere I saw Elba".lower() >>> def ispalindrome(word): ... if len(word) < 2: return True ... if word[0] != word[-1]: return False ... return ispalindrome(word[1:-1]) ... >>> ispalindrome(s) True >>> s = "a man a plan a canal panama" >>> ispalindrome(s) False >>> ispalindrome(s.replace(" ","")) True ```
15,593,870
I am trying to return a sum from an array and for some reason it's not displaying. I tried various things but for some reason it's not returning the sum of the array. When I call `tableSum(sum)` from the console, it returns it, but it's not happening in the JavaScript. Here is my code: ``` var tableSum = function () { 'use strict'; var sum = 0, i; for (i = 0; i < numberArray.length; i += 1) { sum += numberArray[i]; } return sum; document.getElementById('sum').innerHTML = sum; }; ``` HTML: ``` <table border="1"> <tr> <td style = "text-align:right;">Sum:</td> <td style="width:100px" id = "sum">&#160;</td> </tr> ```
2013/03/24
[ "https://Stackoverflow.com/questions/15593870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2175788/" ]
``` >>> text = 'a man a plan a canal panama' >>> x = ''.join(text.split()) >>> x == x[::-1] True ```
You can store the string that is free of special characters and spaces and then check if it is a palindrome or not. ``` def isPalindrome(s: str) -> bool: mystring = s.lower() mystring2 = "" for i in mystring: if i.isalnum(): mystring2 += i return (mystring2 == mystring2[::-1]) ```
15,593,870
I am trying to return a sum from an array and for some reason it's not displaying. I tried various things but for some reason it's not returning the sum of the array. When I call `tableSum(sum)` from the console, it returns it, but it's not happening in the JavaScript. Here is my code: ``` var tableSum = function () { 'use strict'; var sum = 0, i; for (i = 0; i < numberArray.length; i += 1) { sum += numberArray[i]; } return sum; document.getElementById('sum').innerHTML = sum; }; ``` HTML: ``` <table border="1"> <tr> <td style = "text-align:right;">Sum:</td> <td style="width:100px" id = "sum">&#160;</td> </tr> ```
2013/03/24
[ "https://Stackoverflow.com/questions/15593870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2175788/" ]
Outline ======= A phrase is a palindrome if the i'th character is the same as the len-i'th character. Since the series is a mirror image, you haveto go only as far as the middle. To get the effect you are looking for,you can normalize on whitespace, punctuation, and string case before calculating whether a string is a palindrome or not.. Code ==== ``` from string import punctuation def is_palindrome(s):     return all(s[i] == s[-(i + 1)] for i in range(len(s)//2)) def normalized_palindrome(s):     return is_palindrome("".join(c for c in s.replace(" ","").lower() if c not in punctuation)) ``` You can also use `zip` and `reversed` to iterate pairwise over letters: ``` def is_palindrome(s): return all(a == b for a, b in zip(s, reversed(s))) ``` Of course, that does not stop in the middle. Test ==== ``` >>> tests = [ ... "able was I ere I saw Elba", ... "a man, a plan, a canal: Panama!", ... "Was it Eliot's toilet I saw?", ... ] >>> >>> for test in tests: ... print normalized_palindrome(test) ... True True True ``` Your code ========= As for your original, it's correct by me: ``` >>> s = "able was I ere I saw Elba".lower() >>> def ispalindrome(word): ... if len(word) < 2: return True ... if word[0] != word[-1]: return False ... return ispalindrome(word[1:-1]) ... >>> ispalindrome(s) True >>> s = "a man a plan a canal panama" >>> ispalindrome(s) False >>> ispalindrome(s.replace(" ","")) True ```
You can store the string that is free of special characters and spaces and then check if it is a palindrome or not. ``` def isPalindrome(s: str) -> bool: mystring = s.lower() mystring2 = "" for i in mystring: if i.isalnum(): mystring2 += i return (mystring2 == mystring2[::-1]) ```
17,502,353
I don't know how to run $.ajax properly. I usually make all xmlHTTP objects manually using javascript and then use jQuery wherever required. So please help me use this function properly in jQuery. HTML ---- ``` <form action="login.php" method="post" onSubmit="return login()" > <input type="text" name="eMailTxt" id="eMailTxt" placeholder="Email Address" /> <input type="password" name="passWordTxt" id="passWordTxt" placeholder="password" /> <br /> <p><!--wanna show password does not match here--></p> <input type="submit" value="Login" id="submitBtn" class="Btn" /> </form> ``` JQuery Ajax ----------- ``` function login() { $email = $("#eMailTxt").val(); $pass = $("#passWordTxt").val(); $.ajax({ url:'loginCheck.php', type:'POST', data:{q:$email,s:$pass}, success:function(response){ $("#loginForm p").innerHTML = xmlhttp.responseText; return false; //is this the correct way to do it? } }); return true; //not really sure about this } ``` PHP MySQL --------- ``` $q=$_POST["q"]; $s=$_POST["s"]; $con=mysqli_connect("localhost","root","","SocialNetwork"); $check="SELECT PassWord FROM people WHERE EMAIL = '".$q."'"; $data=mysqli_query($con,$check); $result=mysqli_fetch_array($data); if ($s != $result) { echo "Password does not match"; } ```
2013/07/06
[ "https://Stackoverflow.com/questions/17502353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2544974/" ]
jQuery object doesn't have a property `innerHTML` which is used on DOM element. Use method `html()` instead: ``` $("#loginForm p").html(response); ``` Or you could refer to DOM element like that: ``` $("#loginForm p")[0].innerHTML = response; // equivalent to .get(0) ``` Be aware as ajax is async by default, your login function here will always return true. BTW, response here corresponds to the returned value from server, not the jqXHR object (xhr object wrapped inside a jquery object). **UPDATE** ``` function login(form) { $email = $("#eMailTxt").val(); $pass = $("#passWordTxt").val(); $.ajax({ url:'loginCheck.php', type:'POST', data:{q:$email,s:$pass}, success:function(response){ if(response === "Password does not match") { $("#loginForm p").html(response); return false; } //if password match, submit form form.submit(); } }); //we always return false here to avoid form submiting before ajax request is done return false; } ``` In HTML: ``` <form action="login.php" method="post" onSubmit="return login(this)" > ```
Ajax success call back contains only data (you are confused with the compete function of ajax or pure javascript xmlhttp request) therefore ``` success:function(response){ $("#loginForm p").html(response); } ``` Also seeing your query you are susceptible to sql injection
17,502,353
I don't know how to run $.ajax properly. I usually make all xmlHTTP objects manually using javascript and then use jQuery wherever required. So please help me use this function properly in jQuery. HTML ---- ``` <form action="login.php" method="post" onSubmit="return login()" > <input type="text" name="eMailTxt" id="eMailTxt" placeholder="Email Address" /> <input type="password" name="passWordTxt" id="passWordTxt" placeholder="password" /> <br /> <p><!--wanna show password does not match here--></p> <input type="submit" value="Login" id="submitBtn" class="Btn" /> </form> ``` JQuery Ajax ----------- ``` function login() { $email = $("#eMailTxt").val(); $pass = $("#passWordTxt").val(); $.ajax({ url:'loginCheck.php', type:'POST', data:{q:$email,s:$pass}, success:function(response){ $("#loginForm p").innerHTML = xmlhttp.responseText; return false; //is this the correct way to do it? } }); return true; //not really sure about this } ``` PHP MySQL --------- ``` $q=$_POST["q"]; $s=$_POST["s"]; $con=mysqli_connect("localhost","root","","SocialNetwork"); $check="SELECT PassWord FROM people WHERE EMAIL = '".$q."'"; $data=mysqli_query($con,$check); $result=mysqli_fetch_array($data); if ($s != $result) { echo "Password does not match"; } ```
2013/07/06
[ "https://Stackoverflow.com/questions/17502353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2544974/" ]
**HTML** ``` <form action="login.php" method="post" class="js-my-form"> <input type="text" name="record[email]" id="eMailTxt" placeholder="Email Address" /> <input type="password" name="record[password]" id="passWordTxt" placeholder="password" /> <br /> <p><!--wanna show password does not match here--></p> <input type="submit" value="Login" id="submitBtn" class="Btn" /> </form> ``` **jQuery** ``` $(document).ready(function () { $('.js-my-form').submit(function () { var data = $(this).serialize(); var action = $(this).attr('action'); var methodType = $(this).attr('method'); $.ajax({ url: action, type: methodType, data: data, beforeSend: function () { //Maybe Some Ajax Loader }, success: function (response) { // success }, error: function (errorResponse) {} }); return false; //Send form async }); }); ``` **PHP** ``` if (isset($_POST['record']) { //Your PHP Code } else { header("HTTP/1.0 404 Not Found"); // Trow Error for JS echo 'invalid data'; } ```
Ajax success call back contains only data (you are confused with the compete function of ajax or pure javascript xmlhttp request) therefore ``` success:function(response){ $("#loginForm p").html(response); } ``` Also seeing your query you are susceptible to sql injection
56,980,041
I have an application that is written using `C#` on the top of ASP.NET Core 2.2 Framework. The application uses Entity Framework Core as an ORM to interact with the database. Entity Framework has been good to me in many cases. It is extremely helpful in simple CRUD, or even when add/update/delete a small amount of data. However, when I need to read somewhat large dataset or data generated by a complex query it is too slow. In many cases I find Entity Framework over complicate queries which cause my app to slow down. I guess this the disadvantage of using ORM. But an ORM is must have in my case! With that in mind, I am looking for a solution where I can keep using ORM in most cases but find a way to pull data using custom query and directly map the same query to the entity models. I can directly use ADO.NET to execute raw queries that I write which gives me high performance. But, I need a way to auto map the requests to entity models. For the sake of explaining what I am looking for, assume the following query Entity Frameworks over complicates and I found a better query to get the same data. Here is my better raw query ``` SELECT u.username, u.firstname, u.lastname, p.* FROM users AS u INNER JOIN ( SELECT id, title, description, userid FROM posts WHERE deletedon IS NULL AND publishedon BETWEEN '2019-07-01' AND '2019-07-10' ) AS p WHERE u.deletedon IS NULL ``` I have the following entity model ``` public class User { public int id { get ; set; } public string username { get ; set; } public string firstname { get ; set; } public string lastname { get ; set; } public DateTime deletedon { get ; set; } public virtual ICollection<Post> posts { get ; set; } } public class Post { public int id { get ; set; } public string title{ get ; set; } public string description { get ; set; } public int userId { get ; set; } public DateTime deletedon { get ; set; } public DateTime publishedon { get ; set; } public virtual User user { get ; set; } } ``` Is there a tool that could take either a query or a data-table object and map it to my `User` object?
2019/07/11
[ "https://Stackoverflow.com/questions/56980041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4967389/" ]
The short answer is - no (currently). It's listed in [Raw SQL Queries - Limitations](https://learn.microsoft.com/en-us/ef/core/querying/raw-sql#limitations): > > * The SQL query cannot contain related data. > > > I believe this is because EF Core in general does not use single SQL query for retrieving correlated collection data, but one query for the main data and one query for each related collection, i.e. for the sample model it will use 2 SQL queries. You can still use raw SQL queries to return sets of some flattened [query type](https://learn.microsoft.com/en-us/ef/core/modeling/query-types), but then you have to populate entity models manually (or with help of 3rd party libraries like AutoMapper).
You can save the query as a stored procedure and bring it to the model.edmx.
10,623,460
In my MVC application, I have a html.dropdownlist in my view. On selection changed - I want the value to be passed on to a method (that returns something like a list or a JsonResult) in the controller. Q1: How do I do this? ``` <%=Html.DropDownList("title", Model.Titleitems, "" )%> ``` Q2: Is this a good practice (having controller/method name in the view directly) or should I write a JavaScript function and call the appropriate controller/method from inside that JavaScript function? In that case, how can I write a Onchange or OnSelectionChanged event for the above html.dropdownlist control? EDIT: par1 is the dropdownlist selected value I want to pass to this controller/method.. ``` public ActionResult GetMethod(string Par1) { //My code here return Json(varValue, JsonRequestBehavior.AllowGet); } ``` Now I have the dropdownlist on change taking me to a JavaScript function (as per marteljn suggestion) and in the JavaScript function, I have .ajax call specifying URL and type etc. that takes me to the controller/method code; but still not able to figure out how to pass the selected value to the controller?
2012/05/16
[ "https://Stackoverflow.com/questions/10623460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757603/" ]
Q2 is the answer to Q1. There are no events when using MVC like there are in web forms, so you will write some JavaScript to make a request back to the server. There are (at least) two ways to go about it: 1. Inline Event Handler (not recommended) `<%=Html.DropDownList("title", Model.Titleitems, new{@onchange = "YourJsFuncHere()"} )%>` 2. The JQuery way, ``` $("#title").bind("change",function(){ //Your Code //Use .on instead of bind if you are using JQuery 1.7.x or higher //http://api.jquery.com/on/ }); ``` **Edit - The AJAX Code** ``` $.ajax({ "url": "/Controller/Action/" + $("#title").val(), "type": "get", "dataType" : "json", "success": function(data){ //Your code here //data should be your json result } }); ``` Change `GetMethod(string Par1)` to `GetMethod(string id)` or change your default route to reflect the `Par1` parameter. Also, if its not hitting your break point its possible that 1) the AJAX request is not being initied (use firebug to see if it is) 2) Your routes are not configured properly (Look in Global.asax.cs, if you haven't moved the routing somewhere else.
``` $(function(){ $("#title").change(function(){ var selectedVal=$(this).val(); $.getJSON("UserController/YourAction",{ id: selectedVal} , function(result ){ //Now you can access the jSon data here in the result variable }); }); }); ``` Assuming you have an Action method called `YourAction` in your `UserController` which returns JSON ``` public ActionResult YourAction(int id) { //TO DO : get data from wherever you want. var result=new { Success="True", Message="Some Info"}; return Json(result, JsonRequestBehavior.AllowGet); } ```
33,530,928
I recently started learning algorithms based on the book [Data Structures and Algorithms with JavaScript from O'Reilly](http://shop.oreilly.com/product/0636920029557.do). I stopped on Chapter 12 - Sorting Algorithms. I can not understand how Insertion Sort works. Here is the code I am working with: [pasteBin - Insertion Sort](http://pastebin.com/fGV7RqbR) Below is the part that is confusing to me: ``` function insertionSort() { var temp, inner; for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { temp = this.dataStore[outer]; inner = outer; while (inner > 0 && (this.dataStore[inner-1] >= temp)) { this.dataStore[inner] = this.dataStore[inner-1]; --inner; } this.dataStore[inner] = temp; } console.log(this.toString()); } ``` Could anyone help and comment on this code?
2015/11/04
[ "https://Stackoverflow.com/questions/33530928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526354/" ]
It's a sorting algorithm which starts at the beginning of the array and passes through until the end. For the item at each index, it goes back through the items at earlier indices and checks to see if it should be placed before them. If so, it swaps indices with the larger value until it settles into the index it should have. Here's the code with some commentary, hopefully it is helpful to you. ``` function insertionSort() { /* Set up local vars */ var temp, inner; /* Start at index 1, execute outer loop once per index from 1 to the last index */ for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { /* Store the value at the current index */ temp = this.dataStore[outer]; /* Set up temporary index to decrement until we find where this value should be */ inner = outer; /* As long as 'inner' is not the first index, and there is an item in our array whose index is less than inner, but whose value is greater than our temp value... */ while (inner > 0 && (this.dataStore[inner-1] >= temp)) { /* Swap the value at inner with the larger value */ this.dataStore[inner] = this.dataStore[inner-1]; /* Decrement inner to keep moving down the array */ --inner; } /* Finish sorting this value */ this.dataStore[inner] = temp; } console.log(this.toString()); } ``` --- Here is a [jsfiddle](http://jsfiddle.net/tpLt1m0y/1/) with lots of console printouts so you can step through it and see what happens at each step.
Starting from the inner loop check if the current element is greater than the previous if yes, exit the loop since everything is sorted for the iteration, if not swap elements because the current needs to be moved to the left because it's smaller than the previous. The inner loop makes sure to swap elements until you encounter a sorted element which results with the break exiting the loop. After the swap occurs decrease the outer index (i) since you are going downwards to check if the upcoming element is lesser than the previous, you cannot keep the outer index (i) static. At last, the memIndex variable serves as a reset index because at the end of your inner loop you want to move to the next index. Index (i) should always be placed at the last element of the sorted array so that the inner loop can start the comparison again. ```js function insertionSort(arr) { let memIndex = 0 for (let i = 0; i < arr.length; i++) { memIndex = i; for (let j = i + 1; j >= 0; --j) { if (arr[j] >= arr[i]) { break; } if (arr[j] < arr[i]) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i = i - 1; } } i = memIndex; } return arr; } const arr = [5, 1, 6, 2, 4, 9, 9, 3, 1, 1, 1]; console.log('Unsorted array', arr); console.log('Sorted array:', insertionSort(arr)); ```
33,530,928
I recently started learning algorithms based on the book [Data Structures and Algorithms with JavaScript from O'Reilly](http://shop.oreilly.com/product/0636920029557.do). I stopped on Chapter 12 - Sorting Algorithms. I can not understand how Insertion Sort works. Here is the code I am working with: [pasteBin - Insertion Sort](http://pastebin.com/fGV7RqbR) Below is the part that is confusing to me: ``` function insertionSort() { var temp, inner; for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { temp = this.dataStore[outer]; inner = outer; while (inner > 0 && (this.dataStore[inner-1] >= temp)) { this.dataStore[inner] = this.dataStore[inner-1]; --inner; } this.dataStore[inner] = temp; } console.log(this.toString()); } ``` Could anyone help and comment on this code?
2015/11/04
[ "https://Stackoverflow.com/questions/33530928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526354/" ]
It's a sorting algorithm which starts at the beginning of the array and passes through until the end. For the item at each index, it goes back through the items at earlier indices and checks to see if it should be placed before them. If so, it swaps indices with the larger value until it settles into the index it should have. Here's the code with some commentary, hopefully it is helpful to you. ``` function insertionSort() { /* Set up local vars */ var temp, inner; /* Start at index 1, execute outer loop once per index from 1 to the last index */ for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { /* Store the value at the current index */ temp = this.dataStore[outer]; /* Set up temporary index to decrement until we find where this value should be */ inner = outer; /* As long as 'inner' is not the first index, and there is an item in our array whose index is less than inner, but whose value is greater than our temp value... */ while (inner > 0 && (this.dataStore[inner-1] >= temp)) { /* Swap the value at inner with the larger value */ this.dataStore[inner] = this.dataStore[inner-1]; /* Decrement inner to keep moving down the array */ --inner; } /* Finish sorting this value */ this.dataStore[inner] = temp; } console.log(this.toString()); } ``` --- Here is a [jsfiddle](http://jsfiddle.net/tpLt1m0y/1/) with lots of console printouts so you can step through it and see what happens at each step.
```js const insertionSort = array => { const arr = Array.from(array); // avoid side effects for (let i = 1; i < arr.length; i++) { for (let j = i; j > 0 && arr[j] < arr[j - 1]; j--) { [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]]; } } return arr; }; ```
33,530,928
I recently started learning algorithms based on the book [Data Structures and Algorithms with JavaScript from O'Reilly](http://shop.oreilly.com/product/0636920029557.do). I stopped on Chapter 12 - Sorting Algorithms. I can not understand how Insertion Sort works. Here is the code I am working with: [pasteBin - Insertion Sort](http://pastebin.com/fGV7RqbR) Below is the part that is confusing to me: ``` function insertionSort() { var temp, inner; for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { temp = this.dataStore[outer]; inner = outer; while (inner > 0 && (this.dataStore[inner-1] >= temp)) { this.dataStore[inner] = this.dataStore[inner-1]; --inner; } this.dataStore[inner] = temp; } console.log(this.toString()); } ``` Could anyone help and comment on this code?
2015/11/04
[ "https://Stackoverflow.com/questions/33530928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526354/" ]
It's a sorting algorithm which starts at the beginning of the array and passes through until the end. For the item at each index, it goes back through the items at earlier indices and checks to see if it should be placed before them. If so, it swaps indices with the larger value until it settles into the index it should have. Here's the code with some commentary, hopefully it is helpful to you. ``` function insertionSort() { /* Set up local vars */ var temp, inner; /* Start at index 1, execute outer loop once per index from 1 to the last index */ for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { /* Store the value at the current index */ temp = this.dataStore[outer]; /* Set up temporary index to decrement until we find where this value should be */ inner = outer; /* As long as 'inner' is not the first index, and there is an item in our array whose index is less than inner, but whose value is greater than our temp value... */ while (inner > 0 && (this.dataStore[inner-1] >= temp)) { /* Swap the value at inner with the larger value */ this.dataStore[inner] = this.dataStore[inner-1]; /* Decrement inner to keep moving down the array */ --inner; } /* Finish sorting this value */ this.dataStore[inner] = temp; } console.log(this.toString()); } ``` --- Here is a [jsfiddle](http://jsfiddle.net/tpLt1m0y/1/) with lots of console printouts so you can step through it and see what happens at each step.
**insertion sort** means first step we are going to take one value from unsorted sublets and second step we are going to find out appropriate place for that in sorted sublet after find out right place we will insert that value in sorted sublet. you can get deep understanding from this video links:- [Insertion Sort Algorithm | Data Structure](https://youtu.be/yCxV0kBpA6M) ```js function insertionSort(arr) { for (let i = 1; i < arr.length; i++) { // first step let currentValue = arr[i] let j for (j = i - 1; j >= 0 && arr[j] > currentValue; j--) { // second step arr[j + 1] = arr[j] } arr[j + 1] = currentValue } return arr } console.log(insertionSort([5,2,6,3,1,4])) ```
33,530,928
I recently started learning algorithms based on the book [Data Structures and Algorithms with JavaScript from O'Reilly](http://shop.oreilly.com/product/0636920029557.do). I stopped on Chapter 12 - Sorting Algorithms. I can not understand how Insertion Sort works. Here is the code I am working with: [pasteBin - Insertion Sort](http://pastebin.com/fGV7RqbR) Below is the part that is confusing to me: ``` function insertionSort() { var temp, inner; for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { temp = this.dataStore[outer]; inner = outer; while (inner > 0 && (this.dataStore[inner-1] >= temp)) { this.dataStore[inner] = this.dataStore[inner-1]; --inner; } this.dataStore[inner] = temp; } console.log(this.toString()); } ``` Could anyone help and comment on this code?
2015/11/04
[ "https://Stackoverflow.com/questions/33530928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526354/" ]
The main concept behind insertion sort is to sort elements by comparison. The comparison occurs in your case for a `dataStore` array, containing what we assume to be comparable elements such as numbers. In order to compare element by element, this insertion sort algorithm starts at the beginning of the `dataStore` array and will continue to run until the end of the array has been reached. This is accomplished by a `for` loop: ``` for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) ``` As the algorithm goes through each element in order, it will: 1. Store the current element we are visiting in the array in a variable called `temp`. 2. Keep track of the location we are in the array via the `inner` and `outer` variables, where: * `outer` is our counter. * `inner` is a flag to determine whether or not we are visiting the first element in the array. Why is this important? Because there is no point in doing a comparison on the first element, on the first try. 3. It will compare the current element `temp` with each element that came before it in the `dataStore` array. This is accomplished by an inner `while` loop as seen here: `while (inner > 0 && (this.dataStore[inner-1] >= temp))` This tells you that, as long as all previous visited elements in the `dataStore` array are greater than or equal to `temp`, our temporary variable used to store the current element; we want to swap these values. Swapping them will accomplish the following: * Assume all elements before `this.dataStore[inner]` are greater than 10, and the currently visited element `this.dataStore[inner]` equals 5. This logically means that 5 needs to be at the beginning of the array. In such case we would continue to pass 5 all the way down to `this.datastore[0]` thanks to the while loop. Thus making 5 the first element in the array. At the end of this swapping, the value in `temp` is placed accordingly to the current position we are in the array, just to remind you which position this is, it's stored the variable `outer`. TLDR: I also like Justin Powell's answer as it sticks with the code, but I thought a walk through would be more useful depending on your level of understanding. I hope it helps!
Starting from the inner loop check if the current element is greater than the previous if yes, exit the loop since everything is sorted for the iteration, if not swap elements because the current needs to be moved to the left because it's smaller than the previous. The inner loop makes sure to swap elements until you encounter a sorted element which results with the break exiting the loop. After the swap occurs decrease the outer index (i) since you are going downwards to check if the upcoming element is lesser than the previous, you cannot keep the outer index (i) static. At last, the memIndex variable serves as a reset index because at the end of your inner loop you want to move to the next index. Index (i) should always be placed at the last element of the sorted array so that the inner loop can start the comparison again. ```js function insertionSort(arr) { let memIndex = 0 for (let i = 0; i < arr.length; i++) { memIndex = i; for (let j = i + 1; j >= 0; --j) { if (arr[j] >= arr[i]) { break; } if (arr[j] < arr[i]) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i = i - 1; } } i = memIndex; } return arr; } const arr = [5, 1, 6, 2, 4, 9, 9, 3, 1, 1, 1]; console.log('Unsorted array', arr); console.log('Sorted array:', insertionSort(arr)); ```
33,530,928
I recently started learning algorithms based on the book [Data Structures and Algorithms with JavaScript from O'Reilly](http://shop.oreilly.com/product/0636920029557.do). I stopped on Chapter 12 - Sorting Algorithms. I can not understand how Insertion Sort works. Here is the code I am working with: [pasteBin - Insertion Sort](http://pastebin.com/fGV7RqbR) Below is the part that is confusing to me: ``` function insertionSort() { var temp, inner; for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { temp = this.dataStore[outer]; inner = outer; while (inner > 0 && (this.dataStore[inner-1] >= temp)) { this.dataStore[inner] = this.dataStore[inner-1]; --inner; } this.dataStore[inner] = temp; } console.log(this.toString()); } ``` Could anyone help and comment on this code?
2015/11/04
[ "https://Stackoverflow.com/questions/33530928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526354/" ]
The main concept behind insertion sort is to sort elements by comparison. The comparison occurs in your case for a `dataStore` array, containing what we assume to be comparable elements such as numbers. In order to compare element by element, this insertion sort algorithm starts at the beginning of the `dataStore` array and will continue to run until the end of the array has been reached. This is accomplished by a `for` loop: ``` for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) ``` As the algorithm goes through each element in order, it will: 1. Store the current element we are visiting in the array in a variable called `temp`. 2. Keep track of the location we are in the array via the `inner` and `outer` variables, where: * `outer` is our counter. * `inner` is a flag to determine whether or not we are visiting the first element in the array. Why is this important? Because there is no point in doing a comparison on the first element, on the first try. 3. It will compare the current element `temp` with each element that came before it in the `dataStore` array. This is accomplished by an inner `while` loop as seen here: `while (inner > 0 && (this.dataStore[inner-1] >= temp))` This tells you that, as long as all previous visited elements in the `dataStore` array are greater than or equal to `temp`, our temporary variable used to store the current element; we want to swap these values. Swapping them will accomplish the following: * Assume all elements before `this.dataStore[inner]` are greater than 10, and the currently visited element `this.dataStore[inner]` equals 5. This logically means that 5 needs to be at the beginning of the array. In such case we would continue to pass 5 all the way down to `this.datastore[0]` thanks to the while loop. Thus making 5 the first element in the array. At the end of this swapping, the value in `temp` is placed accordingly to the current position we are in the array, just to remind you which position this is, it's stored the variable `outer`. TLDR: I also like Justin Powell's answer as it sticks with the code, but I thought a walk through would be more useful depending on your level of understanding. I hope it helps!
```js const insertionSort = array => { const arr = Array.from(array); // avoid side effects for (let i = 1; i < arr.length; i++) { for (let j = i; j > 0 && arr[j] < arr[j - 1]; j--) { [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]]; } } return arr; }; ```
33,530,928
I recently started learning algorithms based on the book [Data Structures and Algorithms with JavaScript from O'Reilly](http://shop.oreilly.com/product/0636920029557.do). I stopped on Chapter 12 - Sorting Algorithms. I can not understand how Insertion Sort works. Here is the code I am working with: [pasteBin - Insertion Sort](http://pastebin.com/fGV7RqbR) Below is the part that is confusing to me: ``` function insertionSort() { var temp, inner; for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { temp = this.dataStore[outer]; inner = outer; while (inner > 0 && (this.dataStore[inner-1] >= temp)) { this.dataStore[inner] = this.dataStore[inner-1]; --inner; } this.dataStore[inner] = temp; } console.log(this.toString()); } ``` Could anyone help and comment on this code?
2015/11/04
[ "https://Stackoverflow.com/questions/33530928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526354/" ]
The main concept behind insertion sort is to sort elements by comparison. The comparison occurs in your case for a `dataStore` array, containing what we assume to be comparable elements such as numbers. In order to compare element by element, this insertion sort algorithm starts at the beginning of the `dataStore` array and will continue to run until the end of the array has been reached. This is accomplished by a `for` loop: ``` for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) ``` As the algorithm goes through each element in order, it will: 1. Store the current element we are visiting in the array in a variable called `temp`. 2. Keep track of the location we are in the array via the `inner` and `outer` variables, where: * `outer` is our counter. * `inner` is a flag to determine whether or not we are visiting the first element in the array. Why is this important? Because there is no point in doing a comparison on the first element, on the first try. 3. It will compare the current element `temp` with each element that came before it in the `dataStore` array. This is accomplished by an inner `while` loop as seen here: `while (inner > 0 && (this.dataStore[inner-1] >= temp))` This tells you that, as long as all previous visited elements in the `dataStore` array are greater than or equal to `temp`, our temporary variable used to store the current element; we want to swap these values. Swapping them will accomplish the following: * Assume all elements before `this.dataStore[inner]` are greater than 10, and the currently visited element `this.dataStore[inner]` equals 5. This logically means that 5 needs to be at the beginning of the array. In such case we would continue to pass 5 all the way down to `this.datastore[0]` thanks to the while loop. Thus making 5 the first element in the array. At the end of this swapping, the value in `temp` is placed accordingly to the current position we are in the array, just to remind you which position this is, it's stored the variable `outer`. TLDR: I also like Justin Powell's answer as it sticks with the code, but I thought a walk through would be more useful depending on your level of understanding. I hope it helps!
**insertion sort** means first step we are going to take one value from unsorted sublets and second step we are going to find out appropriate place for that in sorted sublet after find out right place we will insert that value in sorted sublet. you can get deep understanding from this video links:- [Insertion Sort Algorithm | Data Structure](https://youtu.be/yCxV0kBpA6M) ```js function insertionSort(arr) { for (let i = 1; i < arr.length; i++) { // first step let currentValue = arr[i] let j for (j = i - 1; j >= 0 && arr[j] > currentValue; j--) { // second step arr[j + 1] = arr[j] } arr[j + 1] = currentValue } return arr } console.log(insertionSort([5,2,6,3,1,4])) ```
33,530,928
I recently started learning algorithms based on the book [Data Structures and Algorithms with JavaScript from O'Reilly](http://shop.oreilly.com/product/0636920029557.do). I stopped on Chapter 12 - Sorting Algorithms. I can not understand how Insertion Sort works. Here is the code I am working with: [pasteBin - Insertion Sort](http://pastebin.com/fGV7RqbR) Below is the part that is confusing to me: ``` function insertionSort() { var temp, inner; for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { temp = this.dataStore[outer]; inner = outer; while (inner > 0 && (this.dataStore[inner-1] >= temp)) { this.dataStore[inner] = this.dataStore[inner-1]; --inner; } this.dataStore[inner] = temp; } console.log(this.toString()); } ``` Could anyone help and comment on this code?
2015/11/04
[ "https://Stackoverflow.com/questions/33530928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526354/" ]
Starting from the inner loop check if the current element is greater than the previous if yes, exit the loop since everything is sorted for the iteration, if not swap elements because the current needs to be moved to the left because it's smaller than the previous. The inner loop makes sure to swap elements until you encounter a sorted element which results with the break exiting the loop. After the swap occurs decrease the outer index (i) since you are going downwards to check if the upcoming element is lesser than the previous, you cannot keep the outer index (i) static. At last, the memIndex variable serves as a reset index because at the end of your inner loop you want to move to the next index. Index (i) should always be placed at the last element of the sorted array so that the inner loop can start the comparison again. ```js function insertionSort(arr) { let memIndex = 0 for (let i = 0; i < arr.length; i++) { memIndex = i; for (let j = i + 1; j >= 0; --j) { if (arr[j] >= arr[i]) { break; } if (arr[j] < arr[i]) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i = i - 1; } } i = memIndex; } return arr; } const arr = [5, 1, 6, 2, 4, 9, 9, 3, 1, 1, 1]; console.log('Unsorted array', arr); console.log('Sorted array:', insertionSort(arr)); ```
```js const insertionSort = array => { const arr = Array.from(array); // avoid side effects for (let i = 1; i < arr.length; i++) { for (let j = i; j > 0 && arr[j] < arr[j - 1]; j--) { [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]]; } } return arr; }; ```
33,530,928
I recently started learning algorithms based on the book [Data Structures and Algorithms with JavaScript from O'Reilly](http://shop.oreilly.com/product/0636920029557.do). I stopped on Chapter 12 - Sorting Algorithms. I can not understand how Insertion Sort works. Here is the code I am working with: [pasteBin - Insertion Sort](http://pastebin.com/fGV7RqbR) Below is the part that is confusing to me: ``` function insertionSort() { var temp, inner; for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { temp = this.dataStore[outer]; inner = outer; while (inner > 0 && (this.dataStore[inner-1] >= temp)) { this.dataStore[inner] = this.dataStore[inner-1]; --inner; } this.dataStore[inner] = temp; } console.log(this.toString()); } ``` Could anyone help and comment on this code?
2015/11/04
[ "https://Stackoverflow.com/questions/33530928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526354/" ]
Starting from the inner loop check if the current element is greater than the previous if yes, exit the loop since everything is sorted for the iteration, if not swap elements because the current needs to be moved to the left because it's smaller than the previous. The inner loop makes sure to swap elements until you encounter a sorted element which results with the break exiting the loop. After the swap occurs decrease the outer index (i) since you are going downwards to check if the upcoming element is lesser than the previous, you cannot keep the outer index (i) static. At last, the memIndex variable serves as a reset index because at the end of your inner loop you want to move to the next index. Index (i) should always be placed at the last element of the sorted array so that the inner loop can start the comparison again. ```js function insertionSort(arr) { let memIndex = 0 for (let i = 0; i < arr.length; i++) { memIndex = i; for (let j = i + 1; j >= 0; --j) { if (arr[j] >= arr[i]) { break; } if (arr[j] < arr[i]) { var temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i = i - 1; } } i = memIndex; } return arr; } const arr = [5, 1, 6, 2, 4, 9, 9, 3, 1, 1, 1]; console.log('Unsorted array', arr); console.log('Sorted array:', insertionSort(arr)); ```
**insertion sort** means first step we are going to take one value from unsorted sublets and second step we are going to find out appropriate place for that in sorted sublet after find out right place we will insert that value in sorted sublet. you can get deep understanding from this video links:- [Insertion Sort Algorithm | Data Structure](https://youtu.be/yCxV0kBpA6M) ```js function insertionSort(arr) { for (let i = 1; i < arr.length; i++) { // first step let currentValue = arr[i] let j for (j = i - 1; j >= 0 && arr[j] > currentValue; j--) { // second step arr[j + 1] = arr[j] } arr[j + 1] = currentValue } return arr } console.log(insertionSort([5,2,6,3,1,4])) ```
33,530,928
I recently started learning algorithms based on the book [Data Structures and Algorithms with JavaScript from O'Reilly](http://shop.oreilly.com/product/0636920029557.do). I stopped on Chapter 12 - Sorting Algorithms. I can not understand how Insertion Sort works. Here is the code I am working with: [pasteBin - Insertion Sort](http://pastebin.com/fGV7RqbR) Below is the part that is confusing to me: ``` function insertionSort() { var temp, inner; for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { temp = this.dataStore[outer]; inner = outer; while (inner > 0 && (this.dataStore[inner-1] >= temp)) { this.dataStore[inner] = this.dataStore[inner-1]; --inner; } this.dataStore[inner] = temp; } console.log(this.toString()); } ``` Could anyone help and comment on this code?
2015/11/04
[ "https://Stackoverflow.com/questions/33530928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526354/" ]
```js const insertionSort = array => { const arr = Array.from(array); // avoid side effects for (let i = 1; i < arr.length; i++) { for (let j = i; j > 0 && arr[j] < arr[j - 1]; j--) { [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]]; } } return arr; }; ```
**insertion sort** means first step we are going to take one value from unsorted sublets and second step we are going to find out appropriate place for that in sorted sublet after find out right place we will insert that value in sorted sublet. you can get deep understanding from this video links:- [Insertion Sort Algorithm | Data Structure](https://youtu.be/yCxV0kBpA6M) ```js function insertionSort(arr) { for (let i = 1; i < arr.length; i++) { // first step let currentValue = arr[i] let j for (j = i - 1; j >= 0 && arr[j] > currentValue; j--) { // second step arr[j + 1] = arr[j] } arr[j + 1] = currentValue } return arr } console.log(insertionSort([5,2,6,3,1,4])) ```
32,702,926
I want to send the value of my PHP session variable to JavaScript in the same file. I tried this code, but it doesn't work. Please help me resolve the issue. Here is what I am trying : ``` <?php session_start(); ?> <h2> <?php echo "Welcome, " .$_SESSION["name"]; ?> </h2> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript" src="chat.js"></script> </head> <body onload="init();"> <noscript> Your browser does not support Javascript!! </noscript> <!-- Some HTML Code --> <div> <a href="../index.php">Go back</a> <a href="../home.php?SignOut" id= "left">Sign Out</a> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function() { $("#left").click(function() { //remove user_name. Set action: left var user_name = <?php echo json_encode($_SESSION["name"]) ?>; $.post('php/users.php', {user_name: user_name, action: 'left' }); }); }); </script> </div> </body> </html> ``` This is my users.php file ``` if(isset($_POST['user_name'], $_POST['action'])) { $user_name = $_POST['user_name']; $action = $_POST['action']; if($action == 'joined') { user_joined($user_name); } } else if(isset($_POST['action'])) { $action = $_POST['action']; if($action == 'list') { foreach(user_list() as $user) { $link_address = "Chat/index.php"; echo '<a class="a" name="a" href='.$link_address.'>'.$user.'</a>'; echo '<br />'; } } else if($action == 'left') { //call user_left function user_left(); } } function user_left() { $servername = ""; $username = ""; $password = ""; $dbname = ""; //Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $user_name = $_SESSION["name"]; $sql = "DELETE FROM online_users WHERE user_name = '$user_name'"; $query = "DELETE FROM chat WHERE to_user = '$user_name'"; $result = $conn->query($query); if($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error in deleting: " . $sql. "<br>" . $conn->error; } $conn->close(); } ```
2015/09/21
[ "https://Stackoverflow.com/questions/32702926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4062119/" ]
First of all you have to look in debug console for errors (usualy it can be opened with F12 key). I see a problem in your code: php echo statement has to be in outer quotes, because it is interpreted as a string in JS: ``` var user_name = "<?php echo $_SESSION["name"] ?>"; ``` Just open console and you will see exact line and character where the error is. Other way of passing variables from PHP to JS is cookies.
Turned out to be a silly mistake. Sorry for troubling you all guys. I figured out the error. I was able to read php sessions in JS (Figured that out when I inspected element on chrome). But, I guess that wasn't required and I just used the ``` $.post('php/users.php', { action: 'left' }); ``` Rather than trusting the post parameter on username, I used sessions variables. The main issue was that I was not able to delete the username in the user.php file and I figured out that because I used ``` $.post('php/users.php', { action: 'left' }), ``` I am actually not sending any user\_name in the post parameter. My call to user\_left function was in the if condition where I was checking ``` if (isset $_POST[user_name] && $_POST[action]), ``` and therefore, I couldnt call user\_left function. This was my code earlier ``` if(isset($_POST['user_name'], $_POST['action'])) { $user_name = $_POST['user_name']; $action = $_POST['action']; if($action == 'joined') { user_joined($user_name); } else if($action == 'left') { //call user_left function user_left(); } } else if(isset($_POST['action'])) { $action = $_POST['action']; if($action == 'list') { foreach(user_list() as $user) { $link_address = "Chat/index.php"; echo '<a class="a" name="a" href='.$link_address.'>'.$user.'</a>'; echo '<br />'; } } } ``` I changed it to: ``` if(isset($_POST['user_name'], $_POST['action'])) { $user_name = $_POST['user_name']; $action = $_POST['action']; if($action == 'joined') { user_joined($user_name); } } else if(isset($_POST['action'])) { $action = $_POST['action']; if($action == 'list') { foreach(user_list() as $user) { //echo $user, '<br />'; $link_address = "Chat/index.php"; echo '<a class="a" name="a" href='.$link_address.'>'.$user.'</a>'; echo '<br />'; } } else if($action == 'left') { //call user_left function user_left(); } } ```
32,702,926
I want to send the value of my PHP session variable to JavaScript in the same file. I tried this code, but it doesn't work. Please help me resolve the issue. Here is what I am trying : ``` <?php session_start(); ?> <h2> <?php echo "Welcome, " .$_SESSION["name"]; ?> </h2> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript" src="chat.js"></script> </head> <body onload="init();"> <noscript> Your browser does not support Javascript!! </noscript> <!-- Some HTML Code --> <div> <a href="../index.php">Go back</a> <a href="../home.php?SignOut" id= "left">Sign Out</a> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function() { $("#left").click(function() { //remove user_name. Set action: left var user_name = <?php echo json_encode($_SESSION["name"]) ?>; $.post('php/users.php', {user_name: user_name, action: 'left' }); }); }); </script> </div> </body> </html> ``` This is my users.php file ``` if(isset($_POST['user_name'], $_POST['action'])) { $user_name = $_POST['user_name']; $action = $_POST['action']; if($action == 'joined') { user_joined($user_name); } } else if(isset($_POST['action'])) { $action = $_POST['action']; if($action == 'list') { foreach(user_list() as $user) { $link_address = "Chat/index.php"; echo '<a class="a" name="a" href='.$link_address.'>'.$user.'</a>'; echo '<br />'; } } else if($action == 'left') { //call user_left function user_left(); } } function user_left() { $servername = ""; $username = ""; $password = ""; $dbname = ""; //Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $user_name = $_SESSION["name"]; $sql = "DELETE FROM online_users WHERE user_name = '$user_name'"; $query = "DELETE FROM chat WHERE to_user = '$user_name'"; $result = $conn->query($query); if($conn->query($sql) === TRUE) { echo "Record deleted successfully"; } else { echo "Error in deleting: " . $sql. "<br>" . $conn->error; } $conn->close(); } ```
2015/09/21
[ "https://Stackoverflow.com/questions/32702926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4062119/" ]
First of all you have to look in debug console for errors (usualy it can be opened with F12 key). I see a problem in your code: php echo statement has to be in outer quotes, because it is interpreted as a string in JS: ``` var user_name = "<?php echo $_SESSION["name"] ?>"; ``` Just open console and you will see exact line and character where the error is. Other way of passing variables from PHP to JS is cookies.
In your main PHP, change: ``` var user_name = <?php echo json_encode($_SESSION["name"]) ?>; $.post('php/users.php', {user_name: user_name, action: 'left' }); ``` To: ``` $.post('php/users.php', { action: 'left' }); ``` Then in users.php change: ``` if(isset($_POST['user_name'], $_POST['action'])) { $user_name = $_POST['user_name']; $action = $_POST['action']; if($action == 'joined') { user_joined($user_name); } } ``` To: ``` session_start(); if(isset($_SESSION['name'], $_POST['action'])) { $user_name = $_SESSION['name']; $action = $_POST['action']; if($action == 'joined') { user_joined($user_name); } } ``` Why? Because you already have a session with the user logged in, so the user\_name is in the session. The safest place to retrieve it from will always be the session. If you print the user\_name from session to your HTML/Javascript code and have it sent back roundtrip to the server in a POST parameter, and trust that parameter, then the user could have changed the username in his browser's developer tools (or some other way) to someone else'se user\_name to log them out (*or even impersonate them in the chat via your user\_joined method*). You'd be creating a security hole. So don't send the user\_name roundtrip: just read it from the session on the server-side. Also, be sure to be consistent on whether its `$_SESSION["name"]` or `$_SESSION["user_name"]`.
48,888,802
I am very worried about this issue. It always throws an exception: > > `JSONObject` cannot converted to `JSONArray` > > > This is in Android. Here is the code: ``` AndroidNetworking.post(url) .addBodyParameter("moving_item", moving.getText().toString()) .addBodyParameter("vehical_move", v) .addBodyParameter("pick_up", starting.getText().toString()) .addBodyParameter("lat_pickup", String.valueOf(strlat)) .addBodyParameter("lng_pickup", String.valueOf(strlng)) .addBodyParameter("lat_dropoff", String.valueOf(endlat)) .addBodyParameter("lng_dropoff", String.valueOf(endlng)) .addBodyParameter("description",descriptionbox.getText().toString()) .addBodyParameter("date",dateserv) .addBodyParameter("email", emailtextfield.getText().toString()) .addBodyParameter("price", pricebox.getText().toString()) .addBodyParameter("comments", detailedbox.getText().toString()) .addBodyParameter("loadtype", drop) .addBodyParameter("drop_off", destination.getText().toString()) .addBodyParameter("distance",dsitnc) .addBodyParameter("image1" , String.valueOf(imageFile1)) .addBodyParameter("image2" ,String.valueOf(imageFile2)) .addBodyParameter("image3" , String.valueOf(imageFile3)) .setPriority(Priority.HIGH) .build() .getAsString(new StringRequestListener() { public void onResponse(String response) { try { /* JSONObject jsonResponse = new JSONObject(new String(response)); JSONArray mtUsers = jsonResponse.getJSONArray("result"); JSONObject jsonObject = mtUsers.getJSONObject(0); String resu = jsonObject.optString("result"); */ /* JSONArray res = new JSONObject(response).getJSONArray("result"); JSONArray mes = new JSONObject(response).getJSONArray("message");*/ JSONArray jsonArray = new JSONArray(response); JSONObject jsonObject = jsonArray.getJSONObject(0); // JSONObject jsonObject1 = mes.getJSONObject(0); //JSONArray result1 = new JSONObject(response).getJSONArray("result"); String result = jsonObject.getString("result"); String message = jsonObject.getString("message"); ```
2018/02/20
[ "https://Stackoverflow.com/questions/48888802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8750783/" ]
The `library` function does not take multiple library names as arguments although doesn't seem to throw an error. You probably have all the libraries loaded in the console, but when `knitr` runs it does so in a new environment and needs to load them all anew. Try this at the top of your code: `library(reshape2) library(knitr) library(ggplot2)` If you want to load them all in a single line, there is already a SO post about that here: [Load multiple packages at once](https://stackoverflow.com/questions/8175912/load-multiple-packages-at-once)
I resolve this, the problem was pacman. For some reason, was not loading the packages properly, I switched back to the baseline command and the issues is resolved. Thanks to everyone
73,613,716
I am trying to figure out how my Javascript code can listen to my native modules events that are being emitted from my Swift code in my React Native app. I cannot seem to find any official documentation and anything I find after a Google search is either outdated or is written in Obj-C whereas my event is fired from my Swift code. I hope that makes sense and any help would be appreciated! Thanks, Aiden
2022/09/05
[ "https://Stackoverflow.com/questions/73613716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13672278/" ]
It's actually described in quite a detail [here](https://reactnative.dev/docs/native-modules-ios#sending-events-to-javascript). 1. First you create an Objective-C bridge to catch events from Swift. 2. Then in Objective-C again, you implement an `RCTEventEmitter` (can be same or different class) This is the class that will send events to JS. The events are sent using `sendEventWithName` function Here's a very rough sketch: Step 1: catch Swift events ``` @interface MyBridge() <SomeDelegate> @end @implementation MyBridge // Here's my delegate function: - (void)myDelegateCalled // Received an event // Calling bridge to send the event to JS BridgeEventEmitter send:someData ... ``` Step 2: send them to JS ``` // Here's the BridgeEventEmitter: @interface BridgeEventEmitter : RCTEventEmitter <RCTBridgeModule> @end @implementation BridgeEventEmitter + (void)send:(NSString *)something { [self sendEventWithName:@"EventName" body:something]; } ```
I don't think you can emit an event in custom swift code and then catch it in your react native code. I might be wrong. maybe consider local storage or server-side storage?
382,382
Is there any way in JavaScript how to find out user clicked through the same domain 2 or more times? I need to popup a window after user clicked anywhere on the site for 3 times. I know how to do it after one click - with `document.referrer` or `addEventListener`, but then I'm lost. I need something that will capture all click events (not only links) and count them.
2008/12/19
[ "https://Stackoverflow.com/questions/382382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46866/" ]
Sure. You need to store a list of users' click events, either in a cookie, or in a server-side data store. On every recorded click, increment the count by one, and do your thing when the number hits 3. Try using session cookies to store state between pages -- they're fast, pretty widely compatible, and will zero out when the browser shuts down, to keep from spamming your users' cookie jars.
Thanks for all your advice. I tried this code. But after the refresh the **clicked** variable goes to 0 again. I need to save every new value of **clicked** into cookie (or whatever else), so its number will rise with every click on link on page. Is it possible to change value of the variable in cookie this way? > > window.onload = function(){ > > > ``` var **allLinks** = document.getElementsByTagName("a"); var **clicked** = 0; **doCookie**('popunder',clicked,1); for(i=0;i<=allLinks.length;i++){ allLinks[i].addEventListener("click",countClicks,true); } function **countClicks**(){ if(clicked == 3){ popunder(); //something to do } else{ alert(readCookie('popunder')); return clicked++; } } function **doCookie**(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function **readCookie**(name) { var readName = name + "="; var cSplit = document.cookie.split(';'); for(var i=0;i < cSplit.length;i++) { var sc = cSplit[i]; while (sc.charAt(0)==' ') sc = sc.substring(1,sc.length); if (sc.indexOf(readName) == 0) return sc.substring(readName.length,sc.length); } return null; } ```
382,382
Is there any way in JavaScript how to find out user clicked through the same domain 2 or more times? I need to popup a window after user clicked anywhere on the site for 3 times. I know how to do it after one click - with `document.referrer` or `addEventListener`, but then I'm lost. I need something that will capture all click events (not only links) and count them.
2008/12/19
[ "https://Stackoverflow.com/questions/382382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46866/" ]
I tried this and it worked fine: ``` window.onload = function() { var clicked = readCookie('popunder'); if(clicked == null) { clicked = 0; } var allLinks = document.getElementsByTagName("a"); for(i=0;i<=allLinks.length;i++) { allLinks[i].addEventListener("click",countClicks,true); } function countClicks() { if(clicked == 2) { popunder(); //something to do } else { clicked++; doCookie('popunder', clicked, 1); alert(clicked); } } function popunder() { alert('thats 3 clicks!'); } function doCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else { var expires = ""; } document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var readName = name + "="; var cSplit = document.cookie.split(';'); for(var i=0;i < cSplit.length;i++) { var sc = cSplit[i]; while (sc.charAt(0)==' ') sc = sc.substring(1,sc.length); if (sc.indexOf(readName) == 0) return sc.substring(readName.length,sc.length); } return null; } } ```
Thanks for all your advice. I tried this code. But after the refresh the **clicked** variable goes to 0 again. I need to save every new value of **clicked** into cookie (or whatever else), so its number will rise with every click on link on page. Is it possible to change value of the variable in cookie this way? > > window.onload = function(){ > > > ``` var **allLinks** = document.getElementsByTagName("a"); var **clicked** = 0; **doCookie**('popunder',clicked,1); for(i=0;i<=allLinks.length;i++){ allLinks[i].addEventListener("click",countClicks,true); } function **countClicks**(){ if(clicked == 3){ popunder(); //something to do } else{ alert(readCookie('popunder')); return clicked++; } } function **doCookie**(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function **readCookie**(name) { var readName = name + "="; var cSplit = document.cookie.split(';'); for(var i=0;i < cSplit.length;i++) { var sc = cSplit[i]; while (sc.charAt(0)==' ') sc = sc.substring(1,sc.length); if (sc.indexOf(readName) == 0) return sc.substring(readName.length,sc.length); } return null; } ```
91,831
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
Import the `System.Web.Configuration` namespace and do something like: ``` var configuration = WebConfigurationManager.OpenWebConfiguration("/"); var authenticationSection = (AuthenticationSection)configuration.GetSection("system.web/authentication"); if (authenticationSection.Mode == AuthenticationMode.Forms) { //do something } ```
In ASP.Net Core you can use this: ``` public Startup(IHostingEnvironment env, IConfiguration config) { var enabledAuthTypes = config["IIS_HTTPAUTH"].Split(';').Where(l => !String.IsNullOrWhiteSpace(l)).ToList(); } ```
91,831
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
The mode property from the authenticationsection: [AuthenticationSection.Mode Property (System.Web.Configuration)](http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection.mode(VS.80).aspx). And you can even modify it. ``` // Get the current Mode property. AuthenticationMode currentMode = authenticationSection.Mode; // Set the Mode property to Windows. authenticationSection.Mode = AuthenticationMode.Windows; ``` This article describes [how to get a reference to the AuthenticationSection](http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection(VS.80).aspx).
Import the `System.Web.Configuration` namespace and do something like: ``` var configuration = WebConfigurationManager.OpenWebConfiguration("/"); var authenticationSection = (AuthenticationSection)configuration.GetSection("system.web/authentication"); if (authenticationSection.Mode == AuthenticationMode.Forms) { //do something } ```
91,831
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
In ASP.Net Core you can use this: ``` public Startup(IHostingEnvironment env, IConfiguration config) { var enabledAuthTypes = config["IIS_HTTPAUTH"].Split(';').Where(l => !String.IsNullOrWhiteSpace(l)).ToList(); } ```
use an xpath query //configuration/system.web/authentication[mode] ? ``` protected void Page_Load(object sender, EventArgs e) { XmlDocument config = new XmlDocument(); config.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); XmlNode node = config.SelectSingleNode("//configuration/system.web/authentication"); this.Label1.Text = node.Attributes["mode"].Value; } ```
91,831
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
Import the `System.Web.Configuration` namespace and do something like: ``` var configuration = WebConfigurationManager.OpenWebConfiguration("/"); var authenticationSection = (AuthenticationSection)configuration.GetSection("system.web/authentication"); if (authenticationSection.Mode == AuthenticationMode.Forms) { //do something } ```
You can also get the authentication mode by using the static [`ConfigurationManager`](https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(v=vs.110).aspx) class to get the section and then the enum `AuthenticationMode`. ``` AuthenticationMode authMode = ((AuthenticationSection) ConfigurationManager.GetSection("system.web/authentication")).Mode; ``` [The difference between WebConfigurationManager and ConfigurationManager](https://stackoverflow.com/questions/698157/whats-the-difference-between-the-webconfigurationmanager-and-the-configurationm) --- If you want to retrieve the name of the constant in the specified enumeration you can do this by using the `Enum.GetName(Type, Object)` method ``` Enum.GetName(typeof(AuthenticationMode), authMode); // e.g. "Windows" ```
91,831
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
You can also get the authentication mode by using the static [`ConfigurationManager`](https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(v=vs.110).aspx) class to get the section and then the enum `AuthenticationMode`. ``` AuthenticationMode authMode = ((AuthenticationSection) ConfigurationManager.GetSection("system.web/authentication")).Mode; ``` [The difference between WebConfigurationManager and ConfigurationManager](https://stackoverflow.com/questions/698157/whats-the-difference-between-the-webconfigurationmanager-and-the-configurationm) --- If you want to retrieve the name of the constant in the specified enumeration you can do this by using the `Enum.GetName(Type, Object)` method ``` Enum.GetName(typeof(AuthenticationMode), authMode); // e.g. "Windows" ```
use an xpath query //configuration/system.web/authentication[mode] ? ``` protected void Page_Load(object sender, EventArgs e) { XmlDocument config = new XmlDocument(); config.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); XmlNode node = config.SelectSingleNode("//configuration/system.web/authentication"); this.Label1.Text = node.Attributes["mode"].Value; } ```
91,831
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
The mode property from the authenticationsection: [AuthenticationSection.Mode Property (System.Web.Configuration)](http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection.mode(VS.80).aspx). And you can even modify it. ``` // Get the current Mode property. AuthenticationMode currentMode = authenticationSection.Mode; // Set the Mode property to Windows. authenticationSection.Mode = AuthenticationMode.Windows; ``` This article describes [how to get a reference to the AuthenticationSection](http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection(VS.80).aspx).
Try `Context.User.Identity.AuthenticationType` Go for PB's answer folks
91,831
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
You can also get the authentication mode by using the static [`ConfigurationManager`](https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(v=vs.110).aspx) class to get the section and then the enum `AuthenticationMode`. ``` AuthenticationMode authMode = ((AuthenticationSection) ConfigurationManager.GetSection("system.web/authentication")).Mode; ``` [The difference between WebConfigurationManager and ConfigurationManager](https://stackoverflow.com/questions/698157/whats-the-difference-between-the-webconfigurationmanager-and-the-configurationm) --- If you want to retrieve the name of the constant in the specified enumeration you can do this by using the `Enum.GetName(Type, Object)` method ``` Enum.GetName(typeof(AuthenticationMode), authMode); // e.g. "Windows" ```
In ASP.Net Core you can use this: ``` public Startup(IHostingEnvironment env, IConfiguration config) { var enabledAuthTypes = config["IIS_HTTPAUTH"].Split(';').Where(l => !String.IsNullOrWhiteSpace(l)).ToList(); } ```
91,831
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
The mode property from the authenticationsection: [AuthenticationSection.Mode Property (System.Web.Configuration)](http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection.mode(VS.80).aspx). And you can even modify it. ``` // Get the current Mode property. AuthenticationMode currentMode = authenticationSection.Mode; // Set the Mode property to Windows. authenticationSection.Mode = AuthenticationMode.Windows; ``` This article describes [how to get a reference to the AuthenticationSection](http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection(VS.80).aspx).
use an xpath query //configuration/system.web/authentication[mode] ? ``` protected void Page_Load(object sender, EventArgs e) { XmlDocument config = new XmlDocument(); config.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); XmlNode node = config.SelectSingleNode("//configuration/system.web/authentication"); this.Label1.Text = node.Attributes["mode"].Value; } ```
91,831
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
The mode property from the authenticationsection: [AuthenticationSection.Mode Property (System.Web.Configuration)](http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection.mode(VS.80).aspx). And you can even modify it. ``` // Get the current Mode property. AuthenticationMode currentMode = authenticationSection.Mode; // Set the Mode property to Windows. authenticationSection.Mode = AuthenticationMode.Windows; ``` This article describes [how to get a reference to the AuthenticationSection](http://msdn.microsoft.com/en-us/library/system.web.configuration.authenticationsection(VS.80).aspx).
You can also get the authentication mode by using the static [`ConfigurationManager`](https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(v=vs.110).aspx) class to get the section and then the enum `AuthenticationMode`. ``` AuthenticationMode authMode = ((AuthenticationSection) ConfigurationManager.GetSection("system.web/authentication")).Mode; ``` [The difference between WebConfigurationManager and ConfigurationManager](https://stackoverflow.com/questions/698157/whats-the-difference-between-the-webconfigurationmanager-and-the-configurationm) --- If you want to retrieve the name of the constant in the specified enumeration you can do this by using the `Enum.GetName(Type, Object)` method ``` Enum.GetName(typeof(AuthenticationMode), authMode); // e.g. "Windows" ```
91,831
Say I have the following web.config: ``` <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authentication mode="Windows"></authentication> </system.web> </configuration> ``` Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?
2008/09/18
[ "https://Stackoverflow.com/questions/91831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
Try `Context.User.Identity.AuthenticationType` Go for PB's answer folks
use an xpath query //configuration/system.web/authentication[mode] ? ``` protected void Page_Load(object sender, EventArgs e) { XmlDocument config = new XmlDocument(); config.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); XmlNode node = config.SelectSingleNode("//configuration/system.web/authentication"); this.Label1.Text = node.Attributes["mode"].Value; } ```
54,481,645
First of I'm rather new at actually posting at Stack Overflow but I will of course try my best to have all the relevant information here AND share the solution once found because I can imagine more people might be having trouble with this. So we've started with a system that has multiple small microservices as the backend and we found Apollo server that's able to retrieve schemas from the graphql endpoints and stitch them together so we can have one nice point of entry. We've got that working but apollo server has nothing really to help with the overal architecture. Thats when we found NestJS and because we use angular on the frontend and NestJS is so simular to it it seemed like a perfect fit. The problem we're having though is that we can't seem to get the following functionality working: - I would like to have a module which contains a service that can be given a number of endpoints (uri's to microservices) - With the enpoints given the service should retrieve the graphQL schemas from these endpoints and make them into RemoteExecutableSchemas and then merge them. - After merging them and making 1 big schema with the (remote) link information so that graphQL knows where to fetch the data. - After this is happened we would like to add some stitching so that all relationships are present (but this is not where my problem lies) I've been going through the official docs (<https://docs.nestjs.com/graphql/quick-start>) through the examples of them (<https://github.com/nestjs/nest/tree/master/sample/12-graphql-apollo>) and of course checked out the github project (<https://github.com/nestjs/graphql>) and been nosing in this repo to see what the code does on the background. We've tried several things to fetch them on the fly but couldn't get the schemas into the GraphQLModule before it instantiated. Then we thought it might be acceptable to have the service retrieve a graphqlSchema from an endpoint and write it to a file using printSchema(schema) which actually works, but then I lose the link information effectively making it a local schema instead of a remote schema. Now we've come up with the following but are once again stuck. lets start with a little snippet from my package.json so people know the versions :) ``` "dependencies": { "@nestjs/common": "^5.4.0", "@nestjs/core": "^5.4.0", "@nestjs/graphql": "^5.5.1", "apollo-link-http": "^1.5.9", "apollo-server-express": "^2.3.2", "graphql": "^14.1.1", "reflect-metadata": "^0.1.12", "rimraf": "^2.6.2", "rxjs": "^6.2.2", "typescript": "^3.0.1" }, "devDependencies": { "@nestjs/testing": "^5.1.0", "@types/express": "^4.16.0", "@types/jest": "^23.3.1", "@types/node": "^10.7.1", "@types/supertest": "^2.0.5", "jest": "^23.5.0", "nodemon": "^1.18.3", "prettier": "^1.14.2", "supertest": "^3.1.0", "ts-jest": "^23.1.3", "ts-loader": "^4.4.2", "ts-node": "^7.0.1", "tsconfig-paths": "^3.5.0", "tslint": "5.11.0" }, ``` So, at the moment I have a schema-handler module which looks like this: ``` @Module({ imports: [GraphQLModule.forRootAsync({ useClass: GqlConfigService })], controllers: [SchemaHandlerController], providers: [SchemaFetcherService, SchemaSticherService, GqlConfigService] }) export class SchemaHandlerModule { } ``` So here we import the GraphQLModule and let it use the gql-config service to handle giving it the GraphQLModuleOptions. The gql-config service looks like this: ``` @Injectable() export class GqlConfigService implements GqlOptionsFactory { async createGqlOptions(): Promise<GqlModuleOptions> { try{ const countrySchema = this.createCountrySchema(); return { typeDefs: [countrySchema] }; } catch(err) { console.log(err); return {}; } } ``` So I'm async creating the GqlModuleOptions and await the result. createCountrySchema functions looks like this: ``` public async createCountrySchema() : GraphQLSchema{ const uri = 'https://countries.trevorblades.com/Graphql'; try { const link = new HttpLink({ uri: uri, fetch }); const remoteSchema = await introspectSchema(link); return makeRemoteExecutableSchema({ schema: remoteSchema, link }); } catch (err) { console.log('ERROR: exception when trying to connect to ' + uri + ' Error Message: ' + err); } }; ``` For the sake of the POC I just got a simple public graphQL API as an endpoint. This function is returning a GraphQLSchema object which I would then like to add (in some way) to the GqlOptions and have it visible on the playground. We've also tried having createCountrySchema return a Promise and await it when calling the function in the createGqlOptions but that doesn't seem to make a difference. The actuall error we're getting looks like this: ``` [Nest] 83 - 2/1/2019, 2:10:57 PM [RoutesResolver] SchemaHandlerController {/schema-handler}: +1ms apollo_1 | (node:83) UnhandledPromiseRejectionWarning: Syntax Error: Unexpected [ apollo_1 | apollo_1 | GraphQL request (2:9) apollo_1 | 1: apollo_1 | 2: [object Promise] apollo_1 | ^ apollo_1 | 3: apollo_1 | apollo_1 | at syntaxError (/opt/node_modules/graphql/error/syntaxError.js:24:10) apollo_1 | at unexpected (/opt/node_modules/graphql/language/parser.js:1483:33) apollo_1 | at parseDefinition (/opt/node_modules/graphql/language/parser.js:155:9) apollo_1 | at many (/opt/node_modules/graphql/language/parser.js:1513:16) apollo_1 | at parseDocument (/opt/node_modules/graphql/language/parser.js:115:18) apollo_1 | at parse (/opt/node_modules/graphql/language/parser.js:50:10) apollo_1 | at parseDocument (/opt/node_modules/graphql-tag/src/index.js:129:16) apollo_1 | at Object.gql (/opt/node_modules/graphql-tag/src/index.js:170:10) apollo_1 | at GraphQLFactory.<anonymous> (/opt/node_modules/@nestjs/graphql/dist/graphql.factory.js:48:55) apollo_1 | at Generator.next (<anonymous>) apollo_1 | (node:83) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2) apollo_1 | (node:83) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. ``` I think I'm rather close with this approach but I'm not really sure. The error I'm getting states that all Promises must be handled with a try/catch so that we won't get an unhandled Promise and I believe I do that everywhere so I don't understand where this error is coming from... If anyone has any pointers, solution or advice I would be very very happy. I've been strugling to get the functionality we want fitted in nestjs for more then a week now and have seen loads of examples, snippets and discussions on this but I cannot find an example that stitches remote schemas and handing them back to nestjs. I would be very gratefull for any comments on this, with kind regards, Tjeerd
2019/02/01
[ "https://Stackoverflow.com/questions/54481645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11000953/" ]
I had solved schema stitching problem by using transform method. **Look src/graphql.config/graphql.config.service.ts** [here my code](https://codesandbox.io/s/github/OLDIN/nestjs-schema-stitching) [link for the test](https://wic63.sse.codesandbox.io/graphql) ``` import { Injectable } from '@nestjs/common'; import { GqlOptionsFactory, GqlModuleOptions } from '@nestjs/graphql'; import * as ws from 'ws'; import { makeRemoteExecutableSchema, mergeSchemas, introspectSchema } from 'graphql-tools'; import { HttpLink } from 'apollo-link-http'; import nodeFetch from 'node-fetch'; import { split, from, NextLink, Observable, FetchResult, Operation } from 'apollo-link'; import { getMainDefinition } from 'apollo-utilities'; import { OperationTypeNode, buildSchema as buildSchemaGraphql, GraphQLSchema, printSchema } from 'graphql'; import { setContext } from 'apollo-link-context'; import { SubscriptionClient, ConnectionContext } from 'subscriptions-transport-ws'; import * as moment from 'moment'; import { extend } from 'lodash'; import { ConfigService } from '../config'; declare const module: any; interface IDefinitionsParams { operation?: OperationTypeNode; kind: 'OperationDefinition' | 'FragmentDefinition'; } interface IContext { graphqlContext: { subscriptionClient: SubscriptionClient, }; } @Injectable() export class GqlConfigService implements GqlOptionsFactory { private remoteLink: string = 'https://countries.trevorblades.com'; constructor( private readonly config: ConfigService ) {} async createGqlOptions(): Promise<GqlModuleOptions> { const remoteExecutableSchema = await this.createRemoteSchema(); return { autoSchemaFile: 'schema.gql', transformSchema: async (schema: GraphQLSchema) => { return mergeSchemas({ schemas: [ schema, remoteExecutableSchema ] }); }, debug: true, playground: { env: this.config.environment, endpoint: '/graphql', subscriptionEndpoint: '/subscriptions', settings: { 'general.betaUpdates': false, 'editor.theme': 'dark' as any, 'editor.reuseHeaders': true, 'tracing.hideTracingResponse': true, 'editor.fontSize': 14, // tslint:disable-next-line:quotemark 'editor.fontFamily': "'Source Code Pro', 'Consolas', 'Inconsolata', 'Droid Sans Mono', 'Monaco', monospace", 'request.credentials': 'include', }, }, tracing: true, installSubscriptionHandlers: true, introspection: true, subscriptions: { path: '/subscriptions', keepAlive: 10000, onConnect: async (connectionParams, webSocket: any, context) => { const subscriptionClient = new SubscriptionClient(this.config.get('HASURA_WS_URI'), { connectionParams: { ...connectionParams, ...context.request.headers }, reconnect: true, lazy: true, }, ws); return { subscriptionClient, }; }, async onDisconnect(webSocket, context: ConnectionContext) { const { subscriptionClient } = await context.initPromise; if (subscriptionClient) { subscriptionClient.close(); } }, }, context(context) { const contextModified: any = { userRole: 'anonymous', currentUTCTime: moment().utc().format() }; if (context && context.connection && context.connection.context) { contextModified.subscriptionClient = context.connection.context.subscriptionClient; } return contextModified; }, }; } private wsLink(operation: Operation, forward?: NextLink): Observable<FetchResult> | null { const context = operation.getContext(); const { graphqlContext: { subscriptionClient } }: any = context; return subscriptionClient.request(operation); } private async createRemoteSchema(): Promise<GraphQLSchema> { const httpLink = new HttpLink({ uri: this.remoteLink, fetch: nodeFetch as any, }); const remoteIntrospectedSchema = await introspectSchema(httpLink); const remoteSchema = printSchema(remoteIntrospectedSchema); const link = split( ({ query }) => { const { kind, operation }: IDefinitionsParams = getMainDefinition(query); return kind === 'OperationDefinition' && operation === 'subscription'; }, this.wsLink, httpLink, ); const contextLink = setContext((request, prevContext) => { extend(prevContext.headers, { 'X-hasura-Role': prevContext.graphqlContext.userRole, 'X-Hasura-Utc-Time': prevContext.graphqlContext.currentUTCTime, }); return prevContext; }); const buildedHasuraSchema = buildSchemaGraphql(remoteSchema); const remoteExecutableSchema = makeRemoteExecutableSchema({ link: from([contextLink, link]), schema: buildedHasuraSchema, }); return remoteExecutableSchema; } } ```
This is a simplification of the first answer - wherever the GraphQLModule.forRoot(async) is being invoked ( coded inside the appModule file or exported separately ), the below snippet of code should help ``` import { GraphQLModule } from "@nestjs/graphql"; import { CommonModule } from "@Common"; import { GraphQLSchema } from 'graphql'; import { ConfigInterface } from "@Common/config/ConfigService"; import { stitchSchemas } from '@graphql-tools/stitch'; import { introspectSchema } from '@graphql-tools/wrap'; import { print } from 'graphql'; import { fetch } from 'cross-fetch'; export default GraphQLModule.forRootAsync({ imports: [CommonModule], useFactory: async (configService: ConfigInterface) => { const remoteSchema = await createRemoteSchema('https://countries.trevorblades.com/graphql'); return { playground: process.env.NODE_ENV !== "production", context: ({ req, res }) => ({ req, res }), installSubscriptionHandlers: true, autoSchemaFile: "schema.gql", transformSchema : async (schema: GraphQLSchema) => { return stitchSchemas({ subschemas: [ schema, remoteSchema ] }); }, }; }, }); const createRemoteSchema = async (url : string) =>{ const executor = async ({ document, variables }) => { const query = print(document); const fetchResult = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query, variables }) }); return fetchResult.json(); }; return { schema: await introspectSchema(executor), executor: executor }; } ``` Reference : <https://www.graphql-tools.com/docs/stitch-combining-schemas/#stitching-remote-schemas>
3,848,144
i use Javascript(AJAX) and want to change the addressbar Ex: <http://mywebsite.com> to http//mywebsite.com?web=info
2010/10/03
[ "https://Stackoverflow.com/questions/3848144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/385335/" ]
you can not change the url without the page actually redirecting. You can however append a hashtag to the url. <http://mywebsite.com> to <http://mywebsite.com#something> See this question on StackOverflow. [Attaching hashtag to URL with javascript](https://stackoverflow.com/questions/2366481/attaching-hashtag-to-url-with-javascript)
You don't want ajax just do this: ``` window.location = "http://mywebsite.com?web=info"; ```
31,463,659
I'm using noUiSlider (<http://refreshless.com/nouislider/>) on a form which will have dozens of sliders on it. Rather than copy/pasting the code for each, I thought I could just set up an array of class names and a loop. That works; ie, it sets up working sliders. However the form also has to show the value of a slider upon update, and that's the part that I can't work out. I know how to do it with a static value but not in the loop ... Simplified example: JavaScript: ``` var steps = [ 'Never', 'Occasionally', 'Frequently', 'Constant' ]; // This array will have many more var slider_names = [ 'slider', 'slider2' ]; var sliders = []; for (var i = 0; i < slider_names.length; i++) { sliders.push(document.getElementById(slider_names[i])); noUiSlider.create(sliders[i], { start: 0, connect: 'lower', step: 1, range: { 'min': [ 0 ], 'max': [ 3 ] }, pips: { mode: 'steps', density: 100 } }); sliders[i].noUiSlider.on('update', function(values, handle) { // ***** Problem line ***** document.getElementById(slider_names[i]+'-value').innerHTML = steps[parseInt(values[handle])]; // ***** Problem line ***** }); } ``` HTML: ``` <div id="slider-value"></div> <div id="slider"></div> <div id="slider2-value"></div> <div id="slider2"></div> (etc...) ``` The problem line is highlighted above ... when using a static value (ex, 'slider2-value') it works fine, but I can't seem to figure out how to target the appropriate id when the update event triggers ... slider\_names[i] obviously won't work there. I'm probably missing something obvious? Thanks!
2015/07/16
[ "https://Stackoverflow.com/questions/31463659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3884381/" ]
I've also stumbled into the same issue today, I've used the following code. Basically i'm just sending all the values of the sliders to this function which then pushes all the results into an array, then i can handle the array of data however i want to. Hopefully this can be of some use to you also. ``` var sliders = document.getElementsByClassName('sliders'); for ( var i = 0; i < sliders.length; i++ ) { noUiSlider.create(sliders[i], { start: 50, step: 5, connect: "lower", orientation: "horizontal", range: { 'min': 0, 'max': 100 }, }); sliders[i].noUiSlider.on('slide', addValues); } function addValues(){ var allValues = []; for (var i = 0; i < sliders.length; i++) { console.log(allValues.push(sliders[i].noUiSlider.get())); }; console.log(allValues); } ```
Here is a working model that will allow you to have multiple noUiSliders and slider values on the same page. Here is the html for 3 sliders. You can include as many as you like. ``` <div class="slider"></div> <div class="value">0</div> <div class="slider"></div> <div class="value">0</div> <div class="slider"></div> <div class="value">0</div> ``` Here is the javascript that will create the sliders and add the correct value to the corresponding slider when the slider is moved. ``` $(function () { var sliders = document.getElementsByClassName('slider'); var slideval = document.getElementsByClassName('value'); for (var i = 0; i < sliders.length; i++) { noUiSlider.create(sliders[i], { start: 0, connect: [true, false], range: { 'min': 0, '10%': 1, '20%': 2, '30%': 3, '40%': 4, '50%': 5, '60%': 6, '70%': 7, '80%': 8, '90%': 9, 'max': 10 }, snap: true, }); sliders[i].noUiSlider.on('slide', function () { var allValues = []; for (var i = 0; i < sliders.length; i++) { // store values in array to pass through ajax... allValues.push(sliders[i].noUiSlider.get()); // assign the slider value to the corresponding noUiSlider slideval[i].innerHTML = sliders[i].noUiSlider.get(); }; }); } }); ```
31,463,659
I'm using noUiSlider (<http://refreshless.com/nouislider/>) on a form which will have dozens of sliders on it. Rather than copy/pasting the code for each, I thought I could just set up an array of class names and a loop. That works; ie, it sets up working sliders. However the form also has to show the value of a slider upon update, and that's the part that I can't work out. I know how to do it with a static value but not in the loop ... Simplified example: JavaScript: ``` var steps = [ 'Never', 'Occasionally', 'Frequently', 'Constant' ]; // This array will have many more var slider_names = [ 'slider', 'slider2' ]; var sliders = []; for (var i = 0; i < slider_names.length; i++) { sliders.push(document.getElementById(slider_names[i])); noUiSlider.create(sliders[i], { start: 0, connect: 'lower', step: 1, range: { 'min': [ 0 ], 'max': [ 3 ] }, pips: { mode: 'steps', density: 100 } }); sliders[i].noUiSlider.on('update', function(values, handle) { // ***** Problem line ***** document.getElementById(slider_names[i]+'-value').innerHTML = steps[parseInt(values[handle])]; // ***** Problem line ***** }); } ``` HTML: ``` <div id="slider-value"></div> <div id="slider"></div> <div id="slider2-value"></div> <div id="slider2"></div> (etc...) ``` The problem line is highlighted above ... when using a static value (ex, 'slider2-value') it works fine, but I can't seem to figure out how to target the appropriate id when the update event triggers ... slider\_names[i] obviously won't work there. I'm probably missing something obvious? Thanks!
2015/07/16
[ "https://Stackoverflow.com/questions/31463659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3884381/" ]
I've also stumbled into the same issue today, I've used the following code. Basically i'm just sending all the values of the sliders to this function which then pushes all the results into an array, then i can handle the array of data however i want to. Hopefully this can be of some use to you also. ``` var sliders = document.getElementsByClassName('sliders'); for ( var i = 0; i < sliders.length; i++ ) { noUiSlider.create(sliders[i], { start: 50, step: 5, connect: "lower", orientation: "horizontal", range: { 'min': 0, 'max': 100 }, }); sliders[i].noUiSlider.on('slide', addValues); } function addValues(){ var allValues = []; for (var i = 0; i < sliders.length; i++) { console.log(allValues.push(sliders[i].noUiSlider.get())); }; console.log(allValues); } ```
This one works: ```js var sliders = document.getElementsByClassName('sliders'); for ( var i = 0; i < sliders.length; i++ ) { noUiSlider.create(sliders[i], { start: 10, step: 1, connect: "lower", orientation: "horizontal", range: { 'min': 0, 'max': 100 }, }); sliders[i].noUiSlider.on('slide', addValues); } function addValues(){ var allValues = []; for (var i = 0; i < sliders.length; i++) { allValues.push(sliders[i].noUiSlider.get()); }; for (var j = 0; j < allValues.length; j++) { document.getElementsByClassName('slider-value')[j].innerHTML = allValues[j]; } } ``` ```html <div class="slider-value"></div> <div class="sliders"></div> <div class="slider-value"></div> <div class="sliders"></div> <div class="slider-value"></div> <div class="sliders"></div> <div class="slider-value"></div> <div class="sliders"></div> ```
6,622,657
I'm new to jQuery (1.5 months) and I've found myself developing a PHP + jQuery habit that I don't particularly like. I'm wondering if anyone has suggestions to make things more elegant. Consider the following HTML that I've generated by performing a simple SQL query and echoed with PHP: ``` <div id='boat_1' class='boat speedboat'></div> <div id='boat_2' class='boat dory'></div> <div id='car_1' class='car racecar'></div> <div id='car_2' class='car racecar'></div> ``` As you can see, I've opted for an `id` naming convention that follows `{type}_{id}`. Now, in jQuery, Assume I want to bind a click handler to these *car* divs. Remembering that they are dynamic and there could be any number of them, I'd perform: ``` $(".car").bind('click', function(){ //do something }); ``` But typically, that `//do something` would like to know which car fired the click event. Furthermore, that `//do something` will probably need to seperate the type (boat or car) and the `id` to perform a POST operation and write back to the database...(for example) What I'm doing now to find the id (and other unique information as I need it) is simple, but to me, it smells: ``` $(".car").bind(function(){ var id = $(this).attr("id").replace("car_", ""); }); ``` One might suggest to use the class attribute instead because you don't have to worry about uniqueness. But because class names are not singular (there can be more than one per element as I've shown), I don't see this as a candidate solution. Because id's must be unique in the entire document, this is the solution I've settled for. I'm aware getElementById() would break if multiple ids of the same name were made possible but sometimes I wonder if it would be beneficial if ids didn't have to be unique provided they have different parents. How do you do it? Should I use HTML5's `data-*`? Thanks!
2011/07/08
[ "https://Stackoverflow.com/questions/6622657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568884/" ]
Yes. Render HTML like this: ``` <div data-id="1" class="boat speedboat"></div> <div data-id="2" class="boat dory"></div> <div data-id="1" class="car racecar"></div> <div data-id="2" class="car racecar"></div> ``` Jquery handler ``` $(".car").bind(function(){ var $this=$(this); var id = $this.data("id"); }); ``` [Jquery Data function](http://api.jquery.com/data/) > > As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification. > > >
What don't you like about your method? I'd look not to use `bind()` but to use `click()`. Also if you want, you can chain the classes and alter your `//do something` to instead split the id by \_ and return the final `[1]` item in the array? :) Your method seems fine to get the numeric id! :)
6,622,657
I'm new to jQuery (1.5 months) and I've found myself developing a PHP + jQuery habit that I don't particularly like. I'm wondering if anyone has suggestions to make things more elegant. Consider the following HTML that I've generated by performing a simple SQL query and echoed with PHP: ``` <div id='boat_1' class='boat speedboat'></div> <div id='boat_2' class='boat dory'></div> <div id='car_1' class='car racecar'></div> <div id='car_2' class='car racecar'></div> ``` As you can see, I've opted for an `id` naming convention that follows `{type}_{id}`. Now, in jQuery, Assume I want to bind a click handler to these *car* divs. Remembering that they are dynamic and there could be any number of them, I'd perform: ``` $(".car").bind('click', function(){ //do something }); ``` But typically, that `//do something` would like to know which car fired the click event. Furthermore, that `//do something` will probably need to seperate the type (boat or car) and the `id` to perform a POST operation and write back to the database...(for example) What I'm doing now to find the id (and other unique information as I need it) is simple, but to me, it smells: ``` $(".car").bind(function(){ var id = $(this).attr("id").replace("car_", ""); }); ``` One might suggest to use the class attribute instead because you don't have to worry about uniqueness. But because class names are not singular (there can be more than one per element as I've shown), I don't see this as a candidate solution. Because id's must be unique in the entire document, this is the solution I've settled for. I'm aware getElementById() would break if multiple ids of the same name were made possible but sometimes I wonder if it would be beneficial if ids didn't have to be unique provided they have different parents. How do you do it? Should I use HTML5's `data-*`? Thanks!
2011/07/08
[ "https://Stackoverflow.com/questions/6622657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568884/" ]
I think your method looks good for what you're doing, but I'll point out that in HTML 4 you can use the `rel` attribute, which is practically unused, but is valid HTML (so it won't trigger warnings like `data-*` will in HTML4 parsers). I use it, just like you proposed using the class attribute, but without the side-effect of munging my classes.
What don't you like about your method? I'd look not to use `bind()` but to use `click()`. Also if you want, you can chain the classes and alter your `//do something` to instead split the id by \_ and return the final `[1]` item in the array? :) Your method seems fine to get the numeric id! :)
6,622,657
I'm new to jQuery (1.5 months) and I've found myself developing a PHP + jQuery habit that I don't particularly like. I'm wondering if anyone has suggestions to make things more elegant. Consider the following HTML that I've generated by performing a simple SQL query and echoed with PHP: ``` <div id='boat_1' class='boat speedboat'></div> <div id='boat_2' class='boat dory'></div> <div id='car_1' class='car racecar'></div> <div id='car_2' class='car racecar'></div> ``` As you can see, I've opted for an `id` naming convention that follows `{type}_{id}`. Now, in jQuery, Assume I want to bind a click handler to these *car* divs. Remembering that they are dynamic and there could be any number of them, I'd perform: ``` $(".car").bind('click', function(){ //do something }); ``` But typically, that `//do something` would like to know which car fired the click event. Furthermore, that `//do something` will probably need to seperate the type (boat or car) and the `id` to perform a POST operation and write back to the database...(for example) What I'm doing now to find the id (and other unique information as I need it) is simple, but to me, it smells: ``` $(".car").bind(function(){ var id = $(this).attr("id").replace("car_", ""); }); ``` One might suggest to use the class attribute instead because you don't have to worry about uniqueness. But because class names are not singular (there can be more than one per element as I've shown), I don't see this as a candidate solution. Because id's must be unique in the entire document, this is the solution I've settled for. I'm aware getElementById() would break if multiple ids of the same name were made possible but sometimes I wonder if it would be beneficial if ids didn't have to be unique provided they have different parents. How do you do it? Should I use HTML5's `data-*`? Thanks!
2011/07/08
[ "https://Stackoverflow.com/questions/6622657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568884/" ]
Yes. Render HTML like this: ``` <div data-id="1" class="boat speedboat"></div> <div data-id="2" class="boat dory"></div> <div data-id="1" class="car racecar"></div> <div data-id="2" class="car racecar"></div> ``` Jquery handler ``` $(".car").bind(function(){ var $this=$(this); var id = $this.data("id"); }); ``` [Jquery Data function](http://api.jquery.com/data/) > > As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification. > > >
To be honest, that's what I'd do. I would however filter it the other way around and make it a function like [this guy correctly suggested](https://stackoverflow.com/questions/4460595/jquery-filter-numbers-of-a-string) and pull the number out of the string: ``` function pullNumber(n) { return n.replace(/[^0-9]/g, ''); } ```
6,622,657
I'm new to jQuery (1.5 months) and I've found myself developing a PHP + jQuery habit that I don't particularly like. I'm wondering if anyone has suggestions to make things more elegant. Consider the following HTML that I've generated by performing a simple SQL query and echoed with PHP: ``` <div id='boat_1' class='boat speedboat'></div> <div id='boat_2' class='boat dory'></div> <div id='car_1' class='car racecar'></div> <div id='car_2' class='car racecar'></div> ``` As you can see, I've opted for an `id` naming convention that follows `{type}_{id}`. Now, in jQuery, Assume I want to bind a click handler to these *car* divs. Remembering that they are dynamic and there could be any number of them, I'd perform: ``` $(".car").bind('click', function(){ //do something }); ``` But typically, that `//do something` would like to know which car fired the click event. Furthermore, that `//do something` will probably need to seperate the type (boat or car) and the `id` to perform a POST operation and write back to the database...(for example) What I'm doing now to find the id (and other unique information as I need it) is simple, but to me, it smells: ``` $(".car").bind(function(){ var id = $(this).attr("id").replace("car_", ""); }); ``` One might suggest to use the class attribute instead because you don't have to worry about uniqueness. But because class names are not singular (there can be more than one per element as I've shown), I don't see this as a candidate solution. Because id's must be unique in the entire document, this is the solution I've settled for. I'm aware getElementById() would break if multiple ids of the same name were made possible but sometimes I wonder if it would be beneficial if ids didn't have to be unique provided they have different parents. How do you do it? Should I use HTML5's `data-*`? Thanks!
2011/07/08
[ "https://Stackoverflow.com/questions/6622657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568884/" ]
I think your method looks good for what you're doing, but I'll point out that in HTML 4 you can use the `rel` attribute, which is practically unused, but is valid HTML (so it won't trigger warnings like `data-*` will in HTML4 parsers). I use it, just like you proposed using the class attribute, but without the side-effect of munging my classes.
To be honest, that's what I'd do. I would however filter it the other way around and make it a function like [this guy correctly suggested](https://stackoverflow.com/questions/4460595/jquery-filter-numbers-of-a-string) and pull the number out of the string: ``` function pullNumber(n) { return n.replace(/[^0-9]/g, ''); } ```
6,622,657
I'm new to jQuery (1.5 months) and I've found myself developing a PHP + jQuery habit that I don't particularly like. I'm wondering if anyone has suggestions to make things more elegant. Consider the following HTML that I've generated by performing a simple SQL query and echoed with PHP: ``` <div id='boat_1' class='boat speedboat'></div> <div id='boat_2' class='boat dory'></div> <div id='car_1' class='car racecar'></div> <div id='car_2' class='car racecar'></div> ``` As you can see, I've opted for an `id` naming convention that follows `{type}_{id}`. Now, in jQuery, Assume I want to bind a click handler to these *car* divs. Remembering that they are dynamic and there could be any number of them, I'd perform: ``` $(".car").bind('click', function(){ //do something }); ``` But typically, that `//do something` would like to know which car fired the click event. Furthermore, that `//do something` will probably need to seperate the type (boat or car) and the `id` to perform a POST operation and write back to the database...(for example) What I'm doing now to find the id (and other unique information as I need it) is simple, but to me, it smells: ``` $(".car").bind(function(){ var id = $(this).attr("id").replace("car_", ""); }); ``` One might suggest to use the class attribute instead because you don't have to worry about uniqueness. But because class names are not singular (there can be more than one per element as I've shown), I don't see this as a candidate solution. Because id's must be unique in the entire document, this is the solution I've settled for. I'm aware getElementById() would break if multiple ids of the same name were made possible but sometimes I wonder if it would be beneficial if ids didn't have to be unique provided they have different parents. How do you do it? Should I use HTML5's `data-*`? Thanks!
2011/07/08
[ "https://Stackoverflow.com/questions/6622657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568884/" ]
Yes. Render HTML like this: ``` <div data-id="1" class="boat speedboat"></div> <div data-id="2" class="boat dory"></div> <div data-id="1" class="car racecar"></div> <div data-id="2" class="car racecar"></div> ``` Jquery handler ``` $(".car").bind(function(){ var $this=$(this); var id = $this.data("id"); }); ``` [Jquery Data function](http://api.jquery.com/data/) > > As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification. > > >
I think your method looks good for what you're doing, but I'll point out that in HTML 4 you can use the `rel` attribute, which is practically unused, but is valid HTML (so it won't trigger warnings like `data-*` will in HTML4 parsers). I use it, just like you proposed using the class attribute, but without the side-effect of munging my classes.
39,632,402
I try to connect my android application using JSON Parser to the web hosting. But whenever I try to connect (even just open using url in the browser) I will get the error message. ``` <?php $dbHost = 'http://sql4.000webhost.com/localhost'; $dbUser = 'a6410240_cbetTD'; $dbPass = 'xxxxxx'; $dbName = 'a6410240_cbetTD'; $conn = mysql_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error()); mysql_select_db($dbName,$conn); ?> ``` This is my database.php file. The full error message is ``` Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on 'http' (4) in /home/a6410240/public_html/database.php on line 8. ``` I have tried change the $conn but still it didn't worked for me. Thanks
2016/09/22
[ "https://Stackoverflow.com/questions/39632402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4943727/" ]
If your database and application is on **same server** then use **"locahost"** in **$dbhost**. And if your database and application is on **different servers** then you need to use **IP address or hostname** in **$dbhost** and the **database user** should be added on database server provided with required privileges.
The problem you are having was already mentioned in one of the comments, [this one](https://stackoverflow.com/questions/39632402/mysql-connect-failed-cant-connect-to-mysql-server-on-http-4#comment66569515_39632402) to be precise. For your solution to work, all you need to do is omit the part `http://` at the beginning and probably `/localhost` at the end. The host is only the domain you are referring to. In this case `sql4.000webhost.com`. With /localhost you tried to already connect to a database, although your configured database is supposed to be `a6410240_cbetTD`.
39,632,402
I try to connect my android application using JSON Parser to the web hosting. But whenever I try to connect (even just open using url in the browser) I will get the error message. ``` <?php $dbHost = 'http://sql4.000webhost.com/localhost'; $dbUser = 'a6410240_cbetTD'; $dbPass = 'xxxxxx'; $dbName = 'a6410240_cbetTD'; $conn = mysql_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error()); mysql_select_db($dbName,$conn); ?> ``` This is my database.php file. The full error message is ``` Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on 'http' (4) in /home/a6410240/public_html/database.php on line 8. ``` I have tried change the $conn but still it didn't worked for me. Thanks
2016/09/22
[ "https://Stackoverflow.com/questions/39632402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4943727/" ]
If your database and application is on **same server** then use **"locahost"** in **$dbhost**. And if your database and application is on **different servers** then you need to use **IP address or hostname** in **$dbhost** and the **database user** should be added on database server provided with required privileges.
MySQL use TCP port 3306 by default ($dbport) and hostname or IP address ($dbhost). For LAMP (Linux-Apache-MySQL-php) you can find a lot of tutorials. Usually MySQL server listens internal port (which can't be reached via Internet) for security purposes. If you familiar with docker, you can simply download examples of LAMP solutions from hub.docker.com.
73,748,309
I want to scrape the bus schedule times from the following website <https://www.redbus.in/>. By putting the locations I am interested in the search fields I arrive at the following link which is an example of ones I am interested in: <https://www.redbus.in/bus-tickets/bhopal-to-indore?fromCityName=Bhopal&fromCityId=979&toCityName=Indore&toCityId=313&onward=18-Sep-2022&srcCountry=IND&destCountry=IND&opId=0&busType=Any> When I manually save this page and open the HTML file I can find the search results including Bus operator names, departure times, fare etc. But when I do the same using Python that part of the page is not saved. The code I am using is the following: ``` from selenium import webdriver from bs4 import BeautifulSoup url = "https://www.redbus.in/bus-tickets/bhopal-to-indore?fromCityName=Bhopal&fromCityId=979&toCityName=Indore&toCityId=313&onward=18-Sep-2022&srcCountry=IND&destCountry=IND&opId=0&busType=Any" browser = webdriver.Chrome() browser.get(url) soup = BeautifulSoup(browser.page_source) browser.quit() ``` `soup` object that is created this way has all the other content of the page in HTML format except the search results showing the bus route and time information. I am not sure why that is the case. I am new to web scrapping so any help here will be really appreciated.
2022/09/16
[ "https://Stackoverflow.com/questions/73748309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5456778/" ]
Main issue is that the data you expect needs a moment to be loaded and rendered by the browser - so simplest way is to give some `time.sleep()` or better [`selenium waits`](https://selenium-python.readthedocs.io/waits.html#explicit-waits) for second or two. ``` from selenium import webdriver from bs4 import BeautifulSoup import time url = "https://www.redbus.in/bus-tickets/bhopal-to-indore?fromCityName=Bhopal&fromCityId=979&toCityName=Indore&toCityId=313&onward=18-Sep-2022&srcCountry=IND&destCountry=IND&opId=0&busType=Any" browser = webdriver.Chrome() browser.get(url) time.sleep(2) soup = BeautifulSoup(browser.page_source) browser.quit() ``` --- But `selenium` is not necessarry, you can also access the [JSON](https://requests.readthedocs.io/en/latest/user/quickstart/#json-response-content) with all the data via [`requests`](https://requests.readthedocs.io/en/latest/user/quickstart/#json-response-content) and this is all well structured: ``` import requests import json url = "https://www.redbus.in/search/SearchResults?" headers = { 'content-type': 'application/json', 'origin': 'https://www.redbus.in', 'user-agent': 'Mozilla/5.0' } data={ 'fromCity':979, 'toCity':313, 'src':'Bhopal', 'dst':'Indore', 'DOJ':'20-Sep-2022', 'sectionId':0, 'groupId':0, 'limit':0, 'offset':0, 'sort':0, 'sortOrder':0, 'meta':'true', 'returnSearch':0} response = requests.request("POST", url, params=data, headers=headers) [e['bpData'] for e in response.json()['inv']] ``` #### Output ``` [[{'Id': 23400197, 'Name': 'ISBT Bhopal (Verma Travels)', 'Vbpname': 'ISBT Bhopal (Verma Travels)', 'BpTm': '07:00', 'bpTminmin': 420, 'eta': None, 'Address': 'ISBT Bhopal (Verma Travels)', 'BpFullTime': '2022-09-18 07:00:00'}, {'Id': 23400198, 'Name': 'Bhopal Railway Station (Verma Travels) (Pickup Van)', 'Vbpname': 'Bhopal Railway Station (Verma Travels) (Pickup Van)', 'BpTm': '07:00', 'bpTminmin': 420, 'eta': None, 'Address': 'Bhopal Railway Station (Verma Travels) (Pickup Van)', 'BpFullTime': '2022-09-18 07:00:00'}, {'Id': 23400196, 'Name': 'Lalghati (Verma Travels)', 'Vbpname': 'Lalghati (Verma Travels)', 'BpTm': '07:30', 'bpTminmin': 450, 'eta': None, 'Address': 'Lalghati (Verma Travels)', 'BpFullTime': '2022-09-18 07:30:00'}, {'Id': 23408191, 'Name': 'Sehore Bypass (Near Crescent Hotel)', 'Vbpname': 'Sehore Bypass (Near Crescent Hotel)', 'BpTm': '08:10', 'bpTminmin': 490, 'eta': None, 'Address': 'Sehore Bypass (Near Crescent Hotel)', 'BpFullTime': '2022-09-18 08:10:00'}], [{'Id': 23400197, 'Name': 'ISBT Bhopal (Verma Travels) (Pickup Van)', 'Vbpname': 'ISBT Bhopal (Verma Travels) (Pickup Van)', 'BpTm': '18:30', 'bpTminmin': 1110, 'eta': None, 'Address': 'ISBT Bhopal (Verma Travels) (Pickup Van)', 'BpFullTime': '2022-09-18 18:30:00'}, {'Id': 23400198, 'Name': 'Bhopal Railway Station (Verma Travels) (Pickup Van)', 'Vbpname': 'Bhopal Railway Station (Verma Travels) (Pickup Van)', 'BpTm': '18:30', 'bpTminmin': 1110, 'eta': None, 'Address': 'Bhopal Railway Station (Verma Travels) (Pickup Van)', 'BpFullTime': '2022-09-18 18:30:00'}, {'Id': 23400196, 'Name': 'Lalghati (Verma Travels)', 'Vbpname': 'Lalghati (Verma Travels)', 'BpTm': '19:00', 'bpTminmin': 1140, 'eta': None, 'Address': 'Lalghati (Verma Travels)', 'BpFullTime': '2022-09-18 19:00:00'}, {'Id': 23408191, 'Name': 'Sehore Bypass (Near Crescent Hotel)', 'Vbpname': 'Sehore Bypass (Near Crescent Hotel)', 'BpTm': '19:40', 'bpTminmin': 1180, 'eta': None, 'Address': 'Sehore Bypass (Near Crescent Hotel)', 'BpFullTime': '2022-09-18 19:40:00'}],...] ```
You don't need to use selenium or soup. Sometimes you can use only the 'requests' module and check if there is an api that sends you a response.(You can do this via network tab of your browser). For example the site you want to scrap, it seems that there is one api. So you take a look and understand how to their api works and you send a request exactly the same way and get the json response and then you parse it.
49,871,473
I am new to Javascripting and React JS coding. I have this JSON object- ``` var json1 = {"facilities":{"facility":[{"facilityCode":"J0LN","facilityId":"1","facilityName":"J0LN","npid":"1295718450","pid":"123457","providerState":"Alabama"},{"facilityCode":"K0NS","facilityId":"2","facilityName":"K0NS","npid":"9696969669","pid":"111111","providerState":"Alaska"},{"facilityCode":"J0LN1","facilityId":"3","facilityName":"J0LN1","npid":"111111111","pid":"221133","providerState":"Alabama"},{"facilityCode":"0987654321","facilityId":"4","facilityName":"0987654321","npid":"0987654321","pid":"235675","providerState":"Alabama"},{"facilityCode":"7776667676","facilityId":"5","facilityName":"7776667676","npid":"7776667676","pid":"236576","providerState":"Alabama"},{"facilityCode":"979797977","facilityId":"6","facilityName":"979797977","npid":"979797977","pid":"325347","providerState":"Alabama"},{"facilityCode":"9898989898","facilityId":"7","facilityName":"9898989898","npid":"9898989898","pid":"989898","providerState":"Alabama"},{"facilityCode":"121212","facilityId":"8","facilityName":"121212","npid":"1212120022","pid":"121212","providerState":"Connecticut"},{"facilityCode":"141414","facilityId":"9","facilityName":"141414","npid":"1414140022","pid":"141414","providerState":"Delaware"},{"facilityCode":"887766","facilityId":"10","facilityName":"887766","npid":"8877660022","pid":"887766","providerState":"Delaware"},{"facilityCode":"212121","facilityId":"11","facilityName":"OP-212121-OP","npid":"2121210022","pid":"212121","providerState":"Maryland"},{"facilityCode":"717171","facilityId":"12","facilityName":"IP-Qrtly-717171","npid":"7171710022","pid":"717174","providerState":"Alabama"},{"facilityCode":"RMC","facilityId":"13","facilityName":"RMC","npid":"1","pid":"676767","providerState":"Alabama"},{"facilityCode":"WCC","facilityId":"14","facilityName":"WCC","npid":"2","pid":"454676","providerState":"Alabama"},{"facilityCode":"FC","facilityId":"15","facilityName":"FN","npid":"1992813240","pid":"123456","providerState":"Alabama"},{"facilityCode":"VCC","facilityId":"16","facilityName":"VCC","npid":"1213121312","pid":"122312","providerState":"Alabama"},{"facilityCode":"AAAAA","facilityId":"17","facilityName":"AAAAA","npid":"3","pid":"112233","providerState":"Alabama"},{"facilityCode":"AAAAB","facilityId":"18","facilityName":"AAAAB","npid":"4","pid":"334455","providerState":"Alabama"},{"facilityCode":"AAAAC","facilityId":"19","facilityName":"AAAAC","npid":"5","pid":"556677","providerState":"Alabama"},{"facilityCode":"AAAAD","facilityId":"20","facilityName":"AAAAD","npid":"6","pid":"778899","providerState":"Alabama"},{"facilityCode":"AAAAE","facilityId":"21","facilityName":"AAAAE","npid":"7","pid":"616161","providerState":"Alabama"},{"facilityCode":"AAAAF","facilityId":"22","facilityName":"AAAAF","npid":"8","pid":"626262","providerState":"Alabama"},{"facilityCode":"AAAAG","facilityId":"23","facilityName":"AAAAG","npid":"9","pid":"717171","providerState":"Alabama"},{"facilityCode":"AAAAH","facilityId":"24","facilityName":"AAAAH","npid":"10","pid":"727272","providerState":"Alabama"},{"facilityCode":"AAAAI","facilityId":"25","facilityName":"AAAAI","npid":"11","pid":"757575","providerState":"Alabama"},{"facilityCode":"AAAAJ","facilityId":"26","facilityName":"AAAAJ","npid":"12","pid":"767676","providerState":"Alabama"},{"facilityCode":"AAAAK","facilityId":"27","facilityName":"AAAAK","npid":"13","pid":"818181","providerState":"Alabama"},{"facilityCode":"AAAAL","facilityId":"28","facilityName":"AAAAL","npid":"14","pid":"828282","providerState":"Alabama"},{"facilityCode":"AAAAM","facilityId":"29","facilityName":"AAAAM","npid":"15","pid":"858585","providerState":"Alabama"},{"facilityCode":"AAAAN","facilityId":"30","facilityName":"AAAAN","npid":"16","pid":"868686","providerState":"Alabama"},{"facilityCode":"AAAAO","facilityId":"31","facilityName":"AAAAO","npid":"17","pid":"919191","providerState":"Alabama"},{"facilityCode":"AAAAP","facilityId":"32","facilityName":"AAAAP","npid":"18","pid":"929292","providerState":"Alabama"},{"facilityCode":"AAAAQ","facilityId":"33","facilityName":"AAAAQ","npid":"19","pid":"959595","providerState":"Alabama"},{"facilityCode":"AAAAR","facilityId":"34","facilityName":"AAAAR","npid":"20","pid":"969696","providerState":"Alabama"},{"facilityCode":"UNIQUE","facilityId":"35","facilityName":"UNIQUE","npid":"21","pid":"123456","providerState":"Alabama"}]}}; ``` I am setting the state of my data here and binding it (not sure why I am doing this, but I see everyone doing it as part of their ajax calls) ``` var stateSet = function(data) { this.setState({data: json1}); }; stateSet.bind(this); // attempt to mock an AJAX call here, by assuming we have already obtained the JSON object. return( <table> <tbody> <tr> <th>Facility Code</th> <th>Facility ID</th> <th>Facility Name</th> <th>NPID</th> <th>PID</th> <th>Provider State</th> </tr> { this.state.data.map(function(facility, key) { // I'm not sure if the control is entering this function, and I don't understand why return ( <tr> <td>{facility.facilityCode}</td> <td>{facility.facilityId}</td> <td>{facility.facilityName}</td> <td>{facility.npid}</td> <td>{facility.pid}</td> <td>{facility.providerState}</td> </tr> ); }) } </tbody> </table> ); ``` As I've mentioned in the code as part of the comment, I don't think the control is entering `this.state.data.map(function(facility, key) {` function and I don't understand why.
2018/04/17
[ "https://Stackoverflow.com/questions/49871473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649068/" ]
You path to array in incorrect, also add a check on availability of `this.state.data` so that it doesn't fail if `data` is not available, ``` {this.state.data && this.state.data.facilities.facility.map(function(facility, key) {}} ```
You re are use a map function on an object that has only on prop, this is not possible. The only prop the json object has is facilities
49,871,473
I am new to Javascripting and React JS coding. I have this JSON object- ``` var json1 = {"facilities":{"facility":[{"facilityCode":"J0LN","facilityId":"1","facilityName":"J0LN","npid":"1295718450","pid":"123457","providerState":"Alabama"},{"facilityCode":"K0NS","facilityId":"2","facilityName":"K0NS","npid":"9696969669","pid":"111111","providerState":"Alaska"},{"facilityCode":"J0LN1","facilityId":"3","facilityName":"J0LN1","npid":"111111111","pid":"221133","providerState":"Alabama"},{"facilityCode":"0987654321","facilityId":"4","facilityName":"0987654321","npid":"0987654321","pid":"235675","providerState":"Alabama"},{"facilityCode":"7776667676","facilityId":"5","facilityName":"7776667676","npid":"7776667676","pid":"236576","providerState":"Alabama"},{"facilityCode":"979797977","facilityId":"6","facilityName":"979797977","npid":"979797977","pid":"325347","providerState":"Alabama"},{"facilityCode":"9898989898","facilityId":"7","facilityName":"9898989898","npid":"9898989898","pid":"989898","providerState":"Alabama"},{"facilityCode":"121212","facilityId":"8","facilityName":"121212","npid":"1212120022","pid":"121212","providerState":"Connecticut"},{"facilityCode":"141414","facilityId":"9","facilityName":"141414","npid":"1414140022","pid":"141414","providerState":"Delaware"},{"facilityCode":"887766","facilityId":"10","facilityName":"887766","npid":"8877660022","pid":"887766","providerState":"Delaware"},{"facilityCode":"212121","facilityId":"11","facilityName":"OP-212121-OP","npid":"2121210022","pid":"212121","providerState":"Maryland"},{"facilityCode":"717171","facilityId":"12","facilityName":"IP-Qrtly-717171","npid":"7171710022","pid":"717174","providerState":"Alabama"},{"facilityCode":"RMC","facilityId":"13","facilityName":"RMC","npid":"1","pid":"676767","providerState":"Alabama"},{"facilityCode":"WCC","facilityId":"14","facilityName":"WCC","npid":"2","pid":"454676","providerState":"Alabama"},{"facilityCode":"FC","facilityId":"15","facilityName":"FN","npid":"1992813240","pid":"123456","providerState":"Alabama"},{"facilityCode":"VCC","facilityId":"16","facilityName":"VCC","npid":"1213121312","pid":"122312","providerState":"Alabama"},{"facilityCode":"AAAAA","facilityId":"17","facilityName":"AAAAA","npid":"3","pid":"112233","providerState":"Alabama"},{"facilityCode":"AAAAB","facilityId":"18","facilityName":"AAAAB","npid":"4","pid":"334455","providerState":"Alabama"},{"facilityCode":"AAAAC","facilityId":"19","facilityName":"AAAAC","npid":"5","pid":"556677","providerState":"Alabama"},{"facilityCode":"AAAAD","facilityId":"20","facilityName":"AAAAD","npid":"6","pid":"778899","providerState":"Alabama"},{"facilityCode":"AAAAE","facilityId":"21","facilityName":"AAAAE","npid":"7","pid":"616161","providerState":"Alabama"},{"facilityCode":"AAAAF","facilityId":"22","facilityName":"AAAAF","npid":"8","pid":"626262","providerState":"Alabama"},{"facilityCode":"AAAAG","facilityId":"23","facilityName":"AAAAG","npid":"9","pid":"717171","providerState":"Alabama"},{"facilityCode":"AAAAH","facilityId":"24","facilityName":"AAAAH","npid":"10","pid":"727272","providerState":"Alabama"},{"facilityCode":"AAAAI","facilityId":"25","facilityName":"AAAAI","npid":"11","pid":"757575","providerState":"Alabama"},{"facilityCode":"AAAAJ","facilityId":"26","facilityName":"AAAAJ","npid":"12","pid":"767676","providerState":"Alabama"},{"facilityCode":"AAAAK","facilityId":"27","facilityName":"AAAAK","npid":"13","pid":"818181","providerState":"Alabama"},{"facilityCode":"AAAAL","facilityId":"28","facilityName":"AAAAL","npid":"14","pid":"828282","providerState":"Alabama"},{"facilityCode":"AAAAM","facilityId":"29","facilityName":"AAAAM","npid":"15","pid":"858585","providerState":"Alabama"},{"facilityCode":"AAAAN","facilityId":"30","facilityName":"AAAAN","npid":"16","pid":"868686","providerState":"Alabama"},{"facilityCode":"AAAAO","facilityId":"31","facilityName":"AAAAO","npid":"17","pid":"919191","providerState":"Alabama"},{"facilityCode":"AAAAP","facilityId":"32","facilityName":"AAAAP","npid":"18","pid":"929292","providerState":"Alabama"},{"facilityCode":"AAAAQ","facilityId":"33","facilityName":"AAAAQ","npid":"19","pid":"959595","providerState":"Alabama"},{"facilityCode":"AAAAR","facilityId":"34","facilityName":"AAAAR","npid":"20","pid":"969696","providerState":"Alabama"},{"facilityCode":"UNIQUE","facilityId":"35","facilityName":"UNIQUE","npid":"21","pid":"123456","providerState":"Alabama"}]}}; ``` I am setting the state of my data here and binding it (not sure why I am doing this, but I see everyone doing it as part of their ajax calls) ``` var stateSet = function(data) { this.setState({data: json1}); }; stateSet.bind(this); // attempt to mock an AJAX call here, by assuming we have already obtained the JSON object. return( <table> <tbody> <tr> <th>Facility Code</th> <th>Facility ID</th> <th>Facility Name</th> <th>NPID</th> <th>PID</th> <th>Provider State</th> </tr> { this.state.data.map(function(facility, key) { // I'm not sure if the control is entering this function, and I don't understand why return ( <tr> <td>{facility.facilityCode}</td> <td>{facility.facilityId}</td> <td>{facility.facilityName}</td> <td>{facility.npid}</td> <td>{facility.pid}</td> <td>{facility.providerState}</td> </tr> ); }) } </tbody> </table> ); ``` As I've mentioned in the code as part of the comment, I don't think the control is entering `this.state.data.map(function(facility, key) {` function and I don't understand why.
2018/04/17
[ "https://Stackoverflow.com/questions/49871473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649068/" ]
You path to array in incorrect, also add a check on availability of `this.state.data` so that it doesn't fail if `data` is not available, ``` {this.state.data && this.state.data.facilities.facility.map(function(facility, key) {}} ```
``` var stateSet = function(data) { this.setState({data: json1}); }; ``` why are you using function(date), this is not needed. Just give function(), because i think the stateSet is firstly not called anywhere so it doesn t get triggerd and you re expecting a prop in that function.
49,871,473
I am new to Javascripting and React JS coding. I have this JSON object- ``` var json1 = {"facilities":{"facility":[{"facilityCode":"J0LN","facilityId":"1","facilityName":"J0LN","npid":"1295718450","pid":"123457","providerState":"Alabama"},{"facilityCode":"K0NS","facilityId":"2","facilityName":"K0NS","npid":"9696969669","pid":"111111","providerState":"Alaska"},{"facilityCode":"J0LN1","facilityId":"3","facilityName":"J0LN1","npid":"111111111","pid":"221133","providerState":"Alabama"},{"facilityCode":"0987654321","facilityId":"4","facilityName":"0987654321","npid":"0987654321","pid":"235675","providerState":"Alabama"},{"facilityCode":"7776667676","facilityId":"5","facilityName":"7776667676","npid":"7776667676","pid":"236576","providerState":"Alabama"},{"facilityCode":"979797977","facilityId":"6","facilityName":"979797977","npid":"979797977","pid":"325347","providerState":"Alabama"},{"facilityCode":"9898989898","facilityId":"7","facilityName":"9898989898","npid":"9898989898","pid":"989898","providerState":"Alabama"},{"facilityCode":"121212","facilityId":"8","facilityName":"121212","npid":"1212120022","pid":"121212","providerState":"Connecticut"},{"facilityCode":"141414","facilityId":"9","facilityName":"141414","npid":"1414140022","pid":"141414","providerState":"Delaware"},{"facilityCode":"887766","facilityId":"10","facilityName":"887766","npid":"8877660022","pid":"887766","providerState":"Delaware"},{"facilityCode":"212121","facilityId":"11","facilityName":"OP-212121-OP","npid":"2121210022","pid":"212121","providerState":"Maryland"},{"facilityCode":"717171","facilityId":"12","facilityName":"IP-Qrtly-717171","npid":"7171710022","pid":"717174","providerState":"Alabama"},{"facilityCode":"RMC","facilityId":"13","facilityName":"RMC","npid":"1","pid":"676767","providerState":"Alabama"},{"facilityCode":"WCC","facilityId":"14","facilityName":"WCC","npid":"2","pid":"454676","providerState":"Alabama"},{"facilityCode":"FC","facilityId":"15","facilityName":"FN","npid":"1992813240","pid":"123456","providerState":"Alabama"},{"facilityCode":"VCC","facilityId":"16","facilityName":"VCC","npid":"1213121312","pid":"122312","providerState":"Alabama"},{"facilityCode":"AAAAA","facilityId":"17","facilityName":"AAAAA","npid":"3","pid":"112233","providerState":"Alabama"},{"facilityCode":"AAAAB","facilityId":"18","facilityName":"AAAAB","npid":"4","pid":"334455","providerState":"Alabama"},{"facilityCode":"AAAAC","facilityId":"19","facilityName":"AAAAC","npid":"5","pid":"556677","providerState":"Alabama"},{"facilityCode":"AAAAD","facilityId":"20","facilityName":"AAAAD","npid":"6","pid":"778899","providerState":"Alabama"},{"facilityCode":"AAAAE","facilityId":"21","facilityName":"AAAAE","npid":"7","pid":"616161","providerState":"Alabama"},{"facilityCode":"AAAAF","facilityId":"22","facilityName":"AAAAF","npid":"8","pid":"626262","providerState":"Alabama"},{"facilityCode":"AAAAG","facilityId":"23","facilityName":"AAAAG","npid":"9","pid":"717171","providerState":"Alabama"},{"facilityCode":"AAAAH","facilityId":"24","facilityName":"AAAAH","npid":"10","pid":"727272","providerState":"Alabama"},{"facilityCode":"AAAAI","facilityId":"25","facilityName":"AAAAI","npid":"11","pid":"757575","providerState":"Alabama"},{"facilityCode":"AAAAJ","facilityId":"26","facilityName":"AAAAJ","npid":"12","pid":"767676","providerState":"Alabama"},{"facilityCode":"AAAAK","facilityId":"27","facilityName":"AAAAK","npid":"13","pid":"818181","providerState":"Alabama"},{"facilityCode":"AAAAL","facilityId":"28","facilityName":"AAAAL","npid":"14","pid":"828282","providerState":"Alabama"},{"facilityCode":"AAAAM","facilityId":"29","facilityName":"AAAAM","npid":"15","pid":"858585","providerState":"Alabama"},{"facilityCode":"AAAAN","facilityId":"30","facilityName":"AAAAN","npid":"16","pid":"868686","providerState":"Alabama"},{"facilityCode":"AAAAO","facilityId":"31","facilityName":"AAAAO","npid":"17","pid":"919191","providerState":"Alabama"},{"facilityCode":"AAAAP","facilityId":"32","facilityName":"AAAAP","npid":"18","pid":"929292","providerState":"Alabama"},{"facilityCode":"AAAAQ","facilityId":"33","facilityName":"AAAAQ","npid":"19","pid":"959595","providerState":"Alabama"},{"facilityCode":"AAAAR","facilityId":"34","facilityName":"AAAAR","npid":"20","pid":"969696","providerState":"Alabama"},{"facilityCode":"UNIQUE","facilityId":"35","facilityName":"UNIQUE","npid":"21","pid":"123456","providerState":"Alabama"}]}}; ``` I am setting the state of my data here and binding it (not sure why I am doing this, but I see everyone doing it as part of their ajax calls) ``` var stateSet = function(data) { this.setState({data: json1}); }; stateSet.bind(this); // attempt to mock an AJAX call here, by assuming we have already obtained the JSON object. return( <table> <tbody> <tr> <th>Facility Code</th> <th>Facility ID</th> <th>Facility Name</th> <th>NPID</th> <th>PID</th> <th>Provider State</th> </tr> { this.state.data.map(function(facility, key) { // I'm not sure if the control is entering this function, and I don't understand why return ( <tr> <td>{facility.facilityCode}</td> <td>{facility.facilityId}</td> <td>{facility.facilityName}</td> <td>{facility.npid}</td> <td>{facility.pid}</td> <td>{facility.providerState}</td> </tr> ); }) } </tbody> </table> ); ``` As I've mentioned in the code as part of the comment, I don't think the control is entering `this.state.data.map(function(facility, key) {` function and I don't understand why.
2018/04/17
[ "https://Stackoverflow.com/questions/49871473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649068/" ]
You're not targeting the `facility` array correctly. It should be `this.state.data.facilities.facility.map`, and you may also set your `json1` to `state` in your `constructor` directly like so ``` constructor() { super(); var json1 = { facilities: { facility: [ { facilityCode: "J0LN", facilityId: "1", facilityName: "J0LN", npid: "1295718450", pid: "123457", providerState: "Alabama" } .... ] } }; this.state = { data: json1 }; } ``` [Working Snippet](https://codesandbox.io/s/p13z652mx)
You path to array in incorrect, also add a check on availability of `this.state.data` so that it doesn't fail if `data` is not available, ``` {this.state.data && this.state.data.facilities.facility.map(function(facility, key) {}} ```
49,871,473
I am new to Javascripting and React JS coding. I have this JSON object- ``` var json1 = {"facilities":{"facility":[{"facilityCode":"J0LN","facilityId":"1","facilityName":"J0LN","npid":"1295718450","pid":"123457","providerState":"Alabama"},{"facilityCode":"K0NS","facilityId":"2","facilityName":"K0NS","npid":"9696969669","pid":"111111","providerState":"Alaska"},{"facilityCode":"J0LN1","facilityId":"3","facilityName":"J0LN1","npid":"111111111","pid":"221133","providerState":"Alabama"},{"facilityCode":"0987654321","facilityId":"4","facilityName":"0987654321","npid":"0987654321","pid":"235675","providerState":"Alabama"},{"facilityCode":"7776667676","facilityId":"5","facilityName":"7776667676","npid":"7776667676","pid":"236576","providerState":"Alabama"},{"facilityCode":"979797977","facilityId":"6","facilityName":"979797977","npid":"979797977","pid":"325347","providerState":"Alabama"},{"facilityCode":"9898989898","facilityId":"7","facilityName":"9898989898","npid":"9898989898","pid":"989898","providerState":"Alabama"},{"facilityCode":"121212","facilityId":"8","facilityName":"121212","npid":"1212120022","pid":"121212","providerState":"Connecticut"},{"facilityCode":"141414","facilityId":"9","facilityName":"141414","npid":"1414140022","pid":"141414","providerState":"Delaware"},{"facilityCode":"887766","facilityId":"10","facilityName":"887766","npid":"8877660022","pid":"887766","providerState":"Delaware"},{"facilityCode":"212121","facilityId":"11","facilityName":"OP-212121-OP","npid":"2121210022","pid":"212121","providerState":"Maryland"},{"facilityCode":"717171","facilityId":"12","facilityName":"IP-Qrtly-717171","npid":"7171710022","pid":"717174","providerState":"Alabama"},{"facilityCode":"RMC","facilityId":"13","facilityName":"RMC","npid":"1","pid":"676767","providerState":"Alabama"},{"facilityCode":"WCC","facilityId":"14","facilityName":"WCC","npid":"2","pid":"454676","providerState":"Alabama"},{"facilityCode":"FC","facilityId":"15","facilityName":"FN","npid":"1992813240","pid":"123456","providerState":"Alabama"},{"facilityCode":"VCC","facilityId":"16","facilityName":"VCC","npid":"1213121312","pid":"122312","providerState":"Alabama"},{"facilityCode":"AAAAA","facilityId":"17","facilityName":"AAAAA","npid":"3","pid":"112233","providerState":"Alabama"},{"facilityCode":"AAAAB","facilityId":"18","facilityName":"AAAAB","npid":"4","pid":"334455","providerState":"Alabama"},{"facilityCode":"AAAAC","facilityId":"19","facilityName":"AAAAC","npid":"5","pid":"556677","providerState":"Alabama"},{"facilityCode":"AAAAD","facilityId":"20","facilityName":"AAAAD","npid":"6","pid":"778899","providerState":"Alabama"},{"facilityCode":"AAAAE","facilityId":"21","facilityName":"AAAAE","npid":"7","pid":"616161","providerState":"Alabama"},{"facilityCode":"AAAAF","facilityId":"22","facilityName":"AAAAF","npid":"8","pid":"626262","providerState":"Alabama"},{"facilityCode":"AAAAG","facilityId":"23","facilityName":"AAAAG","npid":"9","pid":"717171","providerState":"Alabama"},{"facilityCode":"AAAAH","facilityId":"24","facilityName":"AAAAH","npid":"10","pid":"727272","providerState":"Alabama"},{"facilityCode":"AAAAI","facilityId":"25","facilityName":"AAAAI","npid":"11","pid":"757575","providerState":"Alabama"},{"facilityCode":"AAAAJ","facilityId":"26","facilityName":"AAAAJ","npid":"12","pid":"767676","providerState":"Alabama"},{"facilityCode":"AAAAK","facilityId":"27","facilityName":"AAAAK","npid":"13","pid":"818181","providerState":"Alabama"},{"facilityCode":"AAAAL","facilityId":"28","facilityName":"AAAAL","npid":"14","pid":"828282","providerState":"Alabama"},{"facilityCode":"AAAAM","facilityId":"29","facilityName":"AAAAM","npid":"15","pid":"858585","providerState":"Alabama"},{"facilityCode":"AAAAN","facilityId":"30","facilityName":"AAAAN","npid":"16","pid":"868686","providerState":"Alabama"},{"facilityCode":"AAAAO","facilityId":"31","facilityName":"AAAAO","npid":"17","pid":"919191","providerState":"Alabama"},{"facilityCode":"AAAAP","facilityId":"32","facilityName":"AAAAP","npid":"18","pid":"929292","providerState":"Alabama"},{"facilityCode":"AAAAQ","facilityId":"33","facilityName":"AAAAQ","npid":"19","pid":"959595","providerState":"Alabama"},{"facilityCode":"AAAAR","facilityId":"34","facilityName":"AAAAR","npid":"20","pid":"969696","providerState":"Alabama"},{"facilityCode":"UNIQUE","facilityId":"35","facilityName":"UNIQUE","npid":"21","pid":"123456","providerState":"Alabama"}]}}; ``` I am setting the state of my data here and binding it (not sure why I am doing this, but I see everyone doing it as part of their ajax calls) ``` var stateSet = function(data) { this.setState({data: json1}); }; stateSet.bind(this); // attempt to mock an AJAX call here, by assuming we have already obtained the JSON object. return( <table> <tbody> <tr> <th>Facility Code</th> <th>Facility ID</th> <th>Facility Name</th> <th>NPID</th> <th>PID</th> <th>Provider State</th> </tr> { this.state.data.map(function(facility, key) { // I'm not sure if the control is entering this function, and I don't understand why return ( <tr> <td>{facility.facilityCode}</td> <td>{facility.facilityId}</td> <td>{facility.facilityName}</td> <td>{facility.npid}</td> <td>{facility.pid}</td> <td>{facility.providerState}</td> </tr> ); }) } </tbody> </table> ); ``` As I've mentioned in the code as part of the comment, I don't think the control is entering `this.state.data.map(function(facility, key) {` function and I don't understand why.
2018/04/17
[ "https://Stackoverflow.com/questions/49871473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649068/" ]
You path to array in incorrect, also add a check on availability of `this.state.data` so that it doesn't fail if `data` is not available, ``` {this.state.data && this.state.data.facilities.facility.map(function(facility, key) {}} ```
From your question, it is clear that you are trying to access the **facility** array inside the facilities object. You can achieve this as: `this.state.data.facilities.facility.map((elementOffFacilityArray,index) => { // do whatever you would like to do with individual elements of the array. })` But at the time when this map function will execute, it might be the case that this facility array may be empty which will result in error whic already has been pointed out by @nrgwsth. Thus, you will have to keep the check and the above expression for this case will become as : ``` { this.state.data && this.state.data.facilities && this.state.data.facilities.facility ? this.state.data.facilities.facility.map((elementOffFacilityArray,index) => { // do whatever you would like to do with individual elements of the array. }) : '' } ```
49,871,473
I am new to Javascripting and React JS coding. I have this JSON object- ``` var json1 = {"facilities":{"facility":[{"facilityCode":"J0LN","facilityId":"1","facilityName":"J0LN","npid":"1295718450","pid":"123457","providerState":"Alabama"},{"facilityCode":"K0NS","facilityId":"2","facilityName":"K0NS","npid":"9696969669","pid":"111111","providerState":"Alaska"},{"facilityCode":"J0LN1","facilityId":"3","facilityName":"J0LN1","npid":"111111111","pid":"221133","providerState":"Alabama"},{"facilityCode":"0987654321","facilityId":"4","facilityName":"0987654321","npid":"0987654321","pid":"235675","providerState":"Alabama"},{"facilityCode":"7776667676","facilityId":"5","facilityName":"7776667676","npid":"7776667676","pid":"236576","providerState":"Alabama"},{"facilityCode":"979797977","facilityId":"6","facilityName":"979797977","npid":"979797977","pid":"325347","providerState":"Alabama"},{"facilityCode":"9898989898","facilityId":"7","facilityName":"9898989898","npid":"9898989898","pid":"989898","providerState":"Alabama"},{"facilityCode":"121212","facilityId":"8","facilityName":"121212","npid":"1212120022","pid":"121212","providerState":"Connecticut"},{"facilityCode":"141414","facilityId":"9","facilityName":"141414","npid":"1414140022","pid":"141414","providerState":"Delaware"},{"facilityCode":"887766","facilityId":"10","facilityName":"887766","npid":"8877660022","pid":"887766","providerState":"Delaware"},{"facilityCode":"212121","facilityId":"11","facilityName":"OP-212121-OP","npid":"2121210022","pid":"212121","providerState":"Maryland"},{"facilityCode":"717171","facilityId":"12","facilityName":"IP-Qrtly-717171","npid":"7171710022","pid":"717174","providerState":"Alabama"},{"facilityCode":"RMC","facilityId":"13","facilityName":"RMC","npid":"1","pid":"676767","providerState":"Alabama"},{"facilityCode":"WCC","facilityId":"14","facilityName":"WCC","npid":"2","pid":"454676","providerState":"Alabama"},{"facilityCode":"FC","facilityId":"15","facilityName":"FN","npid":"1992813240","pid":"123456","providerState":"Alabama"},{"facilityCode":"VCC","facilityId":"16","facilityName":"VCC","npid":"1213121312","pid":"122312","providerState":"Alabama"},{"facilityCode":"AAAAA","facilityId":"17","facilityName":"AAAAA","npid":"3","pid":"112233","providerState":"Alabama"},{"facilityCode":"AAAAB","facilityId":"18","facilityName":"AAAAB","npid":"4","pid":"334455","providerState":"Alabama"},{"facilityCode":"AAAAC","facilityId":"19","facilityName":"AAAAC","npid":"5","pid":"556677","providerState":"Alabama"},{"facilityCode":"AAAAD","facilityId":"20","facilityName":"AAAAD","npid":"6","pid":"778899","providerState":"Alabama"},{"facilityCode":"AAAAE","facilityId":"21","facilityName":"AAAAE","npid":"7","pid":"616161","providerState":"Alabama"},{"facilityCode":"AAAAF","facilityId":"22","facilityName":"AAAAF","npid":"8","pid":"626262","providerState":"Alabama"},{"facilityCode":"AAAAG","facilityId":"23","facilityName":"AAAAG","npid":"9","pid":"717171","providerState":"Alabama"},{"facilityCode":"AAAAH","facilityId":"24","facilityName":"AAAAH","npid":"10","pid":"727272","providerState":"Alabama"},{"facilityCode":"AAAAI","facilityId":"25","facilityName":"AAAAI","npid":"11","pid":"757575","providerState":"Alabama"},{"facilityCode":"AAAAJ","facilityId":"26","facilityName":"AAAAJ","npid":"12","pid":"767676","providerState":"Alabama"},{"facilityCode":"AAAAK","facilityId":"27","facilityName":"AAAAK","npid":"13","pid":"818181","providerState":"Alabama"},{"facilityCode":"AAAAL","facilityId":"28","facilityName":"AAAAL","npid":"14","pid":"828282","providerState":"Alabama"},{"facilityCode":"AAAAM","facilityId":"29","facilityName":"AAAAM","npid":"15","pid":"858585","providerState":"Alabama"},{"facilityCode":"AAAAN","facilityId":"30","facilityName":"AAAAN","npid":"16","pid":"868686","providerState":"Alabama"},{"facilityCode":"AAAAO","facilityId":"31","facilityName":"AAAAO","npid":"17","pid":"919191","providerState":"Alabama"},{"facilityCode":"AAAAP","facilityId":"32","facilityName":"AAAAP","npid":"18","pid":"929292","providerState":"Alabama"},{"facilityCode":"AAAAQ","facilityId":"33","facilityName":"AAAAQ","npid":"19","pid":"959595","providerState":"Alabama"},{"facilityCode":"AAAAR","facilityId":"34","facilityName":"AAAAR","npid":"20","pid":"969696","providerState":"Alabama"},{"facilityCode":"UNIQUE","facilityId":"35","facilityName":"UNIQUE","npid":"21","pid":"123456","providerState":"Alabama"}]}}; ``` I am setting the state of my data here and binding it (not sure why I am doing this, but I see everyone doing it as part of their ajax calls) ``` var stateSet = function(data) { this.setState({data: json1}); }; stateSet.bind(this); // attempt to mock an AJAX call here, by assuming we have already obtained the JSON object. return( <table> <tbody> <tr> <th>Facility Code</th> <th>Facility ID</th> <th>Facility Name</th> <th>NPID</th> <th>PID</th> <th>Provider State</th> </tr> { this.state.data.map(function(facility, key) { // I'm not sure if the control is entering this function, and I don't understand why return ( <tr> <td>{facility.facilityCode}</td> <td>{facility.facilityId}</td> <td>{facility.facilityName}</td> <td>{facility.npid}</td> <td>{facility.pid}</td> <td>{facility.providerState}</td> </tr> ); }) } </tbody> </table> ); ``` As I've mentioned in the code as part of the comment, I don't think the control is entering `this.state.data.map(function(facility, key) {` function and I don't understand why.
2018/04/17
[ "https://Stackoverflow.com/questions/49871473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649068/" ]
You're not targeting the `facility` array correctly. It should be `this.state.data.facilities.facility.map`, and you may also set your `json1` to `state` in your `constructor` directly like so ``` constructor() { super(); var json1 = { facilities: { facility: [ { facilityCode: "J0LN", facilityId: "1", facilityName: "J0LN", npid: "1295718450", pid: "123457", providerState: "Alabama" } .... ] } }; this.state = { data: json1 }; } ``` [Working Snippet](https://codesandbox.io/s/p13z652mx)
You re are use a map function on an object that has only on prop, this is not possible. The only prop the json object has is facilities
49,871,473
I am new to Javascripting and React JS coding. I have this JSON object- ``` var json1 = {"facilities":{"facility":[{"facilityCode":"J0LN","facilityId":"1","facilityName":"J0LN","npid":"1295718450","pid":"123457","providerState":"Alabama"},{"facilityCode":"K0NS","facilityId":"2","facilityName":"K0NS","npid":"9696969669","pid":"111111","providerState":"Alaska"},{"facilityCode":"J0LN1","facilityId":"3","facilityName":"J0LN1","npid":"111111111","pid":"221133","providerState":"Alabama"},{"facilityCode":"0987654321","facilityId":"4","facilityName":"0987654321","npid":"0987654321","pid":"235675","providerState":"Alabama"},{"facilityCode":"7776667676","facilityId":"5","facilityName":"7776667676","npid":"7776667676","pid":"236576","providerState":"Alabama"},{"facilityCode":"979797977","facilityId":"6","facilityName":"979797977","npid":"979797977","pid":"325347","providerState":"Alabama"},{"facilityCode":"9898989898","facilityId":"7","facilityName":"9898989898","npid":"9898989898","pid":"989898","providerState":"Alabama"},{"facilityCode":"121212","facilityId":"8","facilityName":"121212","npid":"1212120022","pid":"121212","providerState":"Connecticut"},{"facilityCode":"141414","facilityId":"9","facilityName":"141414","npid":"1414140022","pid":"141414","providerState":"Delaware"},{"facilityCode":"887766","facilityId":"10","facilityName":"887766","npid":"8877660022","pid":"887766","providerState":"Delaware"},{"facilityCode":"212121","facilityId":"11","facilityName":"OP-212121-OP","npid":"2121210022","pid":"212121","providerState":"Maryland"},{"facilityCode":"717171","facilityId":"12","facilityName":"IP-Qrtly-717171","npid":"7171710022","pid":"717174","providerState":"Alabama"},{"facilityCode":"RMC","facilityId":"13","facilityName":"RMC","npid":"1","pid":"676767","providerState":"Alabama"},{"facilityCode":"WCC","facilityId":"14","facilityName":"WCC","npid":"2","pid":"454676","providerState":"Alabama"},{"facilityCode":"FC","facilityId":"15","facilityName":"FN","npid":"1992813240","pid":"123456","providerState":"Alabama"},{"facilityCode":"VCC","facilityId":"16","facilityName":"VCC","npid":"1213121312","pid":"122312","providerState":"Alabama"},{"facilityCode":"AAAAA","facilityId":"17","facilityName":"AAAAA","npid":"3","pid":"112233","providerState":"Alabama"},{"facilityCode":"AAAAB","facilityId":"18","facilityName":"AAAAB","npid":"4","pid":"334455","providerState":"Alabama"},{"facilityCode":"AAAAC","facilityId":"19","facilityName":"AAAAC","npid":"5","pid":"556677","providerState":"Alabama"},{"facilityCode":"AAAAD","facilityId":"20","facilityName":"AAAAD","npid":"6","pid":"778899","providerState":"Alabama"},{"facilityCode":"AAAAE","facilityId":"21","facilityName":"AAAAE","npid":"7","pid":"616161","providerState":"Alabama"},{"facilityCode":"AAAAF","facilityId":"22","facilityName":"AAAAF","npid":"8","pid":"626262","providerState":"Alabama"},{"facilityCode":"AAAAG","facilityId":"23","facilityName":"AAAAG","npid":"9","pid":"717171","providerState":"Alabama"},{"facilityCode":"AAAAH","facilityId":"24","facilityName":"AAAAH","npid":"10","pid":"727272","providerState":"Alabama"},{"facilityCode":"AAAAI","facilityId":"25","facilityName":"AAAAI","npid":"11","pid":"757575","providerState":"Alabama"},{"facilityCode":"AAAAJ","facilityId":"26","facilityName":"AAAAJ","npid":"12","pid":"767676","providerState":"Alabama"},{"facilityCode":"AAAAK","facilityId":"27","facilityName":"AAAAK","npid":"13","pid":"818181","providerState":"Alabama"},{"facilityCode":"AAAAL","facilityId":"28","facilityName":"AAAAL","npid":"14","pid":"828282","providerState":"Alabama"},{"facilityCode":"AAAAM","facilityId":"29","facilityName":"AAAAM","npid":"15","pid":"858585","providerState":"Alabama"},{"facilityCode":"AAAAN","facilityId":"30","facilityName":"AAAAN","npid":"16","pid":"868686","providerState":"Alabama"},{"facilityCode":"AAAAO","facilityId":"31","facilityName":"AAAAO","npid":"17","pid":"919191","providerState":"Alabama"},{"facilityCode":"AAAAP","facilityId":"32","facilityName":"AAAAP","npid":"18","pid":"929292","providerState":"Alabama"},{"facilityCode":"AAAAQ","facilityId":"33","facilityName":"AAAAQ","npid":"19","pid":"959595","providerState":"Alabama"},{"facilityCode":"AAAAR","facilityId":"34","facilityName":"AAAAR","npid":"20","pid":"969696","providerState":"Alabama"},{"facilityCode":"UNIQUE","facilityId":"35","facilityName":"UNIQUE","npid":"21","pid":"123456","providerState":"Alabama"}]}}; ``` I am setting the state of my data here and binding it (not sure why I am doing this, but I see everyone doing it as part of their ajax calls) ``` var stateSet = function(data) { this.setState({data: json1}); }; stateSet.bind(this); // attempt to mock an AJAX call here, by assuming we have already obtained the JSON object. return( <table> <tbody> <tr> <th>Facility Code</th> <th>Facility ID</th> <th>Facility Name</th> <th>NPID</th> <th>PID</th> <th>Provider State</th> </tr> { this.state.data.map(function(facility, key) { // I'm not sure if the control is entering this function, and I don't understand why return ( <tr> <td>{facility.facilityCode}</td> <td>{facility.facilityId}</td> <td>{facility.facilityName}</td> <td>{facility.npid}</td> <td>{facility.pid}</td> <td>{facility.providerState}</td> </tr> ); }) } </tbody> </table> ); ``` As I've mentioned in the code as part of the comment, I don't think the control is entering `this.state.data.map(function(facility, key) {` function and I don't understand why.
2018/04/17
[ "https://Stackoverflow.com/questions/49871473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649068/" ]
You're not targeting the `facility` array correctly. It should be `this.state.data.facilities.facility.map`, and you may also set your `json1` to `state` in your `constructor` directly like so ``` constructor() { super(); var json1 = { facilities: { facility: [ { facilityCode: "J0LN", facilityId: "1", facilityName: "J0LN", npid: "1295718450", pid: "123457", providerState: "Alabama" } .... ] } }; this.state = { data: json1 }; } ``` [Working Snippet](https://codesandbox.io/s/p13z652mx)
``` var stateSet = function(data) { this.setState({data: json1}); }; ``` why are you using function(date), this is not needed. Just give function(), because i think the stateSet is firstly not called anywhere so it doesn t get triggerd and you re expecting a prop in that function.
49,871,473
I am new to Javascripting and React JS coding. I have this JSON object- ``` var json1 = {"facilities":{"facility":[{"facilityCode":"J0LN","facilityId":"1","facilityName":"J0LN","npid":"1295718450","pid":"123457","providerState":"Alabama"},{"facilityCode":"K0NS","facilityId":"2","facilityName":"K0NS","npid":"9696969669","pid":"111111","providerState":"Alaska"},{"facilityCode":"J0LN1","facilityId":"3","facilityName":"J0LN1","npid":"111111111","pid":"221133","providerState":"Alabama"},{"facilityCode":"0987654321","facilityId":"4","facilityName":"0987654321","npid":"0987654321","pid":"235675","providerState":"Alabama"},{"facilityCode":"7776667676","facilityId":"5","facilityName":"7776667676","npid":"7776667676","pid":"236576","providerState":"Alabama"},{"facilityCode":"979797977","facilityId":"6","facilityName":"979797977","npid":"979797977","pid":"325347","providerState":"Alabama"},{"facilityCode":"9898989898","facilityId":"7","facilityName":"9898989898","npid":"9898989898","pid":"989898","providerState":"Alabama"},{"facilityCode":"121212","facilityId":"8","facilityName":"121212","npid":"1212120022","pid":"121212","providerState":"Connecticut"},{"facilityCode":"141414","facilityId":"9","facilityName":"141414","npid":"1414140022","pid":"141414","providerState":"Delaware"},{"facilityCode":"887766","facilityId":"10","facilityName":"887766","npid":"8877660022","pid":"887766","providerState":"Delaware"},{"facilityCode":"212121","facilityId":"11","facilityName":"OP-212121-OP","npid":"2121210022","pid":"212121","providerState":"Maryland"},{"facilityCode":"717171","facilityId":"12","facilityName":"IP-Qrtly-717171","npid":"7171710022","pid":"717174","providerState":"Alabama"},{"facilityCode":"RMC","facilityId":"13","facilityName":"RMC","npid":"1","pid":"676767","providerState":"Alabama"},{"facilityCode":"WCC","facilityId":"14","facilityName":"WCC","npid":"2","pid":"454676","providerState":"Alabama"},{"facilityCode":"FC","facilityId":"15","facilityName":"FN","npid":"1992813240","pid":"123456","providerState":"Alabama"},{"facilityCode":"VCC","facilityId":"16","facilityName":"VCC","npid":"1213121312","pid":"122312","providerState":"Alabama"},{"facilityCode":"AAAAA","facilityId":"17","facilityName":"AAAAA","npid":"3","pid":"112233","providerState":"Alabama"},{"facilityCode":"AAAAB","facilityId":"18","facilityName":"AAAAB","npid":"4","pid":"334455","providerState":"Alabama"},{"facilityCode":"AAAAC","facilityId":"19","facilityName":"AAAAC","npid":"5","pid":"556677","providerState":"Alabama"},{"facilityCode":"AAAAD","facilityId":"20","facilityName":"AAAAD","npid":"6","pid":"778899","providerState":"Alabama"},{"facilityCode":"AAAAE","facilityId":"21","facilityName":"AAAAE","npid":"7","pid":"616161","providerState":"Alabama"},{"facilityCode":"AAAAF","facilityId":"22","facilityName":"AAAAF","npid":"8","pid":"626262","providerState":"Alabama"},{"facilityCode":"AAAAG","facilityId":"23","facilityName":"AAAAG","npid":"9","pid":"717171","providerState":"Alabama"},{"facilityCode":"AAAAH","facilityId":"24","facilityName":"AAAAH","npid":"10","pid":"727272","providerState":"Alabama"},{"facilityCode":"AAAAI","facilityId":"25","facilityName":"AAAAI","npid":"11","pid":"757575","providerState":"Alabama"},{"facilityCode":"AAAAJ","facilityId":"26","facilityName":"AAAAJ","npid":"12","pid":"767676","providerState":"Alabama"},{"facilityCode":"AAAAK","facilityId":"27","facilityName":"AAAAK","npid":"13","pid":"818181","providerState":"Alabama"},{"facilityCode":"AAAAL","facilityId":"28","facilityName":"AAAAL","npid":"14","pid":"828282","providerState":"Alabama"},{"facilityCode":"AAAAM","facilityId":"29","facilityName":"AAAAM","npid":"15","pid":"858585","providerState":"Alabama"},{"facilityCode":"AAAAN","facilityId":"30","facilityName":"AAAAN","npid":"16","pid":"868686","providerState":"Alabama"},{"facilityCode":"AAAAO","facilityId":"31","facilityName":"AAAAO","npid":"17","pid":"919191","providerState":"Alabama"},{"facilityCode":"AAAAP","facilityId":"32","facilityName":"AAAAP","npid":"18","pid":"929292","providerState":"Alabama"},{"facilityCode":"AAAAQ","facilityId":"33","facilityName":"AAAAQ","npid":"19","pid":"959595","providerState":"Alabama"},{"facilityCode":"AAAAR","facilityId":"34","facilityName":"AAAAR","npid":"20","pid":"969696","providerState":"Alabama"},{"facilityCode":"UNIQUE","facilityId":"35","facilityName":"UNIQUE","npid":"21","pid":"123456","providerState":"Alabama"}]}}; ``` I am setting the state of my data here and binding it (not sure why I am doing this, but I see everyone doing it as part of their ajax calls) ``` var stateSet = function(data) { this.setState({data: json1}); }; stateSet.bind(this); // attempt to mock an AJAX call here, by assuming we have already obtained the JSON object. return( <table> <tbody> <tr> <th>Facility Code</th> <th>Facility ID</th> <th>Facility Name</th> <th>NPID</th> <th>PID</th> <th>Provider State</th> </tr> { this.state.data.map(function(facility, key) { // I'm not sure if the control is entering this function, and I don't understand why return ( <tr> <td>{facility.facilityCode}</td> <td>{facility.facilityId}</td> <td>{facility.facilityName}</td> <td>{facility.npid}</td> <td>{facility.pid}</td> <td>{facility.providerState}</td> </tr> ); }) } </tbody> </table> ); ``` As I've mentioned in the code as part of the comment, I don't think the control is entering `this.state.data.map(function(facility, key) {` function and I don't understand why.
2018/04/17
[ "https://Stackoverflow.com/questions/49871473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649068/" ]
You're not targeting the `facility` array correctly. It should be `this.state.data.facilities.facility.map`, and you may also set your `json1` to `state` in your `constructor` directly like so ``` constructor() { super(); var json1 = { facilities: { facility: [ { facilityCode: "J0LN", facilityId: "1", facilityName: "J0LN", npid: "1295718450", pid: "123457", providerState: "Alabama" } .... ] } }; this.state = { data: json1 }; } ``` [Working Snippet](https://codesandbox.io/s/p13z652mx)
From your question, it is clear that you are trying to access the **facility** array inside the facilities object. You can achieve this as: `this.state.data.facilities.facility.map((elementOffFacilityArray,index) => { // do whatever you would like to do with individual elements of the array. })` But at the time when this map function will execute, it might be the case that this facility array may be empty which will result in error whic already has been pointed out by @nrgwsth. Thus, you will have to keep the check and the above expression for this case will become as : ``` { this.state.data && this.state.data.facilities && this.state.data.facilities.facility ? this.state.data.facilities.facility.map((elementOffFacilityArray,index) => { // do whatever you would like to do with individual elements of the array. }) : '' } ```
52,297,389
I am using windows 10 professional and I have installed docker using DockerToolBox, so I have a docker-machine running in VirtualBox. When trying to configure an interpreter in PyCharm using my docker-machine, I get the following error: "Cannot connect: java.lang.NullPointerException: uri was not specified" [docker-machine error](https://i.stack.imgur.com/ctbQU.png) When I choose 'TCP socket', I get the following error which is different from above: "Cannot connect: java.io.IOException: Channel disconnected before any data was received" [TCP socket error](https://i.stack.imgur.com/vuCVK.png) I am sure my docker-machine is running because I can connect to it using terminal tools like MobaXterm or XShell, and I can also connect to MySQL running in my docker-machine.
2018/09/12
[ "https://Stackoverflow.com/questions/52297389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4886579/" ]
Replacing tcp:// by https:// in the api url works for me in Webstorm (Windows 8.1). <https://github.com/kubernetes/minikube/issues/580>
I have tried thousands of methods, and finally resolved this problem. The solution is running pycharm as administrator. WTF
52,297,389
I am using windows 10 professional and I have installed docker using DockerToolBox, so I have a docker-machine running in VirtualBox. When trying to configure an interpreter in PyCharm using my docker-machine, I get the following error: "Cannot connect: java.lang.NullPointerException: uri was not specified" [docker-machine error](https://i.stack.imgur.com/ctbQU.png) When I choose 'TCP socket', I get the following error which is different from above: "Cannot connect: java.io.IOException: Channel disconnected before any data was received" [TCP socket error](https://i.stack.imgur.com/vuCVK.png) I am sure my docker-machine is running because I can connect to it using terminal tools like MobaXterm or XShell, and I can also connect to MySQL running in my docker-machine.
2018/09/12
[ "https://Stackoverflow.com/questions/52297389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4886579/" ]
I have tried thousands of methods, and finally resolved this problem. The solution is running pycharm as administrator. WTF
I have same issue. You must check Pycharm logs. There is detailed information about error. In my case Pycharm shows same error "Channel disconnected before any data was received". But in logs i found that error is caused by: "ERROR - HttpResponseStreamHandlerFixed - exceptionCaught before first read or disconnect, we may be hanging io.netty.handler.codec.DecoderException: javax.net.ssl.SSLHandshakeException: No name matching "my\_server\_hostname" found" In my case, the problem was that domain name that i connecting to is in not the same as hostname in SSL self signed cert installed in dockerd. Domain name that you are connecting to must match domain name in SSL cert that dockerd uses. I have to make hosts record (C:\Windows\System32\drivers\etc\hosts on Windows, and /etc/hosts on Linux) and connect to it. And "https://" protocol is required :) PS. You can check SSL cert hostname by opening Chrome browser to the docker API endpoint with https and opening certificate details.
52,297,389
I am using windows 10 professional and I have installed docker using DockerToolBox, so I have a docker-machine running in VirtualBox. When trying to configure an interpreter in PyCharm using my docker-machine, I get the following error: "Cannot connect: java.lang.NullPointerException: uri was not specified" [docker-machine error](https://i.stack.imgur.com/ctbQU.png) When I choose 'TCP socket', I get the following error which is different from above: "Cannot connect: java.io.IOException: Channel disconnected before any data was received" [TCP socket error](https://i.stack.imgur.com/vuCVK.png) I am sure my docker-machine is running because I can connect to it using terminal tools like MobaXterm or XShell, and I can also connect to MySQL running in my docker-machine.
2018/09/12
[ "https://Stackoverflow.com/questions/52297389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4886579/" ]
Replacing tcp:// by https:// in the api url works for me in Webstorm (Windows 8.1). <https://github.com/kubernetes/minikube/issues/580>
I have same issue. You must check Pycharm logs. There is detailed information about error. In my case Pycharm shows same error "Channel disconnected before any data was received". But in logs i found that error is caused by: "ERROR - HttpResponseStreamHandlerFixed - exceptionCaught before first read or disconnect, we may be hanging io.netty.handler.codec.DecoderException: javax.net.ssl.SSLHandshakeException: No name matching "my\_server\_hostname" found" In my case, the problem was that domain name that i connecting to is in not the same as hostname in SSL self signed cert installed in dockerd. Domain name that you are connecting to must match domain name in SSL cert that dockerd uses. I have to make hosts record (C:\Windows\System32\drivers\etc\hosts on Windows, and /etc/hosts on Linux) and connect to it. And "https://" protocol is required :) PS. You can check SSL cert hostname by opening Chrome browser to the docker API endpoint with https and opening certificate details.
19,498,557
I have this PHP/HTML Code that is selecting data from a MySQL Database: ``` <?php $sql3="SELECT * from property_images where property_seq = '".$property["sequence"]."' "; $rs3=mysql_query($sql3,$conn); while($property_img=mysql_fetch_array($rs3)) { ?><tr> <td colspan="2"><img src="http://domain.co.uk/img/property-images/<?php echo $property_img["image"]; ?>" width="80px" height="80px" /></td> <td colspan="2"><input type="checkbox" name="image1" value="Y" <?php if($property_img["image1"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image2" value="Y" <?php if($property_img["image2"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image3" value="Y" <?php if($property_img["image3"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image4" value="Y" <?php if($property_img["image4"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image5" value="Y" <?php if($property_img["image5"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image6" value="Y" <?php if($property_img["image6"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image7" value="Y" <?php if($property_img["image7"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image8" value="Y" <?php if($property_img["image8"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image9" value="Y" <?php if($property_img["image9"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image10" value="Y" <?php if($property_img["image10"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image11" value="Y" <?php if($property_img["image11"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image12" value="Y" <?php if($property_img["image12"] == 'Y') { echo 'checked="checked"'; } ?> /> <input type="checkbox" name="image13" value="Y" <?php if($property_img["image13"] == 'Y') { echo 'checked="checked"'; } ?> /></td> </tr><?php } ?> ``` each row, has its own image with the columns *image1 - image13* i want to update the table with the checkboxes that are checked and unchecked on the form update how is this possible? Thanks
2013/10/21
[ "https://Stackoverflow.com/questions/19498557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2624087/" ]
I think you're on the right track, but that you're missing some details - specifically your `delayedPromise` won't invoke any subsequent callbacks with the same context and parameters as the original promise. Try this, instead: ``` function delayedPromise(promise, timeout) { var d = $.Deferred(); promise.then(function () { var ctx = this; var args = [].slice.call(arguments, 0); setTimeout(function () { d.resolveWith(ctx, args); }, timeout); }, function () { var ctx = this; var args = [].slice.call(arguments, 0); setTimeout(function () { d.rejectWith(ctx, args); }, timeout); }); return d.promise(); } ``` where the `d.resolveWith()` and `d.rejectWith` calls are necessary to preserve the aforementioned context and parameters. Note that you `progress` notifications are not delayed with this method, although those don't necessarily make any sense in this context. Similarly, if you actually want rejected promises to resolve immediately (without delay) then remove the second `function` passed to `.then`.
I hope you find the implementation of `delay` in Q insightful. <https://github.com/kriskowal/q/blob/master/q.js#L1629-L1637> ``` Q.delay = function (object, timeout) { if (timeout === void 0) { timeout = object; object = void 0; } return Q(object).delay(timeout); }; Promise.prototype.delay = function (timeout) { return this.then(function (value) { var deferred = defer(); setTimeout(function () { deferred.resolve(value); }, timeout); return deferred.promise; }); }; ```
40,681,287
I'm attempting to write a global function script that uses groovy.sql.SQL. When adding the annotation `@GrabConfig(systemClassLoader=true)` I get an exception when using the global function in Jenkinsfile. Here is the exception: ``` hudson.remoting.ProxyException: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: General error during conversion: No suitable ClassLoader found for grab ``` Here is my code: ``` @GrabResolver(name='nexus', root='http://internal.repo.com') @GrabConfig(systemClassLoader=true) @Grab('com.microsoft.sqlserver:sqljdbc4:4.0') import groovy.sql.Sql import com.microsoft.sqlserver.jdbc.SQLServerDriver def call(name) { echo "Hello world, ${name}" Sql.newInstance("jdbc:sqlserver://ipaddress/dbname", "username","password", "com.microsoft.sqlserver.jdbc.SQLServerDriver") // sql.execute "select count(*) from TableName" } ```
2016/11/18
[ "https://Stackoverflow.com/questions/40681287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3066026/" ]
Ensure that the "Use groovy sandbox" checkbox is unticked (it's below the pipeline script text box).
As explained [here](https://stackoverflow.com/a/43806910/6730571), Pipeline "scripts" are not simple Groovy scripts, they are heavily transformed before running, some parts on master, some parts on slaves, with their state (variable values) serialized and passed to the next step. As such, not every Groovy feature is supported. I'm not sure about `@Grab` support. It is discussed in [JENKINS-26192](https://issues.jenkins-ci.org/browse/JENKINS-26192) (which is declared as resolved, so maybe it works now). Extract from a very interesting [comment](https://issues.jenkins-ci.org/browse/JENKINS-26192?focusedCommentId=218183&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-218183): > > If you need to perform some complex or expensive tasks with > unrestricted Groovy physically running on a slave, it may be simplest > and most effective to simply write that code in a \*.groovy file in > your workspace (for example, in an SCM checkout) and then use tool and > sh/bat to run Groovy as an external process; or even put this stuff > into a Gradle script, Groovy Maven plugin execution, etc. The workflow > script itself should be limited to simple and extremely lightweight > logical operations focused on orchestrating the overall flow of > control and interacting with other Jenkins features—slave allocation, > user input, and the like. > > > In short, if you can move that custom part that needs SQL to an external script and execute that in a separate process (called from your Pipeline script), that should work. But doing this in the Pipeline script itself is more complicated.
33,722,662
The Train status API I use recently added two additional key value pairs `(has_arrived, has_departed)` in the JSON object, which caused my script to crash. Here's the dictionary: ``` { "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] } ``` Not surprisingly, I got the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'false' is not defined ``` If I am not mistaken, I think this is because the boolean value in the JSON response is `false`/`true` whereas Python recognizes `False`/`True`. Is there any way around it? PS: I tried converting the JSON response of `has_arrived` to string and then converting it back to a boolean value, only to find out that I'll always get a `True` value if there's any character in the string. I am kinda stuck here.
2015/11/15
[ "https://Stackoverflow.com/questions/33722662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
Even though Python's object declaration syntax is very similar to Json syntax, they're distinct and incompatible. As well as the `True`/`true` issue, there are other problems (eg Json and Python handle dates very differently, and python allows single quotes and comments while Json does not). Instead of trying to treat them as the same thing, the solution is to convert from one to the other as needed. Python's native [json](https://docs.python.org/3/library/json.html) library can be used to parse (read) the Json in a string and convert it into a python object, and you already have it installed... ``` # Import the library import json # Define a string of json data data_from_api = '{"response_code": 200, ...}' data = json.loads(data_from_api) # data is now a python dictionary (or list as appropriate) representing your Json ``` You can convert python objects to json too... ``` data_as_json = json.dumps(data) ``` Example: ``` # Import the json library import json # Get the Json data from the question into a variable... data_from_api = """{ "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] }""" # Convert that data into a python object... data = json.loads(data_from_api) print(data) ``` And a second example showing how the True/true conversion happens. Note also the changes to quotation and how the comment is stripped... ``` info = {'foo': True, # Some insightful comment here 'bar': 'Some string'} # Print a condensed representation of the object print(json.dumps(info)) > {"bar": "Some string", "foo": true} # Or print a formatted version which is more human readable but uses more bytes print(json.dumps(info, indent=2)) > { > "bar": "Some string", > "foo": true > } ```
You can also do a cast to boolean with the value. For example, assuming that your data is called "json\_data": ```py value = json_data.get('route')[0].get('has_arrived') # this will pull "false" into *value boolean_value = bool(value == 'true') # resulting in False being loaded into *boolean_value ``` It's kind of hackey, but it works.
33,722,662
The Train status API I use recently added two additional key value pairs `(has_arrived, has_departed)` in the JSON object, which caused my script to crash. Here's the dictionary: ``` { "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] } ``` Not surprisingly, I got the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'false' is not defined ``` If I am not mistaken, I think this is because the boolean value in the JSON response is `false`/`true` whereas Python recognizes `False`/`True`. Is there any way around it? PS: I tried converting the JSON response of `has_arrived` to string and then converting it back to a boolean value, only to find out that I'll always get a `True` value if there's any character in the string. I am kinda stuck here.
2015/11/15
[ "https://Stackoverflow.com/questions/33722662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
You can also do a cast to boolean with the value. For example, assuming that your data is called "json\_data": ```py value = json_data.get('route')[0].get('has_arrived') # this will pull "false" into *value boolean_value = bool(value == 'true') # resulting in False being loaded into *boolean_value ``` It's kind of hackey, but it works.
I would like to add one more thing that would work for people who are **reading from a file.** ``` with open('/Users/mohammed/Desktop/working_create_order.json')as jsonfile: data = json.dumps(jsonfile.read()) ``` Then follow the above **accepted** answer i.e. ``` data_json = json.loads(data) ```
33,722,662
The Train status API I use recently added two additional key value pairs `(has_arrived, has_departed)` in the JSON object, which caused my script to crash. Here's the dictionary: ``` { "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] } ``` Not surprisingly, I got the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'false' is not defined ``` If I am not mistaken, I think this is because the boolean value in the JSON response is `false`/`true` whereas Python recognizes `False`/`True`. Is there any way around it? PS: I tried converting the JSON response of `has_arrived` to string and then converting it back to a boolean value, only to find out that I'll always get a `True` value if there's any character in the string. I am kinda stuck here.
2015/11/15
[ "https://Stackoverflow.com/questions/33722662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
Even though Python's object declaration syntax is very similar to Json syntax, they're distinct and incompatible. As well as the `True`/`true` issue, there are other problems (eg Json and Python handle dates very differently, and python allows single quotes and comments while Json does not). Instead of trying to treat them as the same thing, the solution is to convert from one to the other as needed. Python's native [json](https://docs.python.org/3/library/json.html) library can be used to parse (read) the Json in a string and convert it into a python object, and you already have it installed... ``` # Import the library import json # Define a string of json data data_from_api = '{"response_code": 200, ...}' data = json.loads(data_from_api) # data is now a python dictionary (or list as appropriate) representing your Json ``` You can convert python objects to json too... ``` data_as_json = json.dumps(data) ``` Example: ``` # Import the json library import json # Get the Json data from the question into a variable... data_from_api = """{ "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] }""" # Convert that data into a python object... data = json.loads(data_from_api) print(data) ``` And a second example showing how the True/true conversion happens. Note also the changes to quotation and how the comment is stripped... ``` info = {'foo': True, # Some insightful comment here 'bar': 'Some string'} # Print a condensed representation of the object print(json.dumps(info)) > {"bar": "Some string", "foo": true} # Or print a formatted version which is more human readable but uses more bytes print(json.dumps(info, indent=2)) > { > "bar": "Some string", > "foo": true > } ```
{ "value": False } or { "key": false } is not a valid json <https://jsonlint.com/>
33,722,662
The Train status API I use recently added two additional key value pairs `(has_arrived, has_departed)` in the JSON object, which caused my script to crash. Here's the dictionary: ``` { "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] } ``` Not surprisingly, I got the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'false' is not defined ``` If I am not mistaken, I think this is because the boolean value in the JSON response is `false`/`true` whereas Python recognizes `False`/`True`. Is there any way around it? PS: I tried converting the JSON response of `has_arrived` to string and then converting it back to a boolean value, only to find out that I'll always get a `True` value if there's any character in the string. I am kinda stuck here.
2015/11/15
[ "https://Stackoverflow.com/questions/33722662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
Instead of doing `eval` on the answer, use the [`json`](https://docs.python.org/2/library/json.html#json.loads) module.
I would like to add one more thing that would work for people who are **reading from a file.** ``` with open('/Users/mohammed/Desktop/working_create_order.json')as jsonfile: data = json.dumps(jsonfile.read()) ``` Then follow the above **accepted** answer i.e. ``` data_json = json.loads(data) ```
33,722,662
The Train status API I use recently added two additional key value pairs `(has_arrived, has_departed)` in the JSON object, which caused my script to crash. Here's the dictionary: ``` { "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] } ``` Not surprisingly, I got the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'false' is not defined ``` If I am not mistaken, I think this is because the boolean value in the JSON response is `false`/`true` whereas Python recognizes `False`/`True`. Is there any way around it? PS: I tried converting the JSON response of `has_arrived` to string and then converting it back to a boolean value, only to find out that I'll always get a `True` value if there's any character in the string. I am kinda stuck here.
2015/11/15
[ "https://Stackoverflow.com/questions/33722662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
It is possible to utilize Python's boolean value for int, str, list etc. For example: ``` bool(1) # True bool(0) # False bool("a") # True bool("") # False bool([1]) # True bool([]) # False ``` In Json file, you can set ``` "has_arrived": 0, ``` Then in your Python code ``` if data["has_arrived"]: arrived() else: not_arrived() ``` The issue here is not to confuse 0 indicated for False and 0 for its value.
json.loads cant parse the pythons boolean type (False, True). Json wants to have small letters false, true my solution: python\_json\_string.replace(": True,", ": true,").replace(": False,", ": false,")
33,722,662
The Train status API I use recently added two additional key value pairs `(has_arrived, has_departed)` in the JSON object, which caused my script to crash. Here's the dictionary: ``` { "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] } ``` Not surprisingly, I got the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'false' is not defined ``` If I am not mistaken, I think this is because the boolean value in the JSON response is `false`/`true` whereas Python recognizes `False`/`True`. Is there any way around it? PS: I tried converting the JSON response of `has_arrived` to string and then converting it back to a boolean value, only to find out that I'll always get a `True` value if there's any character in the string. I am kinda stuck here.
2015/11/15
[ "https://Stackoverflow.com/questions/33722662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
You can also do a cast to boolean with the value. For example, assuming that your data is called "json\_data": ```py value = json_data.get('route')[0].get('has_arrived') # this will pull "false" into *value boolean_value = bool(value == 'true') # resulting in False being loaded into *boolean_value ``` It's kind of hackey, but it works.
It is possible to utilize Python's boolean value for int, str, list etc. For example: ``` bool(1) # True bool(0) # False bool("a") # True bool("") # False bool([1]) # True bool([]) # False ``` In Json file, you can set ``` "has_arrived": 0, ``` Then in your Python code ``` if data["has_arrived"]: arrived() else: not_arrived() ``` The issue here is not to confuse 0 indicated for False and 0 for its value.
33,722,662
The Train status API I use recently added two additional key value pairs `(has_arrived, has_departed)` in the JSON object, which caused my script to crash. Here's the dictionary: ``` { "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] } ``` Not surprisingly, I got the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'false' is not defined ``` If I am not mistaken, I think this is because the boolean value in the JSON response is `false`/`true` whereas Python recognizes `False`/`True`. Is there any way around it? PS: I tried converting the JSON response of `has_arrived` to string and then converting it back to a boolean value, only to find out that I'll always get a `True` value if there's any character in the string. I am kinda stuck here.
2015/11/15
[ "https://Stackoverflow.com/questions/33722662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
Instead of doing `eval` on the answer, use the [`json`](https://docs.python.org/2/library/json.html#json.loads) module.
{ "value": False } or { "key": false } is not a valid json <https://jsonlint.com/>
33,722,662
The Train status API I use recently added two additional key value pairs `(has_arrived, has_departed)` in the JSON object, which caused my script to crash. Here's the dictionary: ``` { "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] } ``` Not surprisingly, I got the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'false' is not defined ``` If I am not mistaken, I think this is because the boolean value in the JSON response is `false`/`true` whereas Python recognizes `False`/`True`. Is there any way around it? PS: I tried converting the JSON response of `has_arrived` to string and then converting it back to a boolean value, only to find out that I'll always get a `True` value if there's any character in the string. I am kinda stuck here.
2015/11/15
[ "https://Stackoverflow.com/questions/33722662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
You can also do a cast to boolean with the value. For example, assuming that your data is called "json\_data": ```py value = json_data.get('route')[0].get('has_arrived') # this will pull "false" into *value boolean_value = bool(value == 'true') # resulting in False being loaded into *boolean_value ``` It's kind of hackey, but it works.
json.loads cant parse the pythons boolean type (False, True). Json wants to have small letters false, true my solution: python\_json\_string.replace(": True,", ": true,").replace(": False,", ": false,")
33,722,662
The Train status API I use recently added two additional key value pairs `(has_arrived, has_departed)` in the JSON object, which caused my script to crash. Here's the dictionary: ``` { "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] } ``` Not surprisingly, I got the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'false' is not defined ``` If I am not mistaken, I think this is because the boolean value in the JSON response is `false`/`true` whereas Python recognizes `False`/`True`. Is there any way around it? PS: I tried converting the JSON response of `has_arrived` to string and then converting it back to a boolean value, only to find out that I'll always get a `True` value if there's any character in the string. I am kinda stuck here.
2015/11/15
[ "https://Stackoverflow.com/questions/33722662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
You can also do a cast to boolean with the value. For example, assuming that your data is called "json\_data": ```py value = json_data.get('route')[0].get('has_arrived') # this will pull "false" into *value boolean_value = bool(value == 'true') # resulting in False being loaded into *boolean_value ``` It's kind of hackey, but it works.
``` """ String to Dict (Json): json.loads(jstr) Note: in String , shown true, in Dict shown True Dict(Json) to String: json.dumps(jobj) """ >>> jobj = {'test': True} >>> jstr = json.dumps(jobj) >>> jobj {'test': True} >>> jstr '{"test": true}' >>> json.loads(jstr) {'test': True} ```
33,722,662
The Train status API I use recently added two additional key value pairs `(has_arrived, has_departed)` in the JSON object, which caused my script to crash. Here's the dictionary: ``` { "response_code": 200, "train_number": "12229", "position": "at Source", "route": [ { "no": 1, "has_arrived": false, "has_departed": false, "scharr": "Source", "scharr_date": "15 Nov 2015", "actarr_date": "15 Nov 2015", "station": "LKO", "actdep": "22:15", "schdep": "22:15", "actarr": "00:00", "distance": "0", "day": 0 }, { "actdep": "23:40", "scharr": "23:38", "schdep": "23:40", "actarr": "23:38", "no": 2, "has_departed": false, "scharr_date": "15 Nov 2015", "has_arrived": false, "station": "HRI", "distance": "101", "actarr_date": "15 Nov 2015", "day": 0 } ] } ``` Not surprisingly, I got the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'false' is not defined ``` If I am not mistaken, I think this is because the boolean value in the JSON response is `false`/`true` whereas Python recognizes `False`/`True`. Is there any way around it? PS: I tried converting the JSON response of `has_arrived` to string and then converting it back to a boolean value, only to find out that I'll always get a `True` value if there's any character in the string. I am kinda stuck here.
2015/11/15
[ "https://Stackoverflow.com/questions/33722662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
``` """ String to Dict (Json): json.loads(jstr) Note: in String , shown true, in Dict shown True Dict(Json) to String: json.dumps(jobj) """ >>> jobj = {'test': True} >>> jstr = json.dumps(jobj) >>> jobj {'test': True} >>> jstr '{"test": true}' >>> json.loads(jstr) {'test': True} ```
json.loads cant parse the pythons boolean type (False, True). Json wants to have small letters false, true my solution: python\_json\_string.replace(": True,", ": true,").replace(": False,", ": false,")
13,323,356
This is not about how to manage or correct a faulty JSON, it is about how to explain to the user where the error is in the faulty JSON. Is there a way to find out at which position in the JSON the parser failed. I want to solve this problem in a node.js application so please keep your answers in that domain if possible. When I use the built in JSON object and the parse method for a faulty JSON I only get the exception message **`SyntaxError: Unexpected string`**. I would like to find out where the error occurred. Preferred would be a `JSON.validate(json)` that returned result ok/error and the error position. Something like this: ``` var faultyJsonToParse = '{"string":"value", "boolean": true"}'; var result = JSON.validate(faultyJsonToParse); if (result.ok == true) { console.log('Good JSON, well done!'); } else { console.log('The validator found a \'' + result.error + '\' of type \'' + result.errorType + '\' in your JSON near position ' + result.position); } ``` The wanted outcome of the above would be: ``` The validator found a 'SyntaxError' of type 'Unexpected string' in your JSON near position 35. ```
2012/11/10
[ "https://Stackoverflow.com/questions/13323356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782954/" ]
Try [jsonLint](http://zaach.github.com/jsonlint/): ``` var faultyJsonToParse = '{"string":"value", "boolean": true"}'; try { jsonlint.parse(faultyJsonToParse) } catch(e) { document.write('<pre>' + e) } ``` result: ``` Error: Parse error on line 1: ...ue", "boolean": true"} -----------------------^ Expecting 'EOF', '}', ',', ']', got 'undefined' ``` (although jsonLint is a node project, it can also be used in web: simply grab <https://github.com/zaach/jsonlint/blob/master/web/jsonlint.js>) As @eh9 suggested, it makes sense to create a wrapper around the standard json parser to provide detailed exception info: ``` JSON._parse = JSON.parse JSON.parse = function (json) { try { return JSON._parse(json) } catch(e) { jsonlint.parse(json) } } JSON.parse(someJson) // either a valid object, or an meaningful exception ```
The built-in versions of `JSON.parse()` don't have consistent behavior. It's consistent when the argument is well-formed, and inconsistent if it's not. This goes back to an incomplete specification of this function in the original JSON library implementation. The specification was incomplete because it did not define an interface for exception objects. And this situation leads directly to your question. While I don't know of a solution that's off-the-shelf at this time, the solution requires writing a JSON parser and tracking position information for error handling. This can be inserted seamlessly into your existing code by (1) first invoking the native version, and (2) if the native version throws an exception, invoke the position-aware version (it'll be slower) let it throw the exception that your own code standardizes on.
13,323,356
This is not about how to manage or correct a faulty JSON, it is about how to explain to the user where the error is in the faulty JSON. Is there a way to find out at which position in the JSON the parser failed. I want to solve this problem in a node.js application so please keep your answers in that domain if possible. When I use the built in JSON object and the parse method for a faulty JSON I only get the exception message **`SyntaxError: Unexpected string`**. I would like to find out where the error occurred. Preferred would be a `JSON.validate(json)` that returned result ok/error and the error position. Something like this: ``` var faultyJsonToParse = '{"string":"value", "boolean": true"}'; var result = JSON.validate(faultyJsonToParse); if (result.ok == true) { console.log('Good JSON, well done!'); } else { console.log('The validator found a \'' + result.error + '\' of type \'' + result.errorType + '\' in your JSON near position ' + result.position); } ``` The wanted outcome of the above would be: ``` The validator found a 'SyntaxError' of type 'Unexpected string' in your JSON near position 35. ```
2012/11/10
[ "https://Stackoverflow.com/questions/13323356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782954/" ]
Try [jsonLint](http://zaach.github.com/jsonlint/): ``` var faultyJsonToParse = '{"string":"value", "boolean": true"}'; try { jsonlint.parse(faultyJsonToParse) } catch(e) { document.write('<pre>' + e) } ``` result: ``` Error: Parse error on line 1: ...ue", "boolean": true"} -----------------------^ Expecting 'EOF', '}', ',', ']', got 'undefined' ``` (although jsonLint is a node project, it can also be used in web: simply grab <https://github.com/zaach/jsonlint/blob/master/web/jsonlint.js>) As @eh9 suggested, it makes sense to create a wrapper around the standard json parser to provide detailed exception info: ``` JSON._parse = JSON.parse JSON.parse = function (json) { try { return JSON._parse(json) } catch(e) { jsonlint.parse(json) } } JSON.parse(someJson) // either a valid object, or an meaningful exception ```
If you are using NodeJS, clarinet is a very nice event-based JSON parser that will help you generate better error messages (line and column or the error). I have build a small utility using [clarinet's parser](https://github.com/dscape/clarinet) that returns: ``` snippet (string): the actual line where the error happened line (number) : the line number of the error column (number) : the column number of the error message (string): the parser's error message ``` The code is here: <https://gist.github.com/davidrapin/93eec270153d90581097>
52,947
TLDR; Is there a security risk if rather than setting the iteration parameter to 12 (for example), we set it to 3 but call the function 4 times? I'm asking that for 2 reasons: Firstly, we use SRP protocol where the deprecated SHA1 is replaced by Argon2id inside our PWA (Progressive Web App, so in JavaScript) but Firefox and [Google currently discuss](https://bugs.chromium.org/p/chromium/issues/detail?id=766068) to inform user when an operation take too much CPU or RAM. Their goal is to fight against website that doing bitcoin's mining in the background. I don't want this require user's confirmation each time we use Argon2. Secondly, as we can't known which CPU/RAM are available for the smartphone in JavaScript, we can't known the ideal number of iterations to ideally doing, so we need to find this with the help of a chronometer, we can call Argon2id as many time as possible until 3 seconds elapsed. Of course, we also keep in memory the number of calls used the first time, to do the exact same number of calls the next time we want to compare. BTW, the last [RFC 8018](https://www.rfc-editor.org/rfc/rfc8018) of January 2017 still recommend PBKDF2 and this KDF is natively supported in browser (WebCrypto API) and faster than any external library, so may be the solution is to not use Argon2 and to use WebCrypto PBKDF2, with the same method of multiple calls until 3 seconds elapsed?
2017/11/08
[ "https://crypto.stackexchange.com/questions/52947", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/51301/" ]
I'm adding my solution here for the record. Rather than calling multiple times the Argon2d function when the user sign in, we can do something smarter, with a research of the best settings when the user sign up. We can inform him we will take few seconds to adjust the security while 5 ~ 10 seconds. So if the browser block the process and warn the user, he's already informed and can let continue the process. Technically, we trying different settings from the lower values (1MB / 1 iteration) until the delay measured require at least 1 second. Then, we could save the settings to use for this user's device. When the user sign in, we simply use the associated settings, and this will not take more than 1 ~ 2 seconds. So in theory this shouldn't be blocked by the browser, and we increase security in following the device's capabilities. Some real tests: * Apple iPhone 4S (512MB - 1Ghz): ~1.7s ==> m=1MB,t=1 * Apple iPhone 5 (1GB - 1.3Ghz dual-core): ~1.2s ==> m=4MB,t=1 * Samsung S8 (4 GB, 2.3GHz / 1.7GHz quad-core each): ~1.4s ==> m=24MB,t=2 * NUC i3 (8GB - 1.7Ghz quad-core): ~1.4s ==> m=24MB,t=2 Any feedback are welcome.
I assume you mean the execution time parameter with "iterations". Argon2 was designed to be as memory hard per execution time as possible (along with other critera). If you call Argon2 several times with lower parameters, you are interfering with that goal. Although there are no insecure parameter values, lower values makes an attack easier. That is, the duration of time for a particular hardware of an attack is lower - or the cost of customized hardware to crack the password in a feasible time. PBKDF2 is not an alternative. The resistance to custom hardware attacks is close to zero, and if you increase the number of iterations to an appropriate number, the same browser problem occurs. If Firefox and Chrome really decide to inform users about time-cosuming and memory-consuming operations to protect mining, then that would be an unsolvable problem for your (and any equivalent) application. Mining is very similar to password hashing (Litecoin and other mining is also memory hard). A good password hashing would therefore always be affected by this measure.
52,947
TLDR; Is there a security risk if rather than setting the iteration parameter to 12 (for example), we set it to 3 but call the function 4 times? I'm asking that for 2 reasons: Firstly, we use SRP protocol where the deprecated SHA1 is replaced by Argon2id inside our PWA (Progressive Web App, so in JavaScript) but Firefox and [Google currently discuss](https://bugs.chromium.org/p/chromium/issues/detail?id=766068) to inform user when an operation take too much CPU or RAM. Their goal is to fight against website that doing bitcoin's mining in the background. I don't want this require user's confirmation each time we use Argon2. Secondly, as we can't known which CPU/RAM are available for the smartphone in JavaScript, we can't known the ideal number of iterations to ideally doing, so we need to find this with the help of a chronometer, we can call Argon2id as many time as possible until 3 seconds elapsed. Of course, we also keep in memory the number of calls used the first time, to do the exact same number of calls the next time we want to compare. BTW, the last [RFC 8018](https://www.rfc-editor.org/rfc/rfc8018) of January 2017 still recommend PBKDF2 and this KDF is natively supported in browser (WebCrypto API) and faster than any external library, so may be the solution is to not use Argon2 and to use WebCrypto PBKDF2, with the same method of multiple calls until 3 seconds elapsed?
2017/11/08
[ "https://crypto.stackexchange.com/questions/52947", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/51301/" ]
I'm adding my solution here for the record. Rather than calling multiple times the Argon2d function when the user sign in, we can do something smarter, with a research of the best settings when the user sign up. We can inform him we will take few seconds to adjust the security while 5 ~ 10 seconds. So if the browser block the process and warn the user, he's already informed and can let continue the process. Technically, we trying different settings from the lower values (1MB / 1 iteration) until the delay measured require at least 1 second. Then, we could save the settings to use for this user's device. When the user sign in, we simply use the associated settings, and this will not take more than 1 ~ 2 seconds. So in theory this shouldn't be blocked by the browser, and we increase security in following the device's capabilities. Some real tests: * Apple iPhone 4S (512MB - 1Ghz): ~1.7s ==> m=1MB,t=1 * Apple iPhone 5 (1GB - 1.3Ghz dual-core): ~1.2s ==> m=4MB,t=1 * Samsung S8 (4 GB, 2.3GHz / 1.7GHz quad-core each): ~1.4s ==> m=24MB,t=2 * NUC i3 (8GB - 1.7Ghz quad-core): ~1.4s ==> m=24MB,t=2 Any feedback are welcome.
One other solution is to try to first do a quick microbenchmark, and *then* decide if the user is logging in with approximately the capabilities you've seen before. If no, besides comparing against existing saved results, generate new independent results that can be used next time for devices closer to this performance. Basically, you can have multiple tuples of * Argon2id parameters * salt, and * derived public key or whatever you're using for comparison, for each user. Basic one-to-many relationship. When a user starts a login (or maybe even preemptively, if you have a good heuristic for when to do it, or don't mind hitting the user with a microbenchmark even if they weren't going to log in) you can start that microbenchmark in the background. When that microbenchmark is done, pick Argon2id parameters that are a good fit for results in that ballpark, and then: * If you already have an entry for those parameters, run Argon2id with those parameters and that salt, and compare with those keys. * If you don't already have an entry for those parameters, 1. do the login with the closest parameters you do have an entry for, and then 2. generate a new salt (if each parameterization of Argon2id for a user gets its own salt, then even if an attacker is able to get the existing salts, the attacker still can't benefit from pre-computing rainbow tables with weaker parameters and then causing their target user to run on a system that benchmarks to those weaker settings), generate new keys, and save that new entry for later. (This step can be done in the background, you don't have to block the UI or get in the user's way.) Expire the entries which aren't used for a while, maybe with a bias for expiring weaker or uncommonly used entries sooner. (This way, if a user logs in once from some old or weak device and then doesn't for a while, you're not keeping their weaker less crack-resistant results around indefinitely, reducing the time window during which a database leak or similar could expose those weaker entries.) Of course, alternatively, you could just keep only the weakest Argon2id parameters and derived public key seen so far... the one argument for multiple entries being a bad idea is that there are multiple possible results the attacker could try to brute force, and maybe one day it turns out that Argon2id is easier to crack if the salt has very specific bits or if you have multiple results with different iterarions (in which case multiple entries with individual salts means more chances to have one with such a bad salt). But I would still keep the Argon2id settings from those entries, with at least a timestamp of the most recent time they logged in from a device that would get those settings, so that you can still expire the weakest entry (and delete it on next login after upgrading to a stronger one) - otherwise your system ends up a ratchet that only ever downgrades settings, which is the exact opposite of the goal here. With all this in place, the work factor automatically tunes itself for each user's current systems. The only weakness is that if an attacker can raise the user's CPU and memory usage, or get them to use a device with lower specs, that can become a downgrade attack instead of just making login slow. But of course you'd still impose a minimum acceptable floor on the Argon2id settings, right? The strength is that as your user upgrades their device, their work factor will automatically increase after a slight lag time. Is this scheme actually good? Ehh, decide for yourself. Personally I like it, and I'd rather use something like that than something that got stuck on whatever work factor was appropriate for the one device I registered from, but I'd want good cryptographers and security experts to weigh in and look at it critically first.
33,606,273
Please help.. i have listview with radio button value but my problem is i dont know to check each radio button and get the value.. this is my **checkoutlayout1.xml** ``` <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:fillViewport="false" android:background="#fffff1f1"> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffff1f1" android:orientation="horizontal" android:gravity="center_horizontal" android:paddingBottom="20dp"> <FrameLayout android:id="@+id/framelayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffddbd7" android:padding="10dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="STEP 1 OF 3 - DELIVERY INFORMATION" android:id="@+id/textStep" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:gravity="center" android:textSize="17dp" /> </RelativeLayout> </FrameLayout> <FrameLayout android:id="@+id/framelayout2" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff949596" android:layout_below="@+id/framelayout" android:padding="10dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginBottom="10dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Please select the preferred shipping method to use on this order." android:id="@+id/textShipping" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:gravity="center" android:textColor="#ffffffff" /> </RelativeLayout> </FrameLayout> <FrameLayout android:id="@+id/framelayout3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/framelayout2" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:padding="10dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.administrator.mosbeau.ExpandableHeightListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/shippinglist" android:divider="@android:color/transparent" android:dividerHeight="10dp" android:background="#fffff1f1" android:layout_below="@+id/textnote" android:layout_marginBottom="20dp" android:layout_marginTop="5dp"/> </RelativeLayout> </FrameLayout> <FrameLayout android:id="@+id/framelayout3" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/framelayout4" android:paddingLeft="50dp" android:paddingRight="50dp" android:layout_margin="20dp"> <Button android:layout_width="match_parent" android:layout_height="match_parent" android:text="CONTINUE" android:id="@+id/btnContinue" android:textColor="#ffffffff" android:background="@drawable/cfa245_button" android:textStyle="bold" /> </FrameLayout> </RelativeLayout> </ScrollView> ``` in my layout i have this listview ``` <com.example.administrator.mosbeau.ExpandableHeightListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/shippinglist" android:divider="@android:color/transparent" android:dividerHeight="10dp" android:background="#fffff1f1" android:layout_below="@+id/textnote" android:layout_marginBottom="20dp" android:layout_marginTop="5dp"/> ``` and this is my **shippingrate\_item.xml** ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:background="#fffff1f1" android:layout_height="fill_parent"> <FrameLayout android:id="@+id/framelayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffff1f1"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textconfigurationid" android:layout_width="wrap_content" android:text="configuration_id" android:layout_height="wrap_content" android:visibility="invisible"/> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="shipping_title" android:textColor="#666666" android:id="@+id/radioShippingtitle" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/shipping_icon" android:adjustViewBounds="true" android:layout_toRightOf="@+id/radioShippingtitle" android:layout_toEndOf="@+id/radioShippingtitle" android:layout_marginLeft="10dp" android:layout_marginTop="5dp" android:maxHeight="20dp" android:maxWidth="60dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textPrice" android:text="shipping_price" android:layout_toRightOf="@+id/shipping_icon" android:layout_toEndOf="@+id/shipping_icon" android:layout_marginLeft="10dp" android:minHeight="32dp" android:gravity="center_vertical" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textDesc" android:text="shipping_desc" android:layout_marginLeft="32dp" android:layout_below="@+id/radioShippingtitle"/> </RelativeLayout> </FrameLayout> </RelativeLayout> ``` in my item i have this radio ``` <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="shipping_title" android:textColor="#666666" android:id="@+id/radioShippingtitle" /> ``` i pass value to my listview item with my **checkoutFragment1.java** ``` package com.example.administrator.mosbeau; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentManager; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; /** * Created by Administrator on 11/7/2015. */ public class CheckoutFragment1 extends Fragment { public static CheckoutFragment1 newInstance(String customersid, String countryid, String weightotal, String subtotal, String stateid) { CheckoutFragment1 fragment = new CheckoutFragment1(); Bundle bundle = new Bundle(); bundle.putString("customersid", customersid); bundle.putString("countryid", countryid); bundle.putString("weightotal", weightotal); bundle.putString("subtotal", subtotal); bundle.putString("stateid", stateid); fragment.setArguments(bundle); return fragment; } public CheckoutFragment1 () { } String customersid, countryid, weightotal, subtotal, stateid; public static final int CONNECTION_TIMEOUT = 1000 * 15; public static final String SERVER_ADDRESS = "http://shop.mosbeau.com.ph/android/"; String myJSONShippingRate; JSONArray jsonarrayShippingRate; ExpandableHeightListView shippingratelistview; ListViewAdapterShipping shippingrateadapter; ProgressDialog mProgressDialog; ArrayList<HashMap<String, String>> shippingratearraylist; public static String configuration_id = "configuration_id"; public static String shipping_title = "shipping_title"; public static String shipping_icon = "shipping_icon"; public static String shipping_price = "shipping_price"; public static String shipping_desc = "shipping_desc"; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View rootView = inflater.inflate(R.layout.checkoutlayout1, container, false); ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); //boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; if(isConnected){ getShippingRate(); }else{ nointernet(); } if(getArguments() != null) { String ccustomersid = getArguments().getString("customersid"); String ccountryid = getArguments().getString("countryid"); String cweightotal = getArguments().getString("weightotal"); String csubtotal = getArguments().getString("subtotal"); String cstateid = getArguments().getString("stateid"); customersid = ccustomersid; countryid = ccountryid; weightotal = cweightotal; subtotal = csubtotal; stateid = cstateid; } shippingratelistview = new ExpandableHeightListView(getActivity()); shippingratelistview = (ExpandableHeightListView) rootView.findViewById(R.id.shippinglist); //Toast.makeText(getActivity(),"custoid: "+customersid+" countryid: "+countryid+" weight: "+weightotal+"subtotal: "+subtotal+" stateid: "+stateid,Toast.LENGTH_SHORT).show(); showGlobalContextActionBar(); return rootView; } private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle("CHECKOUT"); } private ActionBar getActionBar() { return ((ActionBarActivity) getActivity()).getSupportActionBar(); } public void getShippingRate(){ class DownloadJSONShippingRate extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); // Create a progressdialog /*mProgressDialog = new ProgressDialog(getActivity()); // Set progressdialog title //mProgressDialog.setTitle(cname); // Set progressdialog message mProgressDialog.setMessage("Please wait..."); mProgressDialog.setIndeterminate(false); // Show progressdialog mProgressDialog.show();*/ mProgressDialog = ProgressDialog.show(getActivity(), null, null, true, false); mProgressDialog.setContentView(R.layout.progressdialog); } @Override protected String doInBackground(String... params) { ArrayList<NameValuePair> dataToSend = new ArrayList<>(); dataToSend.add(new BasicNameValuePair("customersid", customersid)); dataToSend.add(new BasicNameValuePair("countryid", countryid)); dataToSend.add(new BasicNameValuePair("stateid", stateid)); dataToSend.add(new BasicNameValuePair("weightotal", weightotal)); dataToSend.add(new BasicNameValuePair("subtotal", subtotal)); HttpParams httpRequestParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT); DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httppost = new HttpPost(SERVER_ADDRESS + "shippingrate.php"); // Depends on your web service //httppost.setHeader("Content-type", "application/json"); InputStream inputStream = null; String shippingrateresult = null; try { httppost.setEntity(new UrlEncodedFormEntity(dataToSend)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } shippingrateresult = sb.toString(); } catch (Exception e) { // Oops } finally { try{if(inputStream != null)inputStream.close();}catch(Exception squish){} } return shippingrateresult; } @Override protected void onPostExecute(String shippingrateresult){ myJSONShippingRate=shippingrateresult; try { // Locate the array name in JSON JSONObject jsonObjcart = new JSONObject(myJSONShippingRate); jsonarrayShippingRate = jsonObjcart.getJSONArray("shippingrate"); shippingratearraylist = new ArrayList<HashMap<String, String>>(); int qtySum = 0, qtyNum, tqtySum; for (int i = 0; i < jsonarrayShippingRate.length(); i++) { HashMap<String, String> lmap = new HashMap<String, String>(); JSONObject p = jsonarrayShippingRate.getJSONObject(i); // Retrive JSON Objects lmap.put("configuration_id", p.getString("configuration_id")); lmap.put("shipping_title", p.getString("shipping_title")); lmap.put("shipping_desc", p.getString("shipping_desc")); lmap.put("shipping_icon", p.getString("shipping_icon")); lmap.put("shipping_price", p.getString("shipping_price")); shippingratearraylist.add(lmap); } } catch (JSONException e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } shippingrateadapter = new ListViewAdapterShipping(getActivity(), shippingratearraylist); shippingratelistview.setAdapter(shippingrateadapter); shippingratelistview.setExpanded(true); // Close the progressdialog mProgressDialog.dismiss(); } } DownloadJSONShippingRate g = new DownloadJSONShippingRate(); g.execute(); } public void nointernet(){ AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); dialogBuilder.setMessage("There seems to be a problem with your connection."); dialogBuilder.setNegativeButton("Edit Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Stop the activity startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); } }); dialogBuilder.setPositiveButton("Reload", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Stop the activity HomeFragment homefragment = HomeFragment.newInstance(); FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, homefragment) .addToBackStack(null) .commit(); } }); AlertDialog dialog = dialogBuilder.show(); TextView messageText = (TextView)dialog.findViewById(android.R.id.message); messageText.setGravity(Gravity.CENTER); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(false); dialog.show(); } } ``` and my **listviewadaptershipping.java** ``` package com.example.administrator.mosbeau; import android.app.Activity; import android.app.AlertDialog; import android.app.FragmentManager; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONArray; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; /** * Created by Administrator on 11/9/2015. */ public class ListViewAdapterShipping extends BaseAdapter { boolean expanded = false; // Declare Variables Context context; LayoutInflater inflater; ArrayList<HashMap<String, String>> data; HashMap<String, String> resultp = new HashMap<String, String>(); public ListViewAdapterShipping(Context context, ArrayList<HashMap<String, String>> arraylist) { this.context = context; data = arraylist; } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } public View getView(final int position, View convertView, ViewGroup parent) { // Declare Variables TextView configuration_id; RadioButton shipping_title; ImageView shipping_icon; TextView shipping_price; TextView shipping_desc; inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = inflater.inflate(R.layout.shippingrate_item, parent, false); // Get the position resultp = data.get(position); // Locate the TextViews in product_gridview_item.xml configuration_id = (TextView) itemView.findViewById(R.id.textconfigurationid); shipping_title = (RadioButton) itemView.findViewById(R.id.radioShippingtitle); shipping_icon = (ImageView) itemView.findViewById(R.id.shipping_icon); shipping_price = (TextView) itemView.findViewById(R.id.textPrice); shipping_desc = (TextView) itemView.findViewById(R.id.textDesc); // Capture position and set results to the TextViews configuration_id.setText(resultp.get(CheckoutFragment1.configuration_id)); shipping_title.setText(resultp.get(CheckoutFragment1.shipping_title)); shipping_price.setText(resultp.get(CheckoutFragment1.shipping_price)); shipping_desc.setText(resultp.get(CheckoutFragment1.shipping_desc)); // Capture position and set results to the ImageView Glide.with(context).load(resultp.get(CheckoutFragment1.shipping_icon)).diskCacheStrategy(DiskCacheStrategy.ALL).into(shipping_icon); int color = 0xffffffff; itemView.setBackgroundColor(color); return itemView; } } ``` **now the problem is i want to click the radio button and get the textconfigurationid and pass to variable** please help me.. Thanks
2015/11/09
[ "https://Stackoverflow.com/questions/33606273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5392085/" ]
I cant understand your problem correctly, but what i guess you want to get value of RadioButton and TextView(textconfigurationid) to store in a variable. You can handle your click events in your `getView` method in the BaseAdapter. Something like this: ``` public View getView(final int position, View convertView, ViewGroup parent) { //*** Your code here.. ***// itemView.setBackgroundColor(color); //You can get value of radio button and textview like this. Boolean radioValue = shipping_title.isChecked(); int configId = configuration_id.getText(); return itemView; } ```
Try using radioButton.isChecked(), it will tell you whether the radio button is checked or not. Also, you can use ``` radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); ```
33,606,273
Please help.. i have listview with radio button value but my problem is i dont know to check each radio button and get the value.. this is my **checkoutlayout1.xml** ``` <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:fillViewport="false" android:background="#fffff1f1"> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffff1f1" android:orientation="horizontal" android:gravity="center_horizontal" android:paddingBottom="20dp"> <FrameLayout android:id="@+id/framelayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffddbd7" android:padding="10dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="STEP 1 OF 3 - DELIVERY INFORMATION" android:id="@+id/textStep" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:gravity="center" android:textSize="17dp" /> </RelativeLayout> </FrameLayout> <FrameLayout android:id="@+id/framelayout2" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff949596" android:layout_below="@+id/framelayout" android:padding="10dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginBottom="10dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Please select the preferred shipping method to use on this order." android:id="@+id/textShipping" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:gravity="center" android:textColor="#ffffffff" /> </RelativeLayout> </FrameLayout> <FrameLayout android:id="@+id/framelayout3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/framelayout2" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:padding="10dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.administrator.mosbeau.ExpandableHeightListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/shippinglist" android:divider="@android:color/transparent" android:dividerHeight="10dp" android:background="#fffff1f1" android:layout_below="@+id/textnote" android:layout_marginBottom="20dp" android:layout_marginTop="5dp"/> </RelativeLayout> </FrameLayout> <FrameLayout android:id="@+id/framelayout3" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/framelayout4" android:paddingLeft="50dp" android:paddingRight="50dp" android:layout_margin="20dp"> <Button android:layout_width="match_parent" android:layout_height="match_parent" android:text="CONTINUE" android:id="@+id/btnContinue" android:textColor="#ffffffff" android:background="@drawable/cfa245_button" android:textStyle="bold" /> </FrameLayout> </RelativeLayout> </ScrollView> ``` in my layout i have this listview ``` <com.example.administrator.mosbeau.ExpandableHeightListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/shippinglist" android:divider="@android:color/transparent" android:dividerHeight="10dp" android:background="#fffff1f1" android:layout_below="@+id/textnote" android:layout_marginBottom="20dp" android:layout_marginTop="5dp"/> ``` and this is my **shippingrate\_item.xml** ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:background="#fffff1f1" android:layout_height="fill_parent"> <FrameLayout android:id="@+id/framelayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffff1f1"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textconfigurationid" android:layout_width="wrap_content" android:text="configuration_id" android:layout_height="wrap_content" android:visibility="invisible"/> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="shipping_title" android:textColor="#666666" android:id="@+id/radioShippingtitle" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/shipping_icon" android:adjustViewBounds="true" android:layout_toRightOf="@+id/radioShippingtitle" android:layout_toEndOf="@+id/radioShippingtitle" android:layout_marginLeft="10dp" android:layout_marginTop="5dp" android:maxHeight="20dp" android:maxWidth="60dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textPrice" android:text="shipping_price" android:layout_toRightOf="@+id/shipping_icon" android:layout_toEndOf="@+id/shipping_icon" android:layout_marginLeft="10dp" android:minHeight="32dp" android:gravity="center_vertical" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textDesc" android:text="shipping_desc" android:layout_marginLeft="32dp" android:layout_below="@+id/radioShippingtitle"/> </RelativeLayout> </FrameLayout> </RelativeLayout> ``` in my item i have this radio ``` <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="shipping_title" android:textColor="#666666" android:id="@+id/radioShippingtitle" /> ``` i pass value to my listview item with my **checkoutFragment1.java** ``` package com.example.administrator.mosbeau; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentManager; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; /** * Created by Administrator on 11/7/2015. */ public class CheckoutFragment1 extends Fragment { public static CheckoutFragment1 newInstance(String customersid, String countryid, String weightotal, String subtotal, String stateid) { CheckoutFragment1 fragment = new CheckoutFragment1(); Bundle bundle = new Bundle(); bundle.putString("customersid", customersid); bundle.putString("countryid", countryid); bundle.putString("weightotal", weightotal); bundle.putString("subtotal", subtotal); bundle.putString("stateid", stateid); fragment.setArguments(bundle); return fragment; } public CheckoutFragment1 () { } String customersid, countryid, weightotal, subtotal, stateid; public static final int CONNECTION_TIMEOUT = 1000 * 15; public static final String SERVER_ADDRESS = "http://shop.mosbeau.com.ph/android/"; String myJSONShippingRate; JSONArray jsonarrayShippingRate; ExpandableHeightListView shippingratelistview; ListViewAdapterShipping shippingrateadapter; ProgressDialog mProgressDialog; ArrayList<HashMap<String, String>> shippingratearraylist; public static String configuration_id = "configuration_id"; public static String shipping_title = "shipping_title"; public static String shipping_icon = "shipping_icon"; public static String shipping_price = "shipping_price"; public static String shipping_desc = "shipping_desc"; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View rootView = inflater.inflate(R.layout.checkoutlayout1, container, false); ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); //boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; if(isConnected){ getShippingRate(); }else{ nointernet(); } if(getArguments() != null) { String ccustomersid = getArguments().getString("customersid"); String ccountryid = getArguments().getString("countryid"); String cweightotal = getArguments().getString("weightotal"); String csubtotal = getArguments().getString("subtotal"); String cstateid = getArguments().getString("stateid"); customersid = ccustomersid; countryid = ccountryid; weightotal = cweightotal; subtotal = csubtotal; stateid = cstateid; } shippingratelistview = new ExpandableHeightListView(getActivity()); shippingratelistview = (ExpandableHeightListView) rootView.findViewById(R.id.shippinglist); //Toast.makeText(getActivity(),"custoid: "+customersid+" countryid: "+countryid+" weight: "+weightotal+"subtotal: "+subtotal+" stateid: "+stateid,Toast.LENGTH_SHORT).show(); showGlobalContextActionBar(); return rootView; } private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle("CHECKOUT"); } private ActionBar getActionBar() { return ((ActionBarActivity) getActivity()).getSupportActionBar(); } public void getShippingRate(){ class DownloadJSONShippingRate extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); // Create a progressdialog /*mProgressDialog = new ProgressDialog(getActivity()); // Set progressdialog title //mProgressDialog.setTitle(cname); // Set progressdialog message mProgressDialog.setMessage("Please wait..."); mProgressDialog.setIndeterminate(false); // Show progressdialog mProgressDialog.show();*/ mProgressDialog = ProgressDialog.show(getActivity(), null, null, true, false); mProgressDialog.setContentView(R.layout.progressdialog); } @Override protected String doInBackground(String... params) { ArrayList<NameValuePair> dataToSend = new ArrayList<>(); dataToSend.add(new BasicNameValuePair("customersid", customersid)); dataToSend.add(new BasicNameValuePair("countryid", countryid)); dataToSend.add(new BasicNameValuePair("stateid", stateid)); dataToSend.add(new BasicNameValuePair("weightotal", weightotal)); dataToSend.add(new BasicNameValuePair("subtotal", subtotal)); HttpParams httpRequestParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT); DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httppost = new HttpPost(SERVER_ADDRESS + "shippingrate.php"); // Depends on your web service //httppost.setHeader("Content-type", "application/json"); InputStream inputStream = null; String shippingrateresult = null; try { httppost.setEntity(new UrlEncodedFormEntity(dataToSend)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } shippingrateresult = sb.toString(); } catch (Exception e) { // Oops } finally { try{if(inputStream != null)inputStream.close();}catch(Exception squish){} } return shippingrateresult; } @Override protected void onPostExecute(String shippingrateresult){ myJSONShippingRate=shippingrateresult; try { // Locate the array name in JSON JSONObject jsonObjcart = new JSONObject(myJSONShippingRate); jsonarrayShippingRate = jsonObjcart.getJSONArray("shippingrate"); shippingratearraylist = new ArrayList<HashMap<String, String>>(); int qtySum = 0, qtyNum, tqtySum; for (int i = 0; i < jsonarrayShippingRate.length(); i++) { HashMap<String, String> lmap = new HashMap<String, String>(); JSONObject p = jsonarrayShippingRate.getJSONObject(i); // Retrive JSON Objects lmap.put("configuration_id", p.getString("configuration_id")); lmap.put("shipping_title", p.getString("shipping_title")); lmap.put("shipping_desc", p.getString("shipping_desc")); lmap.put("shipping_icon", p.getString("shipping_icon")); lmap.put("shipping_price", p.getString("shipping_price")); shippingratearraylist.add(lmap); } } catch (JSONException e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } shippingrateadapter = new ListViewAdapterShipping(getActivity(), shippingratearraylist); shippingratelistview.setAdapter(shippingrateadapter); shippingratelistview.setExpanded(true); // Close the progressdialog mProgressDialog.dismiss(); } } DownloadJSONShippingRate g = new DownloadJSONShippingRate(); g.execute(); } public void nointernet(){ AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); dialogBuilder.setMessage("There seems to be a problem with your connection."); dialogBuilder.setNegativeButton("Edit Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Stop the activity startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); } }); dialogBuilder.setPositiveButton("Reload", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Stop the activity HomeFragment homefragment = HomeFragment.newInstance(); FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, homefragment) .addToBackStack(null) .commit(); } }); AlertDialog dialog = dialogBuilder.show(); TextView messageText = (TextView)dialog.findViewById(android.R.id.message); messageText.setGravity(Gravity.CENTER); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(false); dialog.show(); } } ``` and my **listviewadaptershipping.java** ``` package com.example.administrator.mosbeau; import android.app.Activity; import android.app.AlertDialog; import android.app.FragmentManager; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONArray; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; /** * Created by Administrator on 11/9/2015. */ public class ListViewAdapterShipping extends BaseAdapter { boolean expanded = false; // Declare Variables Context context; LayoutInflater inflater; ArrayList<HashMap<String, String>> data; HashMap<String, String> resultp = new HashMap<String, String>(); public ListViewAdapterShipping(Context context, ArrayList<HashMap<String, String>> arraylist) { this.context = context; data = arraylist; } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } public View getView(final int position, View convertView, ViewGroup parent) { // Declare Variables TextView configuration_id; RadioButton shipping_title; ImageView shipping_icon; TextView shipping_price; TextView shipping_desc; inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = inflater.inflate(R.layout.shippingrate_item, parent, false); // Get the position resultp = data.get(position); // Locate the TextViews in product_gridview_item.xml configuration_id = (TextView) itemView.findViewById(R.id.textconfigurationid); shipping_title = (RadioButton) itemView.findViewById(R.id.radioShippingtitle); shipping_icon = (ImageView) itemView.findViewById(R.id.shipping_icon); shipping_price = (TextView) itemView.findViewById(R.id.textPrice); shipping_desc = (TextView) itemView.findViewById(R.id.textDesc); // Capture position and set results to the TextViews configuration_id.setText(resultp.get(CheckoutFragment1.configuration_id)); shipping_title.setText(resultp.get(CheckoutFragment1.shipping_title)); shipping_price.setText(resultp.get(CheckoutFragment1.shipping_price)); shipping_desc.setText(resultp.get(CheckoutFragment1.shipping_desc)); // Capture position and set results to the ImageView Glide.with(context).load(resultp.get(CheckoutFragment1.shipping_icon)).diskCacheStrategy(DiskCacheStrategy.ALL).into(shipping_icon); int color = 0xffffffff; itemView.setBackgroundColor(color); return itemView; } } ``` **now the problem is i want to click the radio button and get the textconfigurationid and pass to variable** please help me.. Thanks
2015/11/09
[ "https://Stackoverflow.com/questions/33606273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5392085/" ]
I cant understand your problem correctly, but what i guess you want to get value of RadioButton and TextView(textconfigurationid) to store in a variable. You can handle your click events in your `getView` method in the BaseAdapter. Something like this: ``` public View getView(final int position, View convertView, ViewGroup parent) { //*** Your code here.. ***// itemView.setBackgroundColor(color); //You can get value of radio button and textview like this. Boolean radioValue = shipping_title.isChecked(); int configId = configuration_id.getText(); return itemView; } ```
I solved my problem with this code.. ``` mconfiguration_id = configuration_id.getText().toString(); shipping_title.setTag(mconfiguration_id); shipping_title.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (position != mSelectedPosition && mSelectedRB != null) { mSelectedRB.setChecked(false); } mSelectedPosition = position; mSelectedRB = (RadioButton) v; String mconfiguration_id; mconfiguration_id = v.getTag().toString(); Toast.makeText(context, mconfiguration_id, Toast.LENGTH_SHORT).show(); } }); if(mSelectedPosition != position){ shipping_title.setChecked(false); }else{ shipping_title.setChecked(true); if(mSelectedRB != null && shipping_title != mSelectedRB){ mSelectedRB = shipping_title; } } ```
22,922,648
This is probably a very simple thing, but I'm very new to Javascript and HTML5 and can't seem to find an answer to my question. I'm currently developing an app for Samsung Smart TV. I currently have 2 major files: `Main.js` and `index.html`, in which most of my code is written. Also, I have a style sheet called `Main.css`. My problem: I have a button the screen, that when pressing it (that is, when pushing enter on the remote), I want the screen to change in to a completely different one (from welcome screen to admin settings). How do I do that?? Hope my question is not too general. Any help would be appreciated.
2014/04/07
[ "https://Stackoverflow.com/questions/22922648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3508451/" ]
You should divide your index.html with divs that represent a scene. To make it easy please use Basic Project it will generate a pattern to split the html/css/js like different pages and you only need to call `sf.scene.show("SettingsScene")` If you're using javascript project, then the answer from `user3384518` is the only way. Like i mentioned above, split your body to several divs and do hide/show the div
Your question is clear, but you don't say if you use a library (or not). So, if you use jQuery : ``` $('.myButtonName').click(function () { $('#myWelcomScreenDiv').hide(200, function () { $('#myAdminSettingsDiv').show(200); }); }); ``` But, if you would like to do something better, I recommend you to use a framework like Backbone.js or Angular.js.
17,218,177
I am following Adam Khoury's "**How to Build a Social Network Website**" tutorial, and I am on lesson 6, "**Sign Up Form and Email Activation PHP MySQL JavaScript Programming Tutorial**". Lesson and Code here: <http://www.developphp.com/view.php?tid=1294> After completing this lesson, I have a new user sign up form, but I am experiencing two issues. **1.** The form says the sign up is successful, it displays the proper confirmation message *"OK TestUser, check your email inbox and junk mail box at whatever@gmail.com in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account."*, however the user's details are not entered into the User database table where it should go. **2.** A confirmation email is not sent to the user's inbox (or junk mail for that matter) I am using bluehost.com as my server, and I have created the proper email address at bluehost (email address has been changed to "auto\_responder@myserver.com" in the code below for privacy reasons). This is my signup.php file: ``` <?php session_start(); // If user is logged in, header them away if(isset($_SESSION["username"])){ header("location: message.php?msg=NO to that weenis"); exit(); } ?><?php if(isset($_POST["usernamecheck"])){ include_once("php_includes/db_conx.php"); $username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']); $sql = "SELECT id FROM users WHERE username='$username' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $uname_check = mysqli_num_rows($query); if (strlen($username) < 3 || strlen($username) > 16) { echo '<strong style="color:#F00;">3 - 16 characters please</strong>'; exit(); } if (is_numeric($username[0])) { echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>'; exit(); } if ($uname_check < 1) { echo '<strong style="color:#009900;">' . $username . ' is OK</strong>'; exit(); } else { echo '<strong style="color:#F00;">' . $username . ' is taken</strong>'; exit(); } } ?><?php if(isset($_POST["u"])){ // CONNECT TO THE DATABASE include_once("php_includes/db_conx.php"); // GATHER THE POSTED DATA INTO LOCAL VARIABLES $u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']); $e = mysqli_real_escape_string($db_conx, $_POST['e']); $p = $_POST['p']; $g = preg_replace('#[^a-z]#', '', $_POST['g']); $c = preg_replace('#[^a-z ]#i', '', $_POST['c']); // GET USER IP ADDRESS $ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR')); // DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL $sql = "SELECT id FROM users WHERE username='$u' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $u_check = mysqli_num_rows($query); // ------------------------------------------- $sql = "SELECT id FROM users WHERE email='$e' LIMIT 1"; $query = mysqli_query($db_conx, $sql); $e_check = mysqli_num_rows($query); // FORM DATA ERROR HANDLING if($u == "" || $e == "" || $p == "" || $g == "" || $c == ""){ echo "The form submission is missing values."; exit(); } else if ($u_check > 0){ echo "The username you entered is alreay taken"; exit(); } else if ($e_check > 0){ echo "That email address is already in use in the system"; exit(); } else if (strlen($u) < 3 || strlen($u) > 16) { echo "Username must be between 3 and 16 characters"; exit(); } else if (is_numeric($u[0])) { echo 'Username cannot begin with a number'; exit(); } else { // END FORM DATA ERROR HANDLING // Begin Insertion of data into the database // Hash the password and apply your own mysterious unique salt /*$cryptpass = crypt($p); include_once ("php_includes/randStrGen.php"); $p_hash = randStrGen(20)."$cryptpass".randStrGen(20);*/ $p_hash = md5($p);//CHANGE THIS!!!!! // Add user info into the database table for the main site table $sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck) VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())"; $query = mysqli_query($db_conx, $sql); $uid = mysqli_insert_id($db_conx); // Establish their row in the useroptions table $sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')"; $query = mysqli_query($db_conx, $sql); // Create directory(folder) to hold each user's files(pics, MP3s, etc.) if (!file_exists("user/$u")) { mkdir("user/$u", 0755); } // Email the user their activation link $to = "$e"; $from = "auto_responder@myserver.com"; $subject = 'yoursitename Account Activation'; $message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><a href="http://www.yoursitename.com"><img src="http://www.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;"></a>yoursitename Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br /><a href="http://www.yoursitename.com/activation.php?id='.$uid.'&u='.$u.'&e='.$e.'&p='.$p_hash.'">Click here to activate your account now</a><br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>'; $headers = "From: $from\n"; $headers .= "MIME-Version: 1.0\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\n"; mail($to, $subject, $message, $headers); echo "signup_success"; exit(); } exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Sign Up</title> <link rel="icon" href="favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="style/style.css"> <style type="text/css"> #signupform{ margin-top:24px; } #signupform > div { margin-top: 12px; } #signupform > input,select { width: 200px; padding: 3px; background: #F3F9DD; } #signupbtn { font-size:18px; padding: 12px; } #terms { border:#CCC 1px solid; background: #F5F5F5; padding: 12px; } </style> <script src="js/main.js"></script> <script src="js/ajax.js"></script> <script> function restrict(elem){ var tf = _(elem); var rx = new RegExp; if(elem == "email"){ rx = /[' "]/gi; } else if(elem == "username"){ rx = /[^a-z0-9]/gi; } tf.value = tf.value.replace(rx, ""); } function emptyElement(x){ _(x).innerHTML = ""; } function checkusername(){ var u = _("username").value; if(u != ""){ _("unamestatus").innerHTML = 'checking ...'; var ajax = ajaxObj("POST", "signup.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { _("unamestatus").innerHTML = ajax.responseText; } } ajax.send("usernamecheck="+u); } } function signup(){ var u = _("username").value; var e = _("email").value; var p1 = _("pass1").value; var p2 = _("pass2").value; var c = _("country").value; var g = _("gender").value; var status = _("status"); if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){ status.innerHTML = "Fill out all of the form data"; } else if(p1 != p2){ status.innerHTML = "Your password fields do not match"; } else if( _("terms").style.display == "none"){ status.innerHTML = "Please view the terms of use"; } else { _("signupbtn").style.display = "none"; status.innerHTML = 'please wait ...'; var ajax = ajaxObj("POST", "signup.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText.replace(/^\s+|\s+$/g, "") == "signup_success"){ status.innerHTML = ajax.responseText; _("signupbtn").style.display = "block"; } else { window.scrollTo(0,0); _("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account."; } } } ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g); } } function openTerms(){ _("terms").style.display = "block"; emptyElement("status"); } /* function addEvents(){ _("elemID").addEventListener("click", func, false); } window.onload = addEvents; */ </script> </head> <body> <?php include_once("template_pageTop.php"); ?> <div id="pageMiddle"> <h3>Sign Up Here</h3> <form name="signupform" id="signupform" onSubmit="return false;"> <div>Username: </div> <input id="username" type="text" onBlur="checkusername()" onKeyUp="restrict('username')" maxlength="16"> <span id="unamestatus"></span> <div>Email Address:</div> <input id="email" type="text" onFocus="emptyElement('status')" onKeyUp="restrict('email')" maxlength="88"> <div>Create Password:</div> <input id="pass1" type="password" onFocus="emptyElement('status')" maxlength="16"> <div>Confirm Password:</div> <input id="pass2" type="password" onFocus="emptyElement('status')" maxlength="16"> <div>Gender:</div> <select id="gender" onFocus="emptyElement('status')"> <option value=""></option> <option value="m">Male</option> <option value="f">Female</option> </select> <div>Country:</div> <select id="country" onFocus="emptyElement('status')"> <?php include_once("template_country_list.php"); ?> </select> <div> <a href="#" onClick="return false" onMouseDown="openTerms()"> View the Terms Of Use </a> </div> <div id="terms" style="display:none;"> <h3>Web Intersect Terms Of Use</h3> <p>1. Play nice here.</p> <p>2. Take a bath before you visit.</p> <p>3. Brush your teeth before bed.</p> </div> <br /><br /> <button id="signupbtn" onClick="signup()">Create Account</button> <span id="status"></span> </form> </div> <?php include_once("template_pageBottom.php"); ?> </body> </html> ```
2013/06/20
[ "https://Stackoverflow.com/questions/17218177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1027012/" ]
You should not rely on Adam Khoury's "How To Build a Social Networks" tutorial. Half the code's just outdated, and not reliable. Too many SQL Injections can be done from that source. But the Ajax tutorials are pretty good and reliable too. It's a great way to start, BUT it should NOT be relied on. `mysql_` are way too outdated. I recommend using `PDO`. But yet again, this is an old question.
I am not sure if you found the answer but I was also experiencing this problem. 1) make sure the email from address is correct or you will not send them an email. Now the actual name doesn't need to be correct but the @Yourdomain.com does. many companies put in a false email address what is normally noreply@yourdomain.com and this doesn't actually have a inbox or the fact it does exist but no one checks it. I personally add that email address and do not bother making it as I would rather use my emails slots for something else. Just t clarify that using my method I have never experienced junk mail problems and all emails go to there inbox. 2) My user tables were not being written (but useroptions was) and I brought it down to the fact that in this code ``` // Add user info into the database table for the main site table $sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck) VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())"; ``` at the end it says now() well this needs to be changed to NOW() and make sure you change all the now() to NOW(). as soon as I done that the tables were getting written to also just double check to make sure your table name and rows in the data base match what you have in your code. if they do not match then just changed the names on your database I have added the names below to what your database names should be: users (Name of table), username (name of row in users table), email (name of row in users table), password (name of row in users table), gender (name of row in users table), country, (name of row in users table), ip (name of row in users table), signup (name of row in users table), lastlogin (name of row in users table), notescheck (name of row in users table). YOU WILL FIND MORE ROWS IN THAT TABLE THAT HAVE NOT BEEN LISTED BUT DO NOT WORRY AS THEY ARE ADDED TO IN LATER VIDEOS. I understand that this question was ask a year or so ago but I am posting so that you have the answer if you still want it and above all else anyone who has the same problem then you after I write this answer can also find the fix they need. If this doesn't fix you issue then post a reply and let me know and I will see if I can help you.
1,169,355
I need to do a Bin deployment on our ISP, Network Solutions. They have NET Framework 3.5 SP1 installed on their servers, but NOT ASP.NET MVC. I need to point my application to a directory called **cgi-bin** instead of bin. Network Solutions says that this is the only directory they have marked for execution as medium trust. I need to put the System.Web.Mvc DLL and the application DLL there, and I need my ASP.NET MVC application to find them in that directory. It goes without saying that they won't put them in the GAC for me. How do I tell my application to look in the cgi-bin directory instead of the bin directory for the DLL's? --- **Solution is posted below.**
2009/07/23
[ "https://Stackoverflow.com/questions/1169355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/102937/" ]
You should be able to set the output directory or your project to cgi-bin if you want. If you right-click your project and click on Properties. From there you should be able to select Build in the left list of options and set the output directory to whatever you want.
Try moving to another ISP that will allow you to have a BIN directory as part of you application folder.
1,169,355
I need to do a Bin deployment on our ISP, Network Solutions. They have NET Framework 3.5 SP1 installed on their servers, but NOT ASP.NET MVC. I need to point my application to a directory called **cgi-bin** instead of bin. Network Solutions says that this is the only directory they have marked for execution as medium trust. I need to put the System.Web.Mvc DLL and the application DLL there, and I need my ASP.NET MVC application to find them in that directory. It goes without saying that they won't put them in the GAC for me. How do I tell my application to look in the cgi-bin directory instead of the bin directory for the DLL's? --- **Solution is posted below.**
2009/07/23
[ "https://Stackoverflow.com/questions/1169355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/102937/" ]
After tinkering for awhile, I finally decided to deploy to an actual bin directory that I created (a procedure that Network Solutions says will not work) following [Phil Haacked's instructions](http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx) exactly, and it appears to be working. I did have to apply the routing patch described in [ASP.NET MVC: Default page works, but other pages return 404 error](https://stackoverflow.com/questions/1169492/asp-net-mvc-default-page-works-but-other-pages-return-404-error/1169555#1169555), because Network Solutions is still running IIS6. For those who are interested, you can specify a different bin directory in web.config like this: ``` <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="SomeFolder/bin" /> </assemblyBinding> </runtime> ``` I tried this with Network Solution's cgi-bin directory and my application did indeed find the mvc dll's.
You should be able to set the output directory or your project to cgi-bin if you want. If you right-click your project and click on Properties. From there you should be able to select Build in the left list of options and set the output directory to whatever you want.
1,169,355
I need to do a Bin deployment on our ISP, Network Solutions. They have NET Framework 3.5 SP1 installed on their servers, but NOT ASP.NET MVC. I need to point my application to a directory called **cgi-bin** instead of bin. Network Solutions says that this is the only directory they have marked for execution as medium trust. I need to put the System.Web.Mvc DLL and the application DLL there, and I need my ASP.NET MVC application to find them in that directory. It goes without saying that they won't put them in the GAC for me. How do I tell my application to look in the cgi-bin directory instead of the bin directory for the DLL's? --- **Solution is posted below.**
2009/07/23
[ "https://Stackoverflow.com/questions/1169355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/102937/" ]
After tinkering for awhile, I finally decided to deploy to an actual bin directory that I created (a procedure that Network Solutions says will not work) following [Phil Haacked's instructions](http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx) exactly, and it appears to be working. I did have to apply the routing patch described in [ASP.NET MVC: Default page works, but other pages return 404 error](https://stackoverflow.com/questions/1169492/asp-net-mvc-default-page-works-but-other-pages-return-404-error/1169555#1169555), because Network Solutions is still running IIS6. For those who are interested, you can specify a different bin directory in web.config like this: ``` <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="SomeFolder/bin" /> </assemblyBinding> </runtime> ``` I tried this with Network Solution's cgi-bin directory and my application did indeed find the mvc dll's.
Try moving to another ISP that will allow you to have a BIN directory as part of you application folder.
39,305,498
I would like to upgrade my Umbraco project on my localhost (and eventually my live website) from running on SQL Server CE to either SQL Server 2014 or SQL Server 2016. The reason for the upgrade is simple: I may at some point want to manage a website that has more than 4GB of data in the database, is scalable with multiple servers, and I'd like to back things up. Otherwise I'd be lazy and leave Umbraco.sdf alone. I have not found consistent documentation on this process anywhere. Perhaps one of you might be more experienced with SQL or Umbraco and could help out. (Aside: For those less familiar with Umbraco, Umbraco is a Content Management System written in C# and JavaScript. There's a SQL file in here named Umbraco.sdf which contents all of the website's contents. )
2016/09/03
[ "https://Stackoverflow.com/questions/39305498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4630250/" ]
[SQLCE ToolBox](https://sqlcetoolbox.codeplex.com/) is the best tool for the job. Just install the extension then the steps are as follows: 1. In Server Explorer add the connection to your new database (*Connect To Database* button) 2. Right click on `Umbraco.sdf` file in in the SQLCE ToolBox and choose *Migrate To SQL Server* 3. Choose your server and export. 4. Modify the umbracoDbDSN connection string to point at new database. The target database should be empty (or at least not have any conflicting table names).
It seems easiest to do it in webmatrix, have you tried that? From: <https://our.umbraco.org/forum/umbraco-7/using-umbraco-7/53818-Convert-Umbraco-SQL-CE-database-to-SQL-Express> or: <https://our.umbraco.org/forum/umbraco-7/using-umbraco-7/49519-Changing-database-in-Umbraco-7> > > First you need setup a database in SQL Server. Once that is done, then open the Webmatrix, and in the lower left corner in the webmatrix UI you can select the databas. Then browse to the SQL Server CE database, it's located in the `\App_Data` folder after that a "migrate button" will appear in the upper menu options. By press that button a migrate dialogue appears asking for connection details to the SQL Server database that you have created. > > >
39,305,498
I would like to upgrade my Umbraco project on my localhost (and eventually my live website) from running on SQL Server CE to either SQL Server 2014 or SQL Server 2016. The reason for the upgrade is simple: I may at some point want to manage a website that has more than 4GB of data in the database, is scalable with multiple servers, and I'd like to back things up. Otherwise I'd be lazy and leave Umbraco.sdf alone. I have not found consistent documentation on this process anywhere. Perhaps one of you might be more experienced with SQL or Umbraco and could help out. (Aside: For those less familiar with Umbraco, Umbraco is a Content Management System written in C# and JavaScript. There's a SQL file in here named Umbraco.sdf which contents all of the website's contents. )
2016/09/03
[ "https://Stackoverflow.com/questions/39305498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4630250/" ]
I figured this out, in case anyone else gets stuck. Here's how to do it: **Step 1**: Port over your current database. With Umbraco, there's an easy way of doing this. Simply install the Export SQL Server Compact package, an addon to your Umbraco CMS. Once installed, follow the directions and generate your SQL file. **Step 2**: Import the generated script to SQL Management Studio and run it in a new database. In order to do this: create a new database and give a new user permission settings to access that database (don't use your server login - you can, but it's better to create a user so you can access remotely). After that, go ahead and copy and paste your entire file (yes, that entire file) into a new query (right click the database -> run query), paste the script, and run it. **Step 3**: Change the connection string. This is in your web.config. Within the XML tags of , configure something akin to this (remove the {}): ``` <add name="umbracoDbDSN" connectionString="Data Source={the ip of your database};Initial Catalog={theDatabaseName};User Id={theUserId};Password={yourPassword}" providerName="System.Data.SqlClient" /> ``` The nice thing about this connection string is that you can edit locally, as well as on site, with the same connection string. This allows you to test code changes on your localhost, without changing the code on the website. The only thing that is linked automatically is CMS Content. Make sure not to delete your old Umbraco connection string, in case you want to revert back to it. Simply comment that out. **Step 4**: Encrypt the web.config. Clearly it's not wise to keep your database password in plaintext on your website. This MSDN on encrypting your web.config is invaluable. There are a few things you will lose with this: 1. Portability of your database. Sometimes you'll want to only have a file be a database instead of a whole server. We only recommend doing this step when your site is essentially done, as configuring a SQL Server and keeping it secure is an extra challenge you shouldn't worry about. 2. Occasionally, images don't transport. You might have to reinput all of your images manually. 3. Possible security. Every time you publish your website, you may have to reencrypt the web.config manually. This can be exceedingly dangerous - so make sure your website always has the web.config encrypted, even on new publishes.
It seems easiest to do it in webmatrix, have you tried that? From: <https://our.umbraco.org/forum/umbraco-7/using-umbraco-7/53818-Convert-Umbraco-SQL-CE-database-to-SQL-Express> or: <https://our.umbraco.org/forum/umbraco-7/using-umbraco-7/49519-Changing-database-in-Umbraco-7> > > First you need setup a database in SQL Server. Once that is done, then open the Webmatrix, and in the lower left corner in the webmatrix UI you can select the databas. Then browse to the SQL Server CE database, it's located in the `\App_Data` folder after that a "migrate button" will appear in the upper menu options. By press that button a migrate dialogue appears asking for connection details to the SQL Server database that you have created. > > >
39,305,498
I would like to upgrade my Umbraco project on my localhost (and eventually my live website) from running on SQL Server CE to either SQL Server 2014 or SQL Server 2016. The reason for the upgrade is simple: I may at some point want to manage a website that has more than 4GB of data in the database, is scalable with multiple servers, and I'd like to back things up. Otherwise I'd be lazy and leave Umbraco.sdf alone. I have not found consistent documentation on this process anywhere. Perhaps one of you might be more experienced with SQL or Umbraco and could help out. (Aside: For those less familiar with Umbraco, Umbraco is a Content Management System written in C# and JavaScript. There's a SQL file in here named Umbraco.sdf which contents all of the website's contents. )
2016/09/03
[ "https://Stackoverflow.com/questions/39305498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4630250/" ]
I figured this out, in case anyone else gets stuck. Here's how to do it: **Step 1**: Port over your current database. With Umbraco, there's an easy way of doing this. Simply install the Export SQL Server Compact package, an addon to your Umbraco CMS. Once installed, follow the directions and generate your SQL file. **Step 2**: Import the generated script to SQL Management Studio and run it in a new database. In order to do this: create a new database and give a new user permission settings to access that database (don't use your server login - you can, but it's better to create a user so you can access remotely). After that, go ahead and copy and paste your entire file (yes, that entire file) into a new query (right click the database -> run query), paste the script, and run it. **Step 3**: Change the connection string. This is in your web.config. Within the XML tags of , configure something akin to this (remove the {}): ``` <add name="umbracoDbDSN" connectionString="Data Source={the ip of your database};Initial Catalog={theDatabaseName};User Id={theUserId};Password={yourPassword}" providerName="System.Data.SqlClient" /> ``` The nice thing about this connection string is that you can edit locally, as well as on site, with the same connection string. This allows you to test code changes on your localhost, without changing the code on the website. The only thing that is linked automatically is CMS Content. Make sure not to delete your old Umbraco connection string, in case you want to revert back to it. Simply comment that out. **Step 4**: Encrypt the web.config. Clearly it's not wise to keep your database password in plaintext on your website. This MSDN on encrypting your web.config is invaluable. There are a few things you will lose with this: 1. Portability of your database. Sometimes you'll want to only have a file be a database instead of a whole server. We only recommend doing this step when your site is essentially done, as configuring a SQL Server and keeping it secure is an extra challenge you shouldn't worry about. 2. Occasionally, images don't transport. You might have to reinput all of your images manually. 3. Possible security. Every time you publish your website, you may have to reencrypt the web.config manually. This can be exceedingly dangerous - so make sure your website always has the web.config encrypted, even on new publishes.
[SQLCE ToolBox](https://sqlcetoolbox.codeplex.com/) is the best tool for the job. Just install the extension then the steps are as follows: 1. In Server Explorer add the connection to your new database (*Connect To Database* button) 2. Right click on `Umbraco.sdf` file in in the SQLCE ToolBox and choose *Migrate To SQL Server* 3. Choose your server and export. 4. Modify the umbracoDbDSN connection string to point at new database. The target database should be empty (or at least not have any conflicting table names).
64,534,787
First of All I was using the CQRS architecture for the back-end API and using NSWAG as an API connection; that generates API Endpoints in service proxy for the front-end Angular. I did simple validation for my POST API, while testing the created API the result was different in DevTools. In Network tab the validation that i expected was occured however in Console tab the result is different; As a matter of fact that result is i need. Here's my problem. In detail with image code for API call ``` saveLocationType(createLocationTypeCommand){ this.tenantService.createLocationType(createLocationTypeCommand).subscribe(result => { // Do Something }, error => { console.log(error); }) } ``` This is the validation result coming from my API in Network Tab that was correct. [![enter image description here](https://i.stack.imgur.com/5jVtI.png)](https://i.stack.imgur.com/5jVtI.png) This is my problem in Console the result here must be the same in Network Tab. [![enter image description here](https://i.stack.imgur.com/THODY.png)](https://i.stack.imgur.com/THODY.png) I believe the result in console was coming from service proxy since that's the one generates/formatting the APIs for the front-end. Is there a way to configure the generated service proxy of NSWAG? or is there other way to show the error message in Console tab same in Network Tab?
2020/10/26
[ "https://Stackoverflow.com/questions/64534787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11965929/" ]
I solved my problem using these reference: * <https://github.com/RicoSuter/NSwag/issues/2327> * <https://lurumad.github.io/problem-details-an-standard-way-for-specifying-errors-in-http-api-responses-asp.net-core> Snippet in C# Web API that i implemented to fixed my problem ``` [HttpPost("setup/locationType", Name = "createLocationType")] [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType(typeof(ValidationProblemDetails), (int)HttpStatusCode.BadRequest)] public async Task<IActionResult> CreateLocationTypeAsync([FromBody] CreateLocationTypeCommand command) { try { var commandResult = await _mediator.Send(command); if (!commandResult) { return BadRequest(); } return Ok(); } catch(Exception ex) { var problemDetails = new ValidationProblemDetails { Status = (int)HttpStatusCode.BadRequest, Type = "", Title = "Create Location Type", Detail = ex.Message, Instance = HttpContext.Request.Path }; return new ObjectResult(problemDetails) { ContentTypes = { "application/problem+json" }, StatusCode = (int)HttpStatusCode.BadRequest, }; } } ``` Thanks!
If you use the angular http client, try to use the responseType text option. ``` return this.http.post(url,body, {responseType: 'text'}).subscribe() ``` The client tries to handle the response as responseType: 'json' as default. He tries to parse this response as a json and fails and raises this error. More infos about non Json responsebodies you can find here: <https://angular.io/guide/http#requesting-non-json-data>
34,899
I've just noticed that the Google Maps for ExpressionEngine fieldtype no longer seems to be plotting markers onto the map for new entries in the control panel. When I enter a location and search, nothing happens. It should plot a marker on the map. I have a few sites that use this add-on, and the same issue is happening on each of them. Any ideas what's going wrong with this? I know the add-on is no longer supported, but if anyone has run into the same issue and knows a fix, please let me know. I suspect it might be a Google API change or even a call-back to the Objective HTML servers/services that is suddenly causing this issue. I'm using ExpressionEngine 2.7.2 and Google Maps for EE 3.3.8.
2015/12/01
[ "https://expressionengine.stackexchange.com/questions/34899", "https://expressionengine.stackexchange.com", "https://expressionengine.stackexchange.com/users/290/" ]
There seems to have been a recent change in the gmap API. See if [this thread](https://ellislab.com/forums/viewthread/248463/) can shed some light on your issue. Apparently changing ``` $this->EE->theme_loader->javascript('https://maps.google.com/maps/api/js?sensor=true'); ``` to ``` $this->EE->theme_loader->javascript('https://maps.google.com/maps/api/js?v=3.22&sensor=true'); ``` in `gmap/ft.gmap.php` might help.
I ran into the same issue multiple times. Most recently yesterday. [Creating an API key](https://developers.google.com/maps/documentation/javascript/get-api-key) and including it in the code solved my issue. After you create a key and set your credentials (make sure you add your domain) edit ft.gmap (expressionengine > third\_party > gmap > ft.gmap.php) and change the following line: ``` $this->EE->theme_loader->javascript('https://maps.google.com/maps/api/js?v=3.22&sensor=true'); ``` to ``` $this->EE->theme_loader->javascript('https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_GOES_HERE&sensor=true'); ``` If you need help with a key [see these Google directions](https://developers.google.com/maps/documentation/javascript/get-api-key).
222,084
How to update a list row by matching one of the columns of the row using REST API. Let's say I have a list with column1, column2, and column3. Now I want to search "value5" in "column1" and if "value5" found in a column1 update this row. I have got this REST API to directly update any specific item by passing the item id: ``` /_api/web/lists/getbytitle('${listname}')/items(itemId); ``` But this is not exactly what I am looking for. Can someone help me out with this? Thanks in advance!
2017/07/31
[ "https://sharepoint.stackexchange.com/questions/222084", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/61794/" ]
If you want an exact match, use the `eq` operator or if you want use `contains` use the `substringof` operator. So, first make a REST API GET call to either of the below url: ``` /_api/web/lists/getbytitle('${listname}')/items?$select=ID&$filter=column1 eq 'value5' ``` or ``` /_api/web/lists/getbytitle('${listname}')/items?$select=ID&$filter=substringof('value5,column1) ``` This will fetch you the list items(s) matching your condition. In the JSON response, you will also get the list item's ID. Now, pass this item id in your mentioned REST API call to update the list item ``` /_api/web/lists/getbytitle('${listname}')/items("<value of item id received in previous call>") ```
You can not do it at single request. You need at least two requests. Find Item ========= You need to use `$filter` to find your desired item. ``` /_api/web/lists/getbytitle('${listname}')/items?$filter=column1 eq 'value5' ``` Make a GET request to the aforementioned endpoint. It will return your desired item if it exists. Update Item =========== Now you know the item id from the above request. Thus, you can update it using the following endpoint. ``` /_api/web/lists/getbytitle('${listname}')/items(itemId) ``` **NB:** Spend some time to study the basic of [REST API and SharePoint](https://www.codeproject.com/Articles/990131/CRUD-Operation-to-List-Using-SharePoint-Rest-API).
222,084
How to update a list row by matching one of the columns of the row using REST API. Let's say I have a list with column1, column2, and column3. Now I want to search "value5" in "column1" and if "value5" found in a column1 update this row. I have got this REST API to directly update any specific item by passing the item id: ``` /_api/web/lists/getbytitle('${listname}')/items(itemId); ``` But this is not exactly what I am looking for. Can someone help me out with this? Thanks in advance!
2017/07/31
[ "https://sharepoint.stackexchange.com/questions/222084", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/61794/" ]
There is no direct way to update all the items in one go using REST api. You can consider following steps in order to achieve what your requirements. 1. Get all the items where column match value using REST query i.e. `[url to site coll]/_api/web/lists/getByTitle('Title of list')/items?$filter=Column_Internal_Name eq 'Value of column'`. Note, in case its a number field dont use `'` symbol in value. 2. Use JQuery/JS to loop all the items. 3. Inside loop, create a new item based on the item you received, update the column value to the desired value. 4. Now to the newly item created in step 3, attach another property i.e. metadata property. Its look like `__metadata: {type: "SP.Data.ListInternalNameListItem"}`. You need to replace `ListInternalName` with the internal name of list and keep item `ListItem` at the end of it. 5. Prepare an AJAX request to post this item. The end point will be as in step 1, only you need to remove complete query string. That's it, your task is done. Now wait for all queries to come with response. Tip: If you are using JQuery, you can use its `$.ajaxStart` and `$.ajaxStop` to track concurrent AJAX requests.
You can not do it at single request. You need at least two requests. Find Item ========= You need to use `$filter` to find your desired item. ``` /_api/web/lists/getbytitle('${listname}')/items?$filter=column1 eq 'value5' ``` Make a GET request to the aforementioned endpoint. It will return your desired item if it exists. Update Item =========== Now you know the item id from the above request. Thus, you can update it using the following endpoint. ``` /_api/web/lists/getbytitle('${listname}')/items(itemId) ``` **NB:** Spend some time to study the basic of [REST API and SharePoint](https://www.codeproject.com/Articles/990131/CRUD-Operation-to-List-Using-SharePoint-Rest-API).