qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
61,916,754
During request GET in Postman (<https://localhost:9001/test>) I've received an error: *Error: write EPROTO 8768:error:1408F10B:SSL **routines:ssl3\_get\_record:wrong version number**:c:\users\administrator\buildkite-agent\builds\pm-electron\postman\electron-release\vendor\node\deps\openssl\openssl\ssl\record\ssl3\_record.c:252:* *Warning: This request did not get sent completely and might not have all the required system headers*. Postman Configuration: * SSL certificate verification is disabled; * Proxy configuration - Default Proxy Configuration and Proxy configurations for sending requests are disabled; * Request timeout in ms - 0.
2020/05/20
[ "https://Stackoverflow.com/questions/61916754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730856/" ]
it has to be the http not https for localhost "http://localhost:3000" NOT "https://localhost:3000"
the reason was in an incorrect link. In the controller I have used @RequestMapping(value="/{baseSiteId}/test") And this {baseSiteId} was not what I expected.
61,916,754
During request GET in Postman (<https://localhost:9001/test>) I've received an error: *Error: write EPROTO 8768:error:1408F10B:SSL **routines:ssl3\_get\_record:wrong version number**:c:\users\administrator\buildkite-agent\builds\pm-electron\postman\electron-release\vendor\node\deps\openssl\openssl\ssl\record\ssl3\_record.c:252:* *Warning: This request did not get sent completely and might not have all the required system headers*. Postman Configuration: * SSL certificate verification is disabled; * Proxy configuration - Default Proxy Configuration and Proxy configurations for sending requests are disabled; * Request timeout in ms - 0.
2020/05/20
[ "https://Stackoverflow.com/questions/61916754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730856/" ]
For Localhost we don't really need https, please try with <http://localhost:9001/test>
``` const transporter = nodemailer.createTransport({ host:'smtp.gmail.com', port:587, secure:false, requireTLC:true, auth: { user:'youmail@gmail.com', pass:'youpass' } } ``` Notice that `secure:` is `false`. The error occurs when `secure:` is `true`.
61,916,754
During request GET in Postman (<https://localhost:9001/test>) I've received an error: *Error: write EPROTO 8768:error:1408F10B:SSL **routines:ssl3\_get\_record:wrong version number**:c:\users\administrator\buildkite-agent\builds\pm-electron\postman\electron-release\vendor\node\deps\openssl\openssl\ssl\record\ssl3\_record.c:252:* *Warning: This request did not get sent completely and might not have all the required system headers*. Postman Configuration: * SSL certificate verification is disabled; * Proxy configuration - Default Proxy Configuration and Proxy configurations for sending requests are disabled; * Request timeout in ms - 0.
2020/05/20
[ "https://Stackoverflow.com/questions/61916754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730856/" ]
For Localhost we don't really need https, please try with <http://localhost:9001/test>
check that you are using the `HTTP` protocol not `HTTPS` to send requests to the server: ### example ```js export const config = { baseUrl: "http://localhost:4000" } ```
61,916,754
During request GET in Postman (<https://localhost:9001/test>) I've received an error: *Error: write EPROTO 8768:error:1408F10B:SSL **routines:ssl3\_get\_record:wrong version number**:c:\users\administrator\buildkite-agent\builds\pm-electron\postman\electron-release\vendor\node\deps\openssl\openssl\ssl\record\ssl3\_record.c:252:* *Warning: This request did not get sent completely and might not have all the required system headers*. Postman Configuration: * SSL certificate verification is disabled; * Proxy configuration - Default Proxy Configuration and Proxy configurations for sending requests are disabled; * Request timeout in ms - 0.
2020/05/20
[ "https://Stackoverflow.com/questions/61916754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730856/" ]
For Localhost we don't really need https, please try with <http://localhost:9001/test>
it has to be the http not https for localhost "http://localhost:3000" NOT "https://localhost:3000"
61,916,754
During request GET in Postman (<https://localhost:9001/test>) I've received an error: *Error: write EPROTO 8768:error:1408F10B:SSL **routines:ssl3\_get\_record:wrong version number**:c:\users\administrator\buildkite-agent\builds\pm-electron\postman\electron-release\vendor\node\deps\openssl\openssl\ssl\record\ssl3\_record.c:252:* *Warning: This request did not get sent completely and might not have all the required system headers*. Postman Configuration: * SSL certificate verification is disabled; * Proxy configuration - Default Proxy Configuration and Proxy configurations for sending requests are disabled; * Request timeout in ms - 0.
2020/05/20
[ "https://Stackoverflow.com/questions/61916754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730856/" ]
check that you are using the `HTTP` protocol not `HTTPS` to send requests to the server: ### example ```js export const config = { baseUrl: "http://localhost:4000" } ```
``` const transporter = nodemailer.createTransport({ host:'smtp.gmail.com', port:587, secure:false, requireTLC:true, auth: { user:'youmail@gmail.com', pass:'youpass' } } ``` Notice that `secure:` is `false`. The error occurs when `secure:` is `true`.
61,916,754
During request GET in Postman (<https://localhost:9001/test>) I've received an error: *Error: write EPROTO 8768:error:1408F10B:SSL **routines:ssl3\_get\_record:wrong version number**:c:\users\administrator\buildkite-agent\builds\pm-electron\postman\electron-release\vendor\node\deps\openssl\openssl\ssl\record\ssl3\_record.c:252:* *Warning: This request did not get sent completely and might not have all the required system headers*. Postman Configuration: * SSL certificate verification is disabled; * Proxy configuration - Default Proxy Configuration and Proxy configurations for sending requests are disabled; * Request timeout in ms - 0.
2020/05/20
[ "https://Stackoverflow.com/questions/61916754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730856/" ]
it has to be the http not https for localhost "http://localhost:3000" NOT "https://localhost:3000"
``` const transporter = nodemailer.createTransport({ host:'smtp.gmail.com', port:587, secure:false, requireTLC:true, auth: { user:'youmail@gmail.com', pass:'youpass' } } ``` Notice that `secure:` is `false`. The error occurs when `secure:` is `true`.
67,760,554
``` <script lang="ts"> import { Vue, Component } from 'vue-property-decorator' @Component export default class Index extends Vue { form = { name: '', adress: '', age: '', items: [], } async fetch() { this.form.items = await fetch('https://api.nuxtjs.dev/posts').then(c => c.json()) console.log(this.form.items) } fetchOnServer = true; changeLanguage(language: string) { this.$i18n.setLocale(language); } } </script> ``` async fetch dont work in class component If I use a standard component it works fine. But if I use a class component, the function call stops working. What is the problem and how can it be fixed
2021/05/30
[ "https://Stackoverflow.com/questions/67760554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11069116/" ]
```js const items = [{color: "red"}, {color: "blue"}, {color: "green"}, {color: "orange"}, {color: "blue"}]; const orderedColorsArr = [ ...items.filter(({color}) => color==="blue"), ...items.filter(({color}) => color!=="blue") ].map(({color}) => color); const res = [orderedColorsArr.join(", ")]; console.log(res) ```
First of all, you need an array with the colors, then you need to access the strings instead of not given properties and then sort only by the delta of the comparisons with the wanted top color. ```js const items = [{ color: "red" }, { color: "green" }, { color: "orange" }, { color: "blue" }] items.sort((a, b) => (b.color === 'blue') - (a.color === 'blue')); console.log(items); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` For unstable environments ```js const items = [{ color: "red" }, { color: "green" }, { color: "orange" }, { color: "blue" }], order = items.reduce((m, o, i) => m.set(o, i + 1), new Map); items.sort((a, b) => (b.color === 'blue') - (a.color === 'blue') || order.get(a) - order.get(b) ); console.log(items); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
67,760,554
``` <script lang="ts"> import { Vue, Component } from 'vue-property-decorator' @Component export default class Index extends Vue { form = { name: '', adress: '', age: '', items: [], } async fetch() { this.form.items = await fetch('https://api.nuxtjs.dev/posts').then(c => c.json()) console.log(this.form.items) } fetchOnServer = true; changeLanguage(language: string) { this.$i18n.setLocale(language); } } </script> ``` async fetch dont work in class component If I use a standard component it works fine. But if I use a class component, the function call stops working. What is the problem and how can it be fixed
2021/05/30
[ "https://Stackoverflow.com/questions/67760554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11069116/" ]
```js const items = [{color: "red"}, {color: "blue"}, {color: "green"}, {color: "orange"}, {color: "blue"}]; const orderedColorsArr = [ ...items.filter(({color}) => color==="blue"), ...items.filter(({color}) => color!=="blue") ].map(({color}) => color); const res = [orderedColorsArr.join(", ")]; console.log(res) ```
Well, it doesn't look like you're sorting anything here. So why even use sort? Try something like splicing the "blue" element off after getting the index from an indexOf function, then just inserting it at the beginning off the array. ``` let items= [ {color: "red"}, {color: "green"}, {color: "orange"}, {color: "blue"} ]; const removedElement = items.splice(items.indexOf({color: "blue"}),1); //or alternatively items.unshift(removedElement[0]) items= [...removedElement,...items].map(item=> item.color).join(","); const result = [items] console.log(result); //["blue,red,green,orange"] ``` Another approach you could take is, filter out the non blue elements, filter out the blue elements and just make a new array with these two. ``` const result = [[...items.filter(item => item.color==="blue"), ...items.filter(item => item.color!=="blue")].map(item=>item.color).join(",")]; console.log(result); // ["blue,red,green,orange"] ```
67,760,554
``` <script lang="ts"> import { Vue, Component } from 'vue-property-decorator' @Component export default class Index extends Vue { form = { name: '', adress: '', age: '', items: [], } async fetch() { this.form.items = await fetch('https://api.nuxtjs.dev/posts').then(c => c.json()) console.log(this.form.items) } fetchOnServer = true; changeLanguage(language: string) { this.$i18n.setLocale(language); } } </script> ``` async fetch dont work in class component If I use a standard component it works fine. But if I use a class component, the function call stops working. What is the problem and how can it be fixed
2021/05/30
[ "https://Stackoverflow.com/questions/67760554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11069116/" ]
First of all, you need an array with the colors, then you need to access the strings instead of not given properties and then sort only by the delta of the comparisons with the wanted top color. ```js const items = [{ color: "red" }, { color: "green" }, { color: "orange" }, { color: "blue" }] items.sort((a, b) => (b.color === 'blue') - (a.color === 'blue')); console.log(items); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ``` For unstable environments ```js const items = [{ color: "red" }, { color: "green" }, { color: "orange" }, { color: "blue" }], order = items.reduce((m, o, i) => m.set(o, i + 1), new Map); items.sort((a, b) => (b.color === 'blue') - (a.color === 'blue') || order.get(a) - order.get(b) ); console.log(items); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
Well, it doesn't look like you're sorting anything here. So why even use sort? Try something like splicing the "blue" element off after getting the index from an indexOf function, then just inserting it at the beginning off the array. ``` let items= [ {color: "red"}, {color: "green"}, {color: "orange"}, {color: "blue"} ]; const removedElement = items.splice(items.indexOf({color: "blue"}),1); //or alternatively items.unshift(removedElement[0]) items= [...removedElement,...items].map(item=> item.color).join(","); const result = [items] console.log(result); //["blue,red,green,orange"] ``` Another approach you could take is, filter out the non blue elements, filter out the blue elements and just make a new array with these two. ``` const result = [[...items.filter(item => item.color==="blue"), ...items.filter(item => item.color!=="blue")].map(item=>item.color).join(",")]; console.log(result); // ["blue,red,green,orange"] ```
5,450,607
I need a XML library for constructing simple XML messages. I come from a Java background. I've found some suggestions pointing at Xerces-C++ XML library as it was transferred. Other suggested libraries have their advantages in memory in speed, but all of this is none of my needs. I need an API which supports an easy construction. Furthermore I would like to ask when sending XML via sockets, do I have to pay attention on serialization or can I send plain xml texts? Overall the focus is on building xml and none parsing at all.
2011/03/27
[ "https://Stackoverflow.com/questions/5450607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658718/" ]
A simple XML library would be TinyXML, see <http://www.grinninglizard.com/tinyxmldocs/tutorial0.html> for an example (under section 'Building Documents Programatically') edit: If the XML is really simple, you can also just output the XML tags from your code. Something like: ``` std::stringstream s; s << "<tag>" << var << "</tag>\n"; std::cout << s.str(); ```
[RapidXML](http://rapidxml.sourceforge.net/) > > RapidXml is an attempt to create the fastest XML parser possible, while retaining useability, portability and reasonable W3C compatibility. > > > You will build your XML file in RAM, and at any time you can convert it to a string and from that, an array of chars, meaning you will send the XML file as an array of bytes.
5,450,607
I need a XML library for constructing simple XML messages. I come from a Java background. I've found some suggestions pointing at Xerces-C++ XML library as it was transferred. Other suggested libraries have their advantages in memory in speed, but all of this is none of my needs. I need an API which supports an easy construction. Furthermore I would like to ask when sending XML via sockets, do I have to pay attention on serialization or can I send plain xml texts? Overall the focus is on building xml and none parsing at all.
2011/03/27
[ "https://Stackoverflow.com/questions/5450607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658718/" ]
A simple XML library would be TinyXML, see <http://www.grinninglizard.com/tinyxmldocs/tutorial0.html> for an example (under section 'Building Documents Programatically') edit: If the XML is really simple, you can also just output the XML tags from your code. Something like: ``` std::stringstream s; s << "<tag>" << var << "</tag>\n"; std::cout << s.str(); ```
My suggestion [tinyxml](http://www.grinninglizard.com/tinyxml/) Excellent performance and easy to use. Usage : [TinyXML Tutorial](http://www.grinninglizard.com/tinyxmldocs/tutorial0.html) or [libtinyxml](https://code.google.com/p/libtinyxml/) The TinyXML library provided with a CMake Build System.
5,450,607
I need a XML library for constructing simple XML messages. I come from a Java background. I've found some suggestions pointing at Xerces-C++ XML library as it was transferred. Other suggested libraries have their advantages in memory in speed, but all of this is none of my needs. I need an API which supports an easy construction. Furthermore I would like to ask when sending XML via sockets, do I have to pay attention on serialization or can I send plain xml texts? Overall the focus is on building xml and none parsing at all.
2011/03/27
[ "https://Stackoverflow.com/questions/5450607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658718/" ]
A simple XML library would be TinyXML, see <http://www.grinninglizard.com/tinyxmldocs/tutorial0.html> for an example (under section 'Building Documents Programatically') edit: If the XML is really simple, you can also just output the XML tags from your code. Something like: ``` std::stringstream s; s << "<tag>" << var << "</tag>\n"; std::cout << s.str(); ```
It seems like [pugixml](https://github.com/zeux/pugixml) library is [fastest](http://pugixml.org/benchmark.html) though fullyfunctional, object-oriented C++ library, with support of XPath queries.
5,450,607
I need a XML library for constructing simple XML messages. I come from a Java background. I've found some suggestions pointing at Xerces-C++ XML library as it was transferred. Other suggested libraries have their advantages in memory in speed, but all of this is none of my needs. I need an API which supports an easy construction. Furthermore I would like to ask when sending XML via sockets, do I have to pay attention on serialization or can I send plain xml texts? Overall the focus is on building xml and none parsing at all.
2011/03/27
[ "https://Stackoverflow.com/questions/5450607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658718/" ]
My suggestion [tinyxml](http://www.grinninglizard.com/tinyxml/) Excellent performance and easy to use. Usage : [TinyXML Tutorial](http://www.grinninglizard.com/tinyxmldocs/tutorial0.html) or [libtinyxml](https://code.google.com/p/libtinyxml/) The TinyXML library provided with a CMake Build System.
[RapidXML](http://rapidxml.sourceforge.net/) > > RapidXml is an attempt to create the fastest XML parser possible, while retaining useability, portability and reasonable W3C compatibility. > > > You will build your XML file in RAM, and at any time you can convert it to a string and from that, an array of chars, meaning you will send the XML file as an array of bytes.
5,450,607
I need a XML library for constructing simple XML messages. I come from a Java background. I've found some suggestions pointing at Xerces-C++ XML library as it was transferred. Other suggested libraries have their advantages in memory in speed, but all of this is none of my needs. I need an API which supports an easy construction. Furthermore I would like to ask when sending XML via sockets, do I have to pay attention on serialization or can I send plain xml texts? Overall the focus is on building xml and none parsing at all.
2011/03/27
[ "https://Stackoverflow.com/questions/5450607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658718/" ]
My suggestion [tinyxml](http://www.grinninglizard.com/tinyxml/) Excellent performance and easy to use. Usage : [TinyXML Tutorial](http://www.grinninglizard.com/tinyxmldocs/tutorial0.html) or [libtinyxml](https://code.google.com/p/libtinyxml/) The TinyXML library provided with a CMake Build System.
It seems like [pugixml](https://github.com/zeux/pugixml) library is [fastest](http://pugixml.org/benchmark.html) though fullyfunctional, object-oriented C++ library, with support of XPath queries.
49,188,557
I have the following jobs configuration in `.gitlab-ci.yml`: ``` job1: stage: test services: - name: mariadb alias: mysql entrypoint: [""] command: [...] script: - ... job2: stage: test services: - name: mariadb alias: mysql entrypoint: [""] command: [...] script: - ... job3: stage: test services: - name: mariadb alias: mysql entrypoint: [""] command: [...] script: - ... ``` `services` portion is the same for all 3 jobs. Is it possible to avoid this duplication?
2018/03/09
[ "https://Stackoverflow.com/questions/49188557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7637120/" ]
You can also utilize Anchors YAML feature - <https://docs.gitlab.com/ee/ci/yaml/#anchors> . ``` .job_template: &job_definition services: - name: mariadb alias: mysql entrypoint: [""] command: [...] job1: <<: *job_definition stage: test ``` When the config is common for all jobs, use global service. When you want to avoid duplication among only some jobs, use YAML anchors.
Just define it outside the jobs: <https://docs.gitlab.com/ce/ci/docker/using_docker_images.html#define-image-and-services-from-gitlab-ci-yml> ``` services: - name: mariadb alias: mysql entrypoint: [""] command: [...] job1: stage: test script: - ... job2: stage: test script: - ... job3: stage: test script: - ... ```
49,188,557
I have the following jobs configuration in `.gitlab-ci.yml`: ``` job1: stage: test services: - name: mariadb alias: mysql entrypoint: [""] command: [...] script: - ... job2: stage: test services: - name: mariadb alias: mysql entrypoint: [""] command: [...] script: - ... job3: stage: test services: - name: mariadb alias: mysql entrypoint: [""] command: [...] script: - ... ``` `services` portion is the same for all 3 jobs. Is it possible to avoid this duplication?
2018/03/09
[ "https://Stackoverflow.com/questions/49188557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7637120/" ]
You can also utilize Anchors YAML feature - <https://docs.gitlab.com/ee/ci/yaml/#anchors> . ``` .job_template: &job_definition services: - name: mariadb alias: mysql entrypoint: [""] command: [...] job1: <<: *job_definition stage: test ``` When the config is common for all jobs, use global service. When you want to avoid duplication among only some jobs, use YAML anchors.
You can use `extends` which was introduced in **GitLab 11.3**. It is an alternative to using [YAML anchors](https://docs.gitlab.com/ee/ci/yaml/#anchors) and is a little more flexible and readable. ``` .db_services: services: - name: mariadb alias: mysql entrypoint: [""] command: [...] job1: extends: .db_services stage: test ... ``` Source: [Using extends in Gitlab CI](https://docs.gitlab.com/ee/ci/yaml/#extends)
15,124,501
I have been assigned the task of fixing an older php site since it has been moved to a newer server. The server it is on now doesn't allow globalized variables and that's pretty much all this site was running off of. When trying to upload an image, my sql statement is showing everything but the id for the listing I am adding the image to. I was hoping someone could help me figure this out. This is my upload function: ``` function upload(){ global $imagefolder, $id; global $tbl_units; include "globalizePOSTGET.php"; // $uid = uuid(); $minsize = 5000; // 5kb $maxsize = 3000000; // 3mb $ext = explode('.',basename($_FILES['userfile']['name'])); $ext = $ext[count($ext)-1]; $ext = strtolower($ext); if ($ext != "jpg" && $ext != "jpeg" && $ext != "png") { echo "<script> alert('Image is not a png or jpeg format'); </script>"; return false; } $imagename = $_POST['id']."_img".$_FILES['img'].".$ext"; $imagename2 = "X_".$imagename; $uploadfile = $imagefolder . $imagename; $uploadfile2 = $imagefolder . $imagename2; $uploadthumb = $imagefolder . "tn_" . $imagename; if (file_exists($uploadfile)) unlink($uploadfile); if (file_exists($uploadthumb)) unlink($uploadthumb); if (file_exists($uploadfile)) { echo "<script> alert('Image already exists!'); </script>"; } else { if(is_uploaded_file($_FILES['userfile']['tmp_name'])) { // check the file is less than the maximum file size if($_FILES['userfile']['size'] < $maxsize) { $imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name'])); // prepare the image for insertion $size = getimagesize($_FILES['userfile']['tmp_name']); // get the image info.. if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile2)) { $Image = @imagecreatefromjpeg($uploadfile2); if ($Image) { $img_height = imagesy($Image); $img_width = imagesx($Image); imagedestroy($Image); } if ($img_height > $img_width) { // portrait $tempMultiplier = 150 / $img_height; $tempMultiplierFull = 600 / $img_height; } else { $tempMultiplier = 150 / $img_width; $tempMultiplierFull = 600 / $img_width; } $imageHeight = $img_height * $tempMultiplier; $imageWidth = $img_width * $tempMultiplier; $fullimageHeight = $img_height * $tempMultiplierFull; $fullimageWidth = $img_width * $tempMultiplierFull; createthumb($imagename2,"tn_".$imagename,$imageWidth,$imageHeight); if($_FILES['userfile']['size'] > $minsize) { createthumb($imagename2,$imagename,$fullimageWidth,$fullimageHeight); if (file_exists($uploadfile2)) unlink($uploadfile2); } else { rename($uploadfile2, $uploadfile); } $sql = "UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id']; echo $sql; if(!mysql_query($sql)) { echo "<script> alert('Unable to upload file'); </script>"; } else { ?> <script>location.replace('memonly.php?action=edit_record&id=<?php echo $id; ?>');</script> <?php } } } else { // if the file is not less than the maximum allowed, print an error $file_n = basename($_FILES['userfile']['name']); $file_s = $_FILES['userfile']['size']; ?> <script> alert("File exceeds the maximum limit of <?php echo $maxsize; ?>\nFile <?php echo $file_n; ?> is <?php echo $file_s; ?>");</script> <?php } } } } ``` I am echoing the sql statement on the line that is giving me the error, I think. After clicking on submit, the page tells me `Unable to upload file'. Which is why I echoed the sql there. I end up with a sql statement looking like this:`UPDATE member\_units SET photo = "\_img.jpg" WHERE id = ` Someone please help me! I am very inexperienced in PHP and I have no idea what to do here. Here is the form that is doing the uploading: ``` <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <input type="hidden" name="_submit_check" value="1" /> <input type="hidden" name="id" value="<?php echo $id; ?>" /> <input type="hidden" name="img" value="<?php echo $img; ?>" /> Image URL: <input type="file" name="userfile" value="" style="font-size: 10px; width: 100%;"> <input type="submit" value="Submit" onClick="return validate();">&nbsp; <input type="button" value="Cancel" onClick="location.href='/memonly.php?action=edit_record<?php echo "&id=$id&memberid=$memberid"; ?>';"> </form> ```
2013/02/27
[ "https://Stackoverflow.com/questions/15124501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/880688/" ]
The first thing you need to do with this kind of problem is work through where the issues seem to be happening. So take your echoed statement... > > UPDATE member\_units SET photo = "\_img.jpg" WHERE id = ` > > > This corresponds to... ``` UPDATE $tbl_units SET photo".$_FILES['img']." = \"" . $imagename . "\" WHERE id = " . $_POST['id']; ``` We can see by comparison that it is clear that $\_FILES['img'] is and empty variable as far as converting it to a string goes. The same is said for $\_POST['id'], while $imagename gives a short **\_img.jpg** file name. Tracking back you can then see that $imagename comes from... ``` $_POST['id']."_img".$_FILES['img'].".$ext"; ``` This is where your **photo = "\_img.jpg"** comes from. Again, $\_FILES['img'] and $\_POST['id'] The fact that you're reaching the echo statement means that something is uploading, but it is through the $\_FILES['userfile'] array, with all of it's associated variables, for example $\_FILES['userfile']['name'] which would give you the filename of the image being uploaded. What you need to ask yourself next is where you are expecting $\_POST['id'] to come from, since it is missing or empty, and what field in your HTML form delivers that variable. Then you need to ask yourself what you are trying to achieve with your naming system. For example if you want an image file to look like: 1\_imgLolCat.jpg then your variable will need to look more like ``` $imagename = $_POST['id']."_img".$_FILES['userfile']['name']; ``` However the final part of my answer below makes me think that instead of the file name, what you're looking for is actually a POST variable that denotes a category or type of image, in which case you may want to work from... ``` $imagename = $_POST['id']."_img".$_POST['img'].".$ext"; ``` ...if a HTML field exists with the name "img"! Finally take a look at your SQL statement... ``` SET photo".$_FILES['img']." = \"" . $imagename . "\" ``` And double check your tables, since what you appear to be trying to do is set a unique variable in your table that would depend on something passed from the form. I may be wrong here but I assume (as I said above) you want $\_POST['img'] in there. Word of warning, you need...**NEED** to sanitise these variables before you input them in to a SQL statement like this. Someone could easily take ``` SET photo".$_POST['img'] ``` and delete your whole table if permissions were set up for your database use to do so. There are plenty of other answers around as to how to do this properly. :)
It seems like 'id' field is not sent in the HTML form. I guess it should be a hidden input ? Be careful, your script can be the target of an SQL injection : you use a user input ($\_POST['id']) directly in an SQL query. You should check if this input is actually set and numeric.
23,854,157
I have a fluid image `width: 100%` fixed to the top of my page. When a user scrolls down the page the text scrolls over the image. See this jsfiddle for a [demo](http://jsfiddle.net/qhs6h/5/show) and my [code](http://jsfiddle.net/qhs6h/5/). This is what I want to happen. The problem I'm having is when the user has not scrolled yet (i.e. on page load) and browser is a certain width, the image isn't cleared by the page text (the page text overlaps the image). How do I ensure my page text clears the image at all screen sizes?
2014/05/25
[ "https://Stackoverflow.com/questions/23854157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709033/" ]
Its not about re-inventing the wheel or being more 'javascriptic'. You simply have many options to achieve the same goal. Javascript: ``` function grow(parent, tagName) { var node = document.createElement(tagName); //notice, the jQuery wrapper was removed as it is not needed parent.appendChild(node); return node; } function attach(parent_instance, text) { parent_instance.innerHTML = text; return parent_instance; } ``` jQuery: ``` function grow(parent, tagName) { return $(parent).append($(document.createElement(tagName))); } function attach(parent_instance, text) { return $(parent_instance).text(text); } ```
I found my perfect answer, so I share it. ``` $.fn.grow = function (name) { var child = $(document.createElement(name)); this.append(child); return child; }; ``` It adds a jQuery method and enable this kind of procedural tree building: ``` var ord_list = ["first", "second", "third"]; var n_table = $('#ordinals') for (var i=0 ; i < ord_list.length ; i++) { n_tr = n_table.grow('tr'); n_td = n_tr.grow('td'); n_td.text(i); n_td = n_tr.grow('td'); n_td.text(ord_list[i]); } ``` which produces: ``` <table> <tr><td>1</td><td>first</td></tr> <tr><td>2</td><td>second</td></tr> <tr><td>3</td><td>third</td></tr> </table> ``` clean, unobtrusive, I will propose it to jQuery devs :D .attach() is useless since .text() already exists (thx @AmmarCSE)
748,478
I just had to re-install mysql and I am having a problem starting it up. It cannot find the socket (mysql.sock). The problem is that neither can I. In my Mac OS X 10.4 terminal, I type: `locate mysql.sock`, and I get back `/private/tmp/mysql.sock`. It makes sense that the socket file exist in that location, but it actually does not. 1. How can I find the socket file? 2. If locate is returning a false location, it must have some sort of memory and probably indexes. How can I refresh that index?
2009/04/14
[ "https://Stackoverflow.com/questions/748478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45849/" ]
The original questions seems to come from confusion about a) where is the file, and b) where is it being looked for (and why can't we find it there when we do a locate or grep). I think Alnitak's point was that you want to find where it was linked to - but grep will not show you a link, right? The file doesn't live there, since it's a link it is just a pointer. You still need to know where to put the link. my sock file is definitely in /tmp and the ERROR I am getting is looking for it in /var/lib/ (not just /var) I have linked to /var and /var/lib now, and I still am getting the error "Cannot connect to local MySQL server through socket 'var/lib/mysql.sock' (2)". Note the (2) after the error.... I found on another thread that this means the socket might be indeed attempted to be used, but something is wrong with the socket itself - so to shut down the machine - completely - so that the socket closes. Then a restart should fix it. I tried this, but it didn't work for me (now I question if I restarted too quickly? really?) Maybe it will be a solution for someone else.
I couldn't find mysql socket at all so reinstalled mysql server(all tables and phpmyadmin settings were preserved). Here are the commands: 1) Install > > sudo apt-get install mysql-server > > > 2) Follow terminal configuration steps > > sudo mysql\_secure\_installation > > > 3) Check status: (Should return "Active: active (running)") > > systemctl status mysql.service > > >
748,478
I just had to re-install mysql and I am having a problem starting it up. It cannot find the socket (mysql.sock). The problem is that neither can I. In my Mac OS X 10.4 terminal, I type: `locate mysql.sock`, and I get back `/private/tmp/mysql.sock`. It makes sense that the socket file exist in that location, but it actually does not. 1. How can I find the socket file? 2. If locate is returning a false location, it must have some sort of memory and probably indexes. How can I refresh that index?
2009/04/14
[ "https://Stackoverflow.com/questions/748478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45849/" ]
This found it for me: ``` netstat -ln | grep mysql ``` Mac OSX
I got the exact path using: ``` netstat -ln | grep -o -m 1 -E '\S*mysqld?\.sock' ``` Since this only returns the path and doesn't require any input you could potentially use it in a shell script. MySQL must be currently running on your machine for this to work. Works for MariaDB too.
748,478
I just had to re-install mysql and I am having a problem starting it up. It cannot find the socket (mysql.sock). The problem is that neither can I. In my Mac OS X 10.4 terminal, I type: `locate mysql.sock`, and I get back `/private/tmp/mysql.sock`. It makes sense that the socket file exist in that location, but it actually does not. 1. How can I find the socket file? 2. If locate is returning a false location, it must have some sort of memory and probably indexes. How can I refresh that index?
2009/04/14
[ "https://Stackoverflow.com/questions/748478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45849/" ]
to answer the first part of your question: run ``` % mysqladmin -p -u <user-name> variables ``` and check the 'socket' variable
My problem was also the mysql.sock-file. During the drupal installation process, i had to say which database i want to use but my database wasn't found ``` mkdir /var/mysql ln -s /tmp/mysql.sock /var/mysql/mysql.sock ``` the system is searching mysql.sock but it's in the wrong directory all you have to do is to link it ;) it took me a lot of time to google all important informations but it took me even hours to find out how to adapt , but now i can present the result :D ps: if you want to be exactly you have to link your `/tmp/mysql.sock-file` (if it is located in your system there too) to the directory given by the php.ini (or php.default.ini) where `pdo_mysql.default_socket= ...`
748,478
I just had to re-install mysql and I am having a problem starting it up. It cannot find the socket (mysql.sock). The problem is that neither can I. In my Mac OS X 10.4 terminal, I type: `locate mysql.sock`, and I get back `/private/tmp/mysql.sock`. It makes sense that the socket file exist in that location, but it actually does not. 1. How can I find the socket file? 2. If locate is returning a false location, it must have some sort of memory and probably indexes. How can I refresh that index?
2009/04/14
[ "https://Stackoverflow.com/questions/748478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45849/" ]
to answer the first part of your question: run ``` % mysqladmin -p -u <user-name> variables ``` and check the 'socket' variable
``` $ mysqladmin variables | grep sock ``` Try this instead, this will output the demanded result, getting rid of unrelated info.
748,478
I just had to re-install mysql and I am having a problem starting it up. It cannot find the socket (mysql.sock). The problem is that neither can I. In my Mac OS X 10.4 terminal, I type: `locate mysql.sock`, and I get back `/private/tmp/mysql.sock`. It makes sense that the socket file exist in that location, but it actually does not. 1. How can I find the socket file? 2. If locate is returning a false location, it must have some sort of memory and probably indexes. How can I refresh that index?
2009/04/14
[ "https://Stackoverflow.com/questions/748478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45849/" ]
I got the exact path using: ``` netstat -ln | grep -o -m 1 -E '\S*mysqld?\.sock' ``` Since this only returns the path and doesn't require any input you could potentially use it in a shell script. MySQL must be currently running on your machine for this to work. Works for MariaDB too.
Unfortunately none of the above have worked in my case. But finally I found solutions. To find where is mysql.sock file, simply open xampp manager, select MySQL and click on Configure on the right. On the config panel click Open Conf File, and simply search for mysql.sock by pressing the CMD+F shortcut. In my case, the owner of the mysql.sock was changed, and I had to change it back to root admin with: chmod root:admin mysql.sock After that the database had been accessed.
748,478
I just had to re-install mysql and I am having a problem starting it up. It cannot find the socket (mysql.sock). The problem is that neither can I. In my Mac OS X 10.4 terminal, I type: `locate mysql.sock`, and I get back `/private/tmp/mysql.sock`. It makes sense that the socket file exist in that location, but it actually does not. 1. How can I find the socket file? 2. If locate is returning a false location, it must have some sort of memory and probably indexes. How can I refresh that index?
2009/04/14
[ "https://Stackoverflow.com/questions/748478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45849/" ]
to answer the first part of your question: run ``` % mysqladmin -p -u <user-name> variables ``` and check the 'socket' variable
I couldn't find mysql socket at all so reinstalled mysql server(all tables and phpmyadmin settings were preserved). Here are the commands: 1) Install > > sudo apt-get install mysql-server > > > 2) Follow terminal configuration steps > > sudo mysql\_secure\_installation > > > 3) Check status: (Should return "Active: active (running)") > > systemctl status mysql.service > > >
748,478
I just had to re-install mysql and I am having a problem starting it up. It cannot find the socket (mysql.sock). The problem is that neither can I. In my Mac OS X 10.4 terminal, I type: `locate mysql.sock`, and I get back `/private/tmp/mysql.sock`. It makes sense that the socket file exist in that location, but it actually does not. 1. How can I find the socket file? 2. If locate is returning a false location, it must have some sort of memory and probably indexes. How can I refresh that index?
2009/04/14
[ "https://Stackoverflow.com/questions/748478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45849/" ]
The original questions seems to come from confusion about a) where is the file, and b) where is it being looked for (and why can't we find it there when we do a locate or grep). I think Alnitak's point was that you want to find where it was linked to - but grep will not show you a link, right? The file doesn't live there, since it's a link it is just a pointer. You still need to know where to put the link. my sock file is definitely in /tmp and the ERROR I am getting is looking for it in /var/lib/ (not just /var) I have linked to /var and /var/lib now, and I still am getting the error "Cannot connect to local MySQL server through socket 'var/lib/mysql.sock' (2)". Note the (2) after the error.... I found on another thread that this means the socket might be indeed attempted to be used, but something is wrong with the socket itself - so to shut down the machine - completely - so that the socket closes. Then a restart should fix it. I tried this, but it didn't work for me (now I question if I restarted too quickly? really?) Maybe it will be a solution for someone else.
I'm getting the same error on Mac OS X 10.11.6: `ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)` After a lot of agonizing and digging through advice here and in related questions, none of which seemed to fix the problem, I went back and deleted the installed folders, and just did `brew install mysql`. Still getting the same error with most commands, but this works: `/usr/local/bin/mysqld` and returns: > > /usr/local/bin/mysqld: ready for connections. > > > Version: '5.7.12' socket: '/tmp/mysql.sock' port: 3306 Homebrew > > >
748,478
I just had to re-install mysql and I am having a problem starting it up. It cannot find the socket (mysql.sock). The problem is that neither can I. In my Mac OS X 10.4 terminal, I type: `locate mysql.sock`, and I get back `/private/tmp/mysql.sock`. It makes sense that the socket file exist in that location, but it actually does not. 1. How can I find the socket file? 2. If locate is returning a false location, it must have some sort of memory and probably indexes. How can I refresh that index?
2009/04/14
[ "https://Stackoverflow.com/questions/748478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45849/" ]
to answer the first part of your question: run ``` % mysqladmin -p -u <user-name> variables ``` and check the 'socket' variable
To refresh the locate's database I ran ``` /usr/libexec/locate.updatedb ```
748,478
I just had to re-install mysql and I am having a problem starting it up. It cannot find the socket (mysql.sock). The problem is that neither can I. In my Mac OS X 10.4 terminal, I type: `locate mysql.sock`, and I get back `/private/tmp/mysql.sock`. It makes sense that the socket file exist in that location, but it actually does not. 1. How can I find the socket file? 2. If locate is returning a false location, it must have some sort of memory and probably indexes. How can I refresh that index?
2009/04/14
[ "https://Stackoverflow.com/questions/748478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45849/" ]
``` $ mysqladmin variables | grep sock ``` Try this instead, this will output the demanded result, getting rid of unrelated info.
I couldn't find mysql socket at all so reinstalled mysql server(all tables and phpmyadmin settings were preserved). Here are the commands: 1) Install > > sudo apt-get install mysql-server > > > 2) Follow terminal configuration steps > > sudo mysql\_secure\_installation > > > 3) Check status: (Should return "Active: active (running)") > > systemctl status mysql.service > > >
748,478
I just had to re-install mysql and I am having a problem starting it up. It cannot find the socket (mysql.sock). The problem is that neither can I. In my Mac OS X 10.4 terminal, I type: `locate mysql.sock`, and I get back `/private/tmp/mysql.sock`. It makes sense that the socket file exist in that location, but it actually does not. 1. How can I find the socket file? 2. If locate is returning a false location, it must have some sort of memory and probably indexes. How can I refresh that index?
2009/04/14
[ "https://Stackoverflow.com/questions/748478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45849/" ]
to answer the first part of your question: run ``` % mysqladmin -p -u <user-name> variables ``` and check the 'socket' variable
This found it for me: ``` netstat -ln | grep mysql ``` Mac OSX
57,284,696
How does one get the maximum and minimum values of a Number type like an Integer or a Float? ``` max_value(Int) ```
2019/07/31
[ "https://Stackoverflow.com/questions/57284696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417896/" ]
For questions like this, you will be best served by looking at the julia docs <https://docs.julialang.org/en/v1/base/base/#Base.typemin> Specifically for this question, `typemin(Int)`, and `typemax(Int)` should do what you want.
But `typemax(Float64)` gives 'Inf' which is probably not what the author wanted. The trick is to use `prevfloat(typemax(Float64))` which is not that obvious. ``` julia> typemax(Float64) Inf julia> prevfloat(typemax(Float64)) 1.7976931348623157e308 ```
14,115,980
Spoiler alert, this is problem 5 of Project Euler. I am attempting to learn Clojure and solved problem 5, but it is a couple orders of magnitude slower (1515 ms in Java versus 169932 ms in Clojure). I even tried using type hinting, unchecked math operations, and inlining functions all for naught. Why is my Clojure code so much slower? Clojure code: ``` (set! *unchecked-math* true) (defn divides? [^long number ^long divisor] (zero? (mod number divisor))) (defn has-all-divisors [divisors ^long num] (if (every? (fn [i] (divides? num i)) divisors) num false)) (time (prn (some (fn [^long i] (has-all-divisors (range 2 20) i)) (iterate inc 1)))) ``` Java code: ``` public class Problem5 { public static void main(String[] args) { long start = System.currentTimeMillis(); int i = 1; while(!hasAllDivisors(i, 2, 20)) { i++; } long end = System.currentTimeMillis(); System.out.println(i); System.out.println("Elapsed time " + (end - start)); } public static boolean hasAllDivisors(int num, int startDivisor, int stopDivisor) { for(int divisor=startDivisor; divisor<=stopDivisor; divisor++) { if(!divides(num, divisor)) return false; } return true; } public static boolean divides(int num, int divisor) { return num % divisor == 0; } } ```
2013/01/02
[ "https://Stackoverflow.com/questions/14115980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1054469/" ]
Some performance problems: * The `(range 2 20)` call is creating a new lazy list of numbers for every increment of `i`. This is expensive, and is causing lots of unnecessary GC. * You are doing a lot of boxing by passing through function calls. Even the `(iterate inc 1)` is doing boxing / unboxing at every increment. * You are traversing a sequence of divisors. This is slower than a straight iterative loop * `mod` is actually not a very well optimised function in Clojure at present. You are much better off using `rem` You can solve the first problem by using a `let` statement to define the range just once: ``` (time (let [rng (range 2 20)] (prn (some (fn [^long i] (has-all-divisors rng i)) (iterate inc 1))))) => "Elapsed time: 48863.801522 msecs" ``` You can solve the second problem with loop/recur: ``` (time (let [rng (range 2 20) f (fn [^long i] (has-all-divisors rng i))] (prn (loop [i 1] (if (f i) i (recur (inc i))))))) => "Elapsed time: 32757.594957 msecs" ``` You can solve the third problem by using an iterative loop over the possible divisors: ``` (defn has-all-divisors [^long num] (loop [d (long 2)] (if (zero? (mod num d)) (if (>= d 20) true (recur (inc d))) false))) (time (prn (loop [i (long 1)] (if (has-all-divisors i) i (recur (inc i)))))) => "Elapsed time: 13369.525651 msecs" ``` You can solve the final problem using `rem` ``` (defn has-all-divisors [^long num] (loop [d (long 2)] (if (== 0 (rem num d)) (if (>= d 20) true (recur (inc d))) false))) (time (prn (loop [i (long 1)] (if (has-all-divisors i) i (recur (inc i)))))) => "Elapsed time: 2423.195407 msecs" ``` As you can see, it is now competitive with the Java version. In general, you can usually make Clojure almost as fast as Java with a bit of effort. The main tricks are usually: * Avoid lazy functional features. They are nice, but add some overhead which can be problematic in low-level computation-intensive code. * Use primitive / unchecked maths * Use loop/recur rather than sequences * Ensure you are not doing any reflection on Java objects (i.e. `(set! *warn-on-reflection* true)` and eliminate all warnings you find)
I have not been able to reproduce the 1500 ms performance. The Clojure code seems actually twice as fast as the Java version after compilation to uberjar. ``` Now timing Java version 232792560 "Elapsed time: 4385.205 msecs" Now timing Clojure version 232792560 "Elapsed time: 2511.916 msecs" ``` I put the java class in resources/HasAllDivisors.java ``` public class HasAllDivisors { public static long findMinimumWithAllDivisors() { long i = 1; while(!hasAllDivisors(i,2,20)) i++; return i; } public static boolean hasAllDivisors(long num, int startDivisor, int stopDivisor) { for(int divisor = startDivisor; divisor <= stopDivisor; divisor++) { if(num % divisor > 0) return false; } return true; } public static void main(String[] args){ long start = System.currentTimeMillis(); long i = findMinimumWithAllDivisors(); long end = System.currentTimeMillis(); System.out.println(i); System.out.println("Elapsed time " + (end - start)); } } ``` And in Clojure ``` (time (prn (HasAllDivisors/findMinimumWithAllDivisors))) (println "Now timing Clojure version") (time (prn (loop [i (long 1)] (if (has-all-divisors i) i (recur (inc i)))))) ``` Even on the command line the java class is not reproducing the fast speed. ``` $ time java HasAllDivisors 232792560 Elapsed time 4398 real 0m4.563s user 0m4.597s sys 0m0.029s ```
14,115,980
Spoiler alert, this is problem 5 of Project Euler. I am attempting to learn Clojure and solved problem 5, but it is a couple orders of magnitude slower (1515 ms in Java versus 169932 ms in Clojure). I even tried using type hinting, unchecked math operations, and inlining functions all for naught. Why is my Clojure code so much slower? Clojure code: ``` (set! *unchecked-math* true) (defn divides? [^long number ^long divisor] (zero? (mod number divisor))) (defn has-all-divisors [divisors ^long num] (if (every? (fn [i] (divides? num i)) divisors) num false)) (time (prn (some (fn [^long i] (has-all-divisors (range 2 20) i)) (iterate inc 1)))) ``` Java code: ``` public class Problem5 { public static void main(String[] args) { long start = System.currentTimeMillis(); int i = 1; while(!hasAllDivisors(i, 2, 20)) { i++; } long end = System.currentTimeMillis(); System.out.println(i); System.out.println("Elapsed time " + (end - start)); } public static boolean hasAllDivisors(int num, int startDivisor, int stopDivisor) { for(int divisor=startDivisor; divisor<=stopDivisor; divisor++) { if(!divides(num, divisor)) return false; } return true; } public static boolean divides(int num, int divisor) { return num % divisor == 0; } } ```
2013/01/02
[ "https://Stackoverflow.com/questions/14115980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1054469/" ]
Some performance problems: * The `(range 2 20)` call is creating a new lazy list of numbers for every increment of `i`. This is expensive, and is causing lots of unnecessary GC. * You are doing a lot of boxing by passing through function calls. Even the `(iterate inc 1)` is doing boxing / unboxing at every increment. * You are traversing a sequence of divisors. This is slower than a straight iterative loop * `mod` is actually not a very well optimised function in Clojure at present. You are much better off using `rem` You can solve the first problem by using a `let` statement to define the range just once: ``` (time (let [rng (range 2 20)] (prn (some (fn [^long i] (has-all-divisors rng i)) (iterate inc 1))))) => "Elapsed time: 48863.801522 msecs" ``` You can solve the second problem with loop/recur: ``` (time (let [rng (range 2 20) f (fn [^long i] (has-all-divisors rng i))] (prn (loop [i 1] (if (f i) i (recur (inc i))))))) => "Elapsed time: 32757.594957 msecs" ``` You can solve the third problem by using an iterative loop over the possible divisors: ``` (defn has-all-divisors [^long num] (loop [d (long 2)] (if (zero? (mod num d)) (if (>= d 20) true (recur (inc d))) false))) (time (prn (loop [i (long 1)] (if (has-all-divisors i) i (recur (inc i)))))) => "Elapsed time: 13369.525651 msecs" ``` You can solve the final problem using `rem` ``` (defn has-all-divisors [^long num] (loop [d (long 2)] (if (== 0 (rem num d)) (if (>= d 20) true (recur (inc d))) false))) (time (prn (loop [i (long 1)] (if (has-all-divisors i) i (recur (inc i)))))) => "Elapsed time: 2423.195407 msecs" ``` As you can see, it is now competitive with the Java version. In general, you can usually make Clojure almost as fast as Java with a bit of effort. The main tricks are usually: * Avoid lazy functional features. They are nice, but add some overhead which can be problematic in low-level computation-intensive code. * Use primitive / unchecked maths * Use loop/recur rather than sequences * Ensure you are not doing any reflection on Java objects (i.e. `(set! *warn-on-reflection* true)` and eliminate all warnings you find)
I know this is an old question, but I've been running into similar things. It looks like the statement from the OP, that Clojure is much worse than Java on simple loops, is true. I went through the process in this thread, starting with OP's code and then adding the performance improvements. At the end of it all, the java code runs in around 300 ms and the optimized Clojure code runs in 3000 ms. Creating an uberjar with lein gets the Clojure code down to 2500 ms. Since we know the answer that the given code spits out, I used that to have the Clojure code merely loop the number of times without doing the mod/rem calculations. It simply goes through the loops. ``` (def target 232792560) (defn has-all-divisors [divisors ^long num] (loop [d (long 2)] (if (< d 20) (recur (inc d))))) (time (let [rng (range 2 20) f (fn [^long i] (has-all-divisors (range 2 20) i)) ] (prn (loop [i 1] (if (< i target) (do (f i) (recur (inc i)))))))) ``` The resulting times are roughly the same as doing the calculations, i.e. 3000 ms. So, it's taking Clojure that long simply to walk through that many loops.
14,115,980
Spoiler alert, this is problem 5 of Project Euler. I am attempting to learn Clojure and solved problem 5, but it is a couple orders of magnitude slower (1515 ms in Java versus 169932 ms in Clojure). I even tried using type hinting, unchecked math operations, and inlining functions all for naught. Why is my Clojure code so much slower? Clojure code: ``` (set! *unchecked-math* true) (defn divides? [^long number ^long divisor] (zero? (mod number divisor))) (defn has-all-divisors [divisors ^long num] (if (every? (fn [i] (divides? num i)) divisors) num false)) (time (prn (some (fn [^long i] (has-all-divisors (range 2 20) i)) (iterate inc 1)))) ``` Java code: ``` public class Problem5 { public static void main(String[] args) { long start = System.currentTimeMillis(); int i = 1; while(!hasAllDivisors(i, 2, 20)) { i++; } long end = System.currentTimeMillis(); System.out.println(i); System.out.println("Elapsed time " + (end - start)); } public static boolean hasAllDivisors(int num, int startDivisor, int stopDivisor) { for(int divisor=startDivisor; divisor<=stopDivisor; divisor++) { if(!divides(num, divisor)) return false; } return true; } public static boolean divides(int num, int divisor) { return num % divisor == 0; } } ```
2013/01/02
[ "https://Stackoverflow.com/questions/14115980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1054469/" ]
I have not been able to reproduce the 1500 ms performance. The Clojure code seems actually twice as fast as the Java version after compilation to uberjar. ``` Now timing Java version 232792560 "Elapsed time: 4385.205 msecs" Now timing Clojure version 232792560 "Elapsed time: 2511.916 msecs" ``` I put the java class in resources/HasAllDivisors.java ``` public class HasAllDivisors { public static long findMinimumWithAllDivisors() { long i = 1; while(!hasAllDivisors(i,2,20)) i++; return i; } public static boolean hasAllDivisors(long num, int startDivisor, int stopDivisor) { for(int divisor = startDivisor; divisor <= stopDivisor; divisor++) { if(num % divisor > 0) return false; } return true; } public static void main(String[] args){ long start = System.currentTimeMillis(); long i = findMinimumWithAllDivisors(); long end = System.currentTimeMillis(); System.out.println(i); System.out.println("Elapsed time " + (end - start)); } } ``` And in Clojure ``` (time (prn (HasAllDivisors/findMinimumWithAllDivisors))) (println "Now timing Clojure version") (time (prn (loop [i (long 1)] (if (has-all-divisors i) i (recur (inc i)))))) ``` Even on the command line the java class is not reproducing the fast speed. ``` $ time java HasAllDivisors 232792560 Elapsed time 4398 real 0m4.563s user 0m4.597s sys 0m0.029s ```
I know this is an old question, but I've been running into similar things. It looks like the statement from the OP, that Clojure is much worse than Java on simple loops, is true. I went through the process in this thread, starting with OP's code and then adding the performance improvements. At the end of it all, the java code runs in around 300 ms and the optimized Clojure code runs in 3000 ms. Creating an uberjar with lein gets the Clojure code down to 2500 ms. Since we know the answer that the given code spits out, I used that to have the Clojure code merely loop the number of times without doing the mod/rem calculations. It simply goes through the loops. ``` (def target 232792560) (defn has-all-divisors [divisors ^long num] (loop [d (long 2)] (if (< d 20) (recur (inc d))))) (time (let [rng (range 2 20) f (fn [^long i] (has-all-divisors (range 2 20) i)) ] (prn (loop [i 1] (if (< i target) (do (f i) (recur (inc i)))))))) ``` The resulting times are roughly the same as doing the calculations, i.e. 3000 ms. So, it's taking Clojure that long simply to walk through that many loops.
4,199,312
I have a UserControl, we'll call it `myUC`, that is one among several UserControls in the main window (`myWindow`) of my WPF application. `myUC` contains a number of standard controls, one of them being a button, we'll call it `myButton`. When I click `myButton`, I would like to execute `myMethod()`, which exists in the code-behind of myWindow. The problem being that `myUC` doesn't have any idea that `myWindow` even exists, much less that myMethod exists. How can I send the message: 'Hey, myWindow, wake up. myButton on myUc was just clicked; please run myMethod'?
2010/11/16
[ "https://Stackoverflow.com/questions/4199312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107899/" ]
What I actually ended up having to do in VB: Create a new Public Class for my custom commands because it was undesirable to have my MainWindow class as Public: ``` Public Class Commands Public Shared myCmd As New RoutedCommand End Class ``` Create the Execute and CanExecute methods that run the desired code. These two methods were created in the MainWindow code behind: ``` Class MainWindow Private Sub myCmdCanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs) e.CanExecute = True e.Handled = True End Sub Private Sub myCmdExecuted(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs) //Do stuff here... e.Handled = True End Sub End Class ``` Create the Command binding in the MainWindow code-behind and add the two handler methods to the binding (this is the part that is quite different between C# and VB): ``` Class MainWindow Public Sub New() // This call is required by the designer. InitializeComponent() //Add any initialization after the InitializeComponent() call. //Create command bindings. Dim cb As New CommandBinding(Commands.myCmd) AddHandler cb.CanExecute, AddressOf myCmdCanExecute AddHandler cb.Executed, AddressOf myCmdExecuted Me.CommandBindings.Add(cb) End Sub End Class ``` Add the new custom command to the button object on the UserControl. With a custom command, this did not seem to be possible in XAML, so I had to do it in code-behind. The Commands class needed to be Public so the commands were accessible in this UserControl: ``` Public Class myUserControl Public Sub New() //This call is required by the designer. InitializeComponent() // Add any initialization after the InitializeComponent() call. myButton.Command = Commands.myCmd End Sub End Class ```
Try something like this static helper method: ``` public static T GetParentOfType<T>(DependencyObject currentObject) where T : DependencyObject { // Get the parent of the object in question DependencyObject parentObject = GetParentObject(currentObject); if (parentObject == null) return null; // if the parent is the type then return T parent = parentObject as T; if (parent != null) { return parent; } else // if not the type, recursively continue up { return GetParentOfType<T>(parentObject); } } public static DependencyObject GetParent(DependencyObject currentObject) { if (currentObject == null) return null; // Convert the object in question to a content element ContentElement contentEl = currentObject as ContentElement; if (contentEl != null) { // try dependencyobject DependencyObject parent = System.Windows.ContentOperations.GetParent(contentEl); if (parent != null) return parent; // Convert the contentEl to a FrameworkContentElement FrameworkContentElement frameworkEl = contentEl as FrameworkContentElement; // try frameworkcontentelement if (frameworkEl != null) return frameworkEl.Parent; else return null; } // couldn't get the content element, so return the parent of the visual element return System.Windows.Media.VisualTreeHelper.GetParent(currentObject); } ``` Execute it like so: ``` StaticHelpers.GetParentOfType<Window>(this); ```
4,199,312
I have a UserControl, we'll call it `myUC`, that is one among several UserControls in the main window (`myWindow`) of my WPF application. `myUC` contains a number of standard controls, one of them being a button, we'll call it `myButton`. When I click `myButton`, I would like to execute `myMethod()`, which exists in the code-behind of myWindow. The problem being that `myUC` doesn't have any idea that `myWindow` even exists, much less that myMethod exists. How can I send the message: 'Hey, myWindow, wake up. myButton on myUc was just clicked; please run myMethod'?
2010/11/16
[ "https://Stackoverflow.com/questions/4199312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107899/" ]
What I actually ended up having to do in VB: Create a new Public Class for my custom commands because it was undesirable to have my MainWindow class as Public: ``` Public Class Commands Public Shared myCmd As New RoutedCommand End Class ``` Create the Execute and CanExecute methods that run the desired code. These two methods were created in the MainWindow code behind: ``` Class MainWindow Private Sub myCmdCanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs) e.CanExecute = True e.Handled = True End Sub Private Sub myCmdExecuted(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs) //Do stuff here... e.Handled = True End Sub End Class ``` Create the Command binding in the MainWindow code-behind and add the two handler methods to the binding (this is the part that is quite different between C# and VB): ``` Class MainWindow Public Sub New() // This call is required by the designer. InitializeComponent() //Add any initialization after the InitializeComponent() call. //Create command bindings. Dim cb As New CommandBinding(Commands.myCmd) AddHandler cb.CanExecute, AddressOf myCmdCanExecute AddHandler cb.Executed, AddressOf myCmdExecuted Me.CommandBindings.Add(cb) End Sub End Class ``` Add the new custom command to the button object on the UserControl. With a custom command, this did not seem to be possible in XAML, so I had to do it in code-behind. The Commands class needed to be Public so the commands were accessible in this UserControl: ``` Public Class myUserControl Public Sub New() //This call is required by the designer. InitializeComponent() // Add any initialization after the InitializeComponent() call. myButton.Command = Commands.myCmd End Sub End Class ```
I recommend learning about [Routed Events](http://msdn.microsoft.com/en-us/library/ms742806.aspx) and [Routed Commands](http://msdn.microsoft.com/en-us/magazine/cc785480.aspx) - this is the sort of thing they're meant to do.
4,199,312
I have a UserControl, we'll call it `myUC`, that is one among several UserControls in the main window (`myWindow`) of my WPF application. `myUC` contains a number of standard controls, one of them being a button, we'll call it `myButton`. When I click `myButton`, I would like to execute `myMethod()`, which exists in the code-behind of myWindow. The problem being that `myUC` doesn't have any idea that `myWindow` even exists, much less that myMethod exists. How can I send the message: 'Hey, myWindow, wake up. myButton on myUc was just clicked; please run myMethod'?
2010/11/16
[ "https://Stackoverflow.com/questions/4199312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107899/" ]
You can create a command in the window and set the Command property of the button to the name of this command. Clicking the button will fire the command, without a need for a reference to the parent window. [This tutorial explains everything very clearly.](https://web.archive.org/web/20121102095816/http://www.switchonthecode.com/tutorials/wpf-tutorial-command-bindings-and-custom-commands)
Try something like this static helper method: ``` public static T GetParentOfType<T>(DependencyObject currentObject) where T : DependencyObject { // Get the parent of the object in question DependencyObject parentObject = GetParentObject(currentObject); if (parentObject == null) return null; // if the parent is the type then return T parent = parentObject as T; if (parent != null) { return parent; } else // if not the type, recursively continue up { return GetParentOfType<T>(parentObject); } } public static DependencyObject GetParent(DependencyObject currentObject) { if (currentObject == null) return null; // Convert the object in question to a content element ContentElement contentEl = currentObject as ContentElement; if (contentEl != null) { // try dependencyobject DependencyObject parent = System.Windows.ContentOperations.GetParent(contentEl); if (parent != null) return parent; // Convert the contentEl to a FrameworkContentElement FrameworkContentElement frameworkEl = contentEl as FrameworkContentElement; // try frameworkcontentelement if (frameworkEl != null) return frameworkEl.Parent; else return null; } // couldn't get the content element, so return the parent of the visual element return System.Windows.Media.VisualTreeHelper.GetParent(currentObject); } ``` Execute it like so: ``` StaticHelpers.GetParentOfType<Window>(this); ```
4,199,312
I have a UserControl, we'll call it `myUC`, that is one among several UserControls in the main window (`myWindow`) of my WPF application. `myUC` contains a number of standard controls, one of them being a button, we'll call it `myButton`. When I click `myButton`, I would like to execute `myMethod()`, which exists in the code-behind of myWindow. The problem being that `myUC` doesn't have any idea that `myWindow` even exists, much less that myMethod exists. How can I send the message: 'Hey, myWindow, wake up. myButton on myUc was just clicked; please run myMethod'?
2010/11/16
[ "https://Stackoverflow.com/questions/4199312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107899/" ]
The above is all well and good... but seems a bit convoluted to me... **My similar problem:** I have a Window (MainWindow.xaml) with a UserControl (SurveyHeader.xaml) in it and inside that UserControl is another UserControl (GetSurveyByID.xaml). I have a private void in MainWindow.xaml that i want to run when a button (btnGetSurvey) is clicked in GetSurveyByID.xaml. This one line solution worked quite well for me. ``` this.ucSurveyHeader.ucGetSurveyByID.btnGetSurvey.Click += new RoutedEventHandler(btnGetSurvey_Click); ```
Try something like this static helper method: ``` public static T GetParentOfType<T>(DependencyObject currentObject) where T : DependencyObject { // Get the parent of the object in question DependencyObject parentObject = GetParentObject(currentObject); if (parentObject == null) return null; // if the parent is the type then return T parent = parentObject as T; if (parent != null) { return parent; } else // if not the type, recursively continue up { return GetParentOfType<T>(parentObject); } } public static DependencyObject GetParent(DependencyObject currentObject) { if (currentObject == null) return null; // Convert the object in question to a content element ContentElement contentEl = currentObject as ContentElement; if (contentEl != null) { // try dependencyobject DependencyObject parent = System.Windows.ContentOperations.GetParent(contentEl); if (parent != null) return parent; // Convert the contentEl to a FrameworkContentElement FrameworkContentElement frameworkEl = contentEl as FrameworkContentElement; // try frameworkcontentelement if (frameworkEl != null) return frameworkEl.Parent; else return null; } // couldn't get the content element, so return the parent of the visual element return System.Windows.Media.VisualTreeHelper.GetParent(currentObject); } ``` Execute it like so: ``` StaticHelpers.GetParentOfType<Window>(this); ```
4,199,312
I have a UserControl, we'll call it `myUC`, that is one among several UserControls in the main window (`myWindow`) of my WPF application. `myUC` contains a number of standard controls, one of them being a button, we'll call it `myButton`. When I click `myButton`, I would like to execute `myMethod()`, which exists in the code-behind of myWindow. The problem being that `myUC` doesn't have any idea that `myWindow` even exists, much less that myMethod exists. How can I send the message: 'Hey, myWindow, wake up. myButton on myUc was just clicked; please run myMethod'?
2010/11/16
[ "https://Stackoverflow.com/questions/4199312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107899/" ]
The above is all well and good... but seems a bit convoluted to me... **My similar problem:** I have a Window (MainWindow.xaml) with a UserControl (SurveyHeader.xaml) in it and inside that UserControl is another UserControl (GetSurveyByID.xaml). I have a private void in MainWindow.xaml that i want to run when a button (btnGetSurvey) is clicked in GetSurveyByID.xaml. This one line solution worked quite well for me. ``` this.ucSurveyHeader.ucGetSurveyByID.btnGetSurvey.Click += new RoutedEventHandler(btnGetSurvey_Click); ```
Every control has a parent property which tells you that who actually "owns" this control. You can use that along side with type casting to access your myWindow's myMethod. You could also use the *sender* argument of your event handler like this: ``` (sender as MyWindow).myMethod() ```
4,199,312
I have a UserControl, we'll call it `myUC`, that is one among several UserControls in the main window (`myWindow`) of my WPF application. `myUC` contains a number of standard controls, one of them being a button, we'll call it `myButton`. When I click `myButton`, I would like to execute `myMethod()`, which exists in the code-behind of myWindow. The problem being that `myUC` doesn't have any idea that `myWindow` even exists, much less that myMethod exists. How can I send the message: 'Hey, myWindow, wake up. myButton on myUc was just clicked; please run myMethod'?
2010/11/16
[ "https://Stackoverflow.com/questions/4199312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107899/" ]
I recommend learning about [Routed Events](http://msdn.microsoft.com/en-us/library/ms742806.aspx) and [Routed Commands](http://msdn.microsoft.com/en-us/magazine/cc785480.aspx) - this is the sort of thing they're meant to do.
Try something like this static helper method: ``` public static T GetParentOfType<T>(DependencyObject currentObject) where T : DependencyObject { // Get the parent of the object in question DependencyObject parentObject = GetParentObject(currentObject); if (parentObject == null) return null; // if the parent is the type then return T parent = parentObject as T; if (parent != null) { return parent; } else // if not the type, recursively continue up { return GetParentOfType<T>(parentObject); } } public static DependencyObject GetParent(DependencyObject currentObject) { if (currentObject == null) return null; // Convert the object in question to a content element ContentElement contentEl = currentObject as ContentElement; if (contentEl != null) { // try dependencyobject DependencyObject parent = System.Windows.ContentOperations.GetParent(contentEl); if (parent != null) return parent; // Convert the contentEl to a FrameworkContentElement FrameworkContentElement frameworkEl = contentEl as FrameworkContentElement; // try frameworkcontentelement if (frameworkEl != null) return frameworkEl.Parent; else return null; } // couldn't get the content element, so return the parent of the visual element return System.Windows.Media.VisualTreeHelper.GetParent(currentObject); } ``` Execute it like so: ``` StaticHelpers.GetParentOfType<Window>(this); ```
4,199,312
I have a UserControl, we'll call it `myUC`, that is one among several UserControls in the main window (`myWindow`) of my WPF application. `myUC` contains a number of standard controls, one of them being a button, we'll call it `myButton`. When I click `myButton`, I would like to execute `myMethod()`, which exists in the code-behind of myWindow. The problem being that `myUC` doesn't have any idea that `myWindow` even exists, much less that myMethod exists. How can I send the message: 'Hey, myWindow, wake up. myButton on myUc was just clicked; please run myMethod'?
2010/11/16
[ "https://Stackoverflow.com/questions/4199312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107899/" ]
You can create a command in the window and set the Command property of the button to the name of this command. Clicking the button will fire the command, without a need for a reference to the parent window. [This tutorial explains everything very clearly.](https://web.archive.org/web/20121102095816/http://www.switchonthecode.com/tutorials/wpf-tutorial-command-bindings-and-custom-commands)
The above is all well and good... but seems a bit convoluted to me... **My similar problem:** I have a Window (MainWindow.xaml) with a UserControl (SurveyHeader.xaml) in it and inside that UserControl is another UserControl (GetSurveyByID.xaml). I have a private void in MainWindow.xaml that i want to run when a button (btnGetSurvey) is clicked in GetSurveyByID.xaml. This one line solution worked quite well for me. ``` this.ucSurveyHeader.ucGetSurveyByID.btnGetSurvey.Click += new RoutedEventHandler(btnGetSurvey_Click); ```
4,199,312
I have a UserControl, we'll call it `myUC`, that is one among several UserControls in the main window (`myWindow`) of my WPF application. `myUC` contains a number of standard controls, one of them being a button, we'll call it `myButton`. When I click `myButton`, I would like to execute `myMethod()`, which exists in the code-behind of myWindow. The problem being that `myUC` doesn't have any idea that `myWindow` even exists, much less that myMethod exists. How can I send the message: 'Hey, myWindow, wake up. myButton on myUc was just clicked; please run myMethod'?
2010/11/16
[ "https://Stackoverflow.com/questions/4199312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107899/" ]
You can create a command in the window and set the Command property of the button to the name of this command. Clicking the button will fire the command, without a need for a reference to the parent window. [This tutorial explains everything very clearly.](https://web.archive.org/web/20121102095816/http://www.switchonthecode.com/tutorials/wpf-tutorial-command-bindings-and-custom-commands)
Every control has a parent property which tells you that who actually "owns" this control. You can use that along side with type casting to access your myWindow's myMethod. You could also use the *sender* argument of your event handler like this: ``` (sender as MyWindow).myMethod() ```
4,199,312
I have a UserControl, we'll call it `myUC`, that is one among several UserControls in the main window (`myWindow`) of my WPF application. `myUC` contains a number of standard controls, one of them being a button, we'll call it `myButton`. When I click `myButton`, I would like to execute `myMethod()`, which exists in the code-behind of myWindow. The problem being that `myUC` doesn't have any idea that `myWindow` even exists, much less that myMethod exists. How can I send the message: 'Hey, myWindow, wake up. myButton on myUc was just clicked; please run myMethod'?
2010/11/16
[ "https://Stackoverflow.com/questions/4199312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107899/" ]
What I actually ended up having to do in VB: Create a new Public Class for my custom commands because it was undesirable to have my MainWindow class as Public: ``` Public Class Commands Public Shared myCmd As New RoutedCommand End Class ``` Create the Execute and CanExecute methods that run the desired code. These two methods were created in the MainWindow code behind: ``` Class MainWindow Private Sub myCmdCanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs) e.CanExecute = True e.Handled = True End Sub Private Sub myCmdExecuted(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs) //Do stuff here... e.Handled = True End Sub End Class ``` Create the Command binding in the MainWindow code-behind and add the two handler methods to the binding (this is the part that is quite different between C# and VB): ``` Class MainWindow Public Sub New() // This call is required by the designer. InitializeComponent() //Add any initialization after the InitializeComponent() call. //Create command bindings. Dim cb As New CommandBinding(Commands.myCmd) AddHandler cb.CanExecute, AddressOf myCmdCanExecute AddHandler cb.Executed, AddressOf myCmdExecuted Me.CommandBindings.Add(cb) End Sub End Class ``` Add the new custom command to the button object on the UserControl. With a custom command, this did not seem to be possible in XAML, so I had to do it in code-behind. The Commands class needed to be Public so the commands were accessible in this UserControl: ``` Public Class myUserControl Public Sub New() //This call is required by the designer. InitializeComponent() // Add any initialization after the InitializeComponent() call. myButton.Command = Commands.myCmd End Sub End Class ```
The above is all well and good... but seems a bit convoluted to me... **My similar problem:** I have a Window (MainWindow.xaml) with a UserControl (SurveyHeader.xaml) in it and inside that UserControl is another UserControl (GetSurveyByID.xaml). I have a private void in MainWindow.xaml that i want to run when a button (btnGetSurvey) is clicked in GetSurveyByID.xaml. This one line solution worked quite well for me. ``` this.ucSurveyHeader.ucGetSurveyByID.btnGetSurvey.Click += new RoutedEventHandler(btnGetSurvey_Click); ```
4,199,312
I have a UserControl, we'll call it `myUC`, that is one among several UserControls in the main window (`myWindow`) of my WPF application. `myUC` contains a number of standard controls, one of them being a button, we'll call it `myButton`. When I click `myButton`, I would like to execute `myMethod()`, which exists in the code-behind of myWindow. The problem being that `myUC` doesn't have any idea that `myWindow` even exists, much less that myMethod exists. How can I send the message: 'Hey, myWindow, wake up. myButton on myUc was just clicked; please run myMethod'?
2010/11/16
[ "https://Stackoverflow.com/questions/4199312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107899/" ]
You can create a command in the window and set the Command property of the button to the name of this command. Clicking the button will fire the command, without a need for a reference to the parent window. [This tutorial explains everything very clearly.](https://web.archive.org/web/20121102095816/http://www.switchonthecode.com/tutorials/wpf-tutorial-command-bindings-and-custom-commands)
What I actually ended up having to do in VB: Create a new Public Class for my custom commands because it was undesirable to have my MainWindow class as Public: ``` Public Class Commands Public Shared myCmd As New RoutedCommand End Class ``` Create the Execute and CanExecute methods that run the desired code. These two methods were created in the MainWindow code behind: ``` Class MainWindow Private Sub myCmdCanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs) e.CanExecute = True e.Handled = True End Sub Private Sub myCmdExecuted(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs) //Do stuff here... e.Handled = True End Sub End Class ``` Create the Command binding in the MainWindow code-behind and add the two handler methods to the binding (this is the part that is quite different between C# and VB): ``` Class MainWindow Public Sub New() // This call is required by the designer. InitializeComponent() //Add any initialization after the InitializeComponent() call. //Create command bindings. Dim cb As New CommandBinding(Commands.myCmd) AddHandler cb.CanExecute, AddressOf myCmdCanExecute AddHandler cb.Executed, AddressOf myCmdExecuted Me.CommandBindings.Add(cb) End Sub End Class ``` Add the new custom command to the button object on the UserControl. With a custom command, this did not seem to be possible in XAML, so I had to do it in code-behind. The Commands class needed to be Public so the commands were accessible in this UserControl: ``` Public Class myUserControl Public Sub New() //This call is required by the designer. InitializeComponent() // Add any initialization after the InitializeComponent() call. myButton.Command = Commands.myCmd End Sub End Class ```
8,015,790
XCode is driving me nuts, when I register for multiple notification types: > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge]; > > ``` > > or > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; > > ``` > > It throws and error not a warning: > > error: Semantic Issue: Cannot initialize a parameter of type 'UIRemoteNotificationType' with an rvalue of type 'int' > > > Even though this is the same line that everyone uses (even Apple in their demos). I'm using the iOS 5 SDK (first one that came out after release of iOS 5) & XCode 4.2. The project is a older project (XCode 3 & iOS 4) that is being upgraded and targeted for iOS 5.
2011/11/04
[ "https://Stackoverflow.com/questions/8015790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/635095/" ]
Try casting to `UIRemoteNotificationType`: ``` [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; ```
put parentheses around the parameters like ``` [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; ```
8,015,790
XCode is driving me nuts, when I register for multiple notification types: > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge]; > > ``` > > or > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; > > ``` > > It throws and error not a warning: > > error: Semantic Issue: Cannot initialize a parameter of type 'UIRemoteNotificationType' with an rvalue of type 'int' > > > Even though this is the same line that everyone uses (even Apple in their demos). I'm using the iOS 5 SDK (first one that came out after release of iOS 5) & XCode 4.2. The project is a older project (XCode 3 & iOS 4) that is being upgraded and targeted for iOS 5.
2011/11/04
[ "https://Stackoverflow.com/questions/8015790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/635095/" ]
For the record I was never able to solve this problem completely. It is definitely a problem with the developer tools. The line in my UIApplicationDelegate didn't work. I was able to work around this by placing this line in my MainViewController rather than my ApplicationDelegate.
put parentheses around the parameters like ``` [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; ```
8,015,790
XCode is driving me nuts, when I register for multiple notification types: > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge]; > > ``` > > or > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; > > ``` > > It throws and error not a warning: > > error: Semantic Issue: Cannot initialize a parameter of type 'UIRemoteNotificationType' with an rvalue of type 'int' > > > Even though this is the same line that everyone uses (even Apple in their demos). I'm using the iOS 5 SDK (first one that came out after release of iOS 5) & XCode 4.2. The project is a older project (XCode 3 & iOS 4) that is being upgraded and targeted for iOS 5.
2011/11/04
[ "https://Stackoverflow.com/questions/8015790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/635095/" ]
I had this problem too. The trick is if this code is in a .mm file (Objective C++), this error occurs. If you aren't using any C++ features, change the filename extension from .mm to .m and it will compile OK.
put parentheses around the parameters like ``` [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; ```
8,015,790
XCode is driving me nuts, when I register for multiple notification types: > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge]; > > ``` > > or > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; > > ``` > > It throws and error not a warning: > > error: Semantic Issue: Cannot initialize a parameter of type 'UIRemoteNotificationType' with an rvalue of type 'int' > > > Even though this is the same line that everyone uses (even Apple in their demos). I'm using the iOS 5 SDK (first one that came out after release of iOS 5) & XCode 4.2. The project is a older project (XCode 3 & iOS 4) that is being upgraded and targeted for iOS 5.
2011/11/04
[ "https://Stackoverflow.com/questions/8015790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/635095/" ]
Try casting to `UIRemoteNotificationType`: ``` [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; ```
For the record I was never able to solve this problem completely. It is definitely a problem with the developer tools. The line in my UIApplicationDelegate didn't work. I was able to work around this by placing this line in my MainViewController rather than my ApplicationDelegate.
8,015,790
XCode is driving me nuts, when I register for multiple notification types: > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge]; > > ``` > > or > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; > > ``` > > It throws and error not a warning: > > error: Semantic Issue: Cannot initialize a parameter of type 'UIRemoteNotificationType' with an rvalue of type 'int' > > > Even though this is the same line that everyone uses (even Apple in their demos). I'm using the iOS 5 SDK (first one that came out after release of iOS 5) & XCode 4.2. The project is a older project (XCode 3 & iOS 4) that is being upgraded and targeted for iOS 5.
2011/11/04
[ "https://Stackoverflow.com/questions/8015790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/635095/" ]
I had this problem too. The trick is if this code is in a .mm file (Objective C++), this error occurs. If you aren't using any C++ features, change the filename extension from .mm to .m and it will compile OK.
Try casting to `UIRemoteNotificationType`: ``` [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; ```
8,015,790
XCode is driving me nuts, when I register for multiple notification types: > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge]; > > ``` > > or > > > ``` > [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge)]; > > ``` > > It throws and error not a warning: > > error: Semantic Issue: Cannot initialize a parameter of type 'UIRemoteNotificationType' with an rvalue of type 'int' > > > Even though this is the same line that everyone uses (even Apple in their demos). I'm using the iOS 5 SDK (first one that came out after release of iOS 5) & XCode 4.2. The project is a older project (XCode 3 & iOS 4) that is being upgraded and targeted for iOS 5.
2011/11/04
[ "https://Stackoverflow.com/questions/8015790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/635095/" ]
I had this problem too. The trick is if this code is in a .mm file (Objective C++), this error occurs. If you aren't using any C++ features, change the filename extension from .mm to .m and it will compile OK.
For the record I was never able to solve this problem completely. It is definitely a problem with the developer tools. The line in my UIApplicationDelegate didn't work. I was able to work around this by placing this line in my MainViewController rather than my ApplicationDelegate.
1,314,640
I used inequality between arithmetic and geometric means to show that a sequence $\{a\_{n}\}$ is bounded: $$a\_{n+2}=\sqrt{a\_{n+1}a\_{n}}\le \frac{a\_{n+1}+a\_{n}}{2}$$ Solving this, I get quadratic inequality $$a^2\_{n+1}-2a\_{n+1}a\_{n}+a^2\_{n}\ge 0$$ which gets me to $$0\le a\_{n}\le 1$$ thus, sequence is bounded. I get that sequence is not monotonic, because $$a\_{n}\le a\_{n+2} \le {a\_{n+1}}$$ or $$a\_{n+1}\le a\_{n+2} \le {a\_{n}}$$ Is this right?
2015/06/06
[ "https://math.stackexchange.com/questions/1314640", "https://math.stackexchange.com", "https://math.stackexchange.com/users/222321/" ]
Let $c\_n=\log a\_n$. Then the sequence $\{c\_n\}\_{n\in\mathbb N}$ satisfies the recursive relation: $$ c\_{n+2}=\frac{1}{2}c\_{n+1}+\frac{1}{2}c\_{n}, \quad c\_1=\log a,\,\,c\_2=\log b. $$ Then we have $$ c\_{n+2}-c\_{n+1}=-\frac{1}{2}\big(c\_{n+1}-c\_{n})=\cdots=\frac{(-1)^n}{2^n}(c\_2-c\_1). \tag{1} $$ Also $$ c\_{n+2}+\frac{1}{2}c\_{n+1}=c\_{n+1}+\frac{1}{2}c\_{n}=\cdots=c\_{2}+\frac{1}{2}c\_{1}. \tag{2} $$ Combining $(1)$ and $(2)$ we obtain $$ c\_{n+2}=\frac{1}{3}\left(2c\_2+c\_1+\frac{(-1)^n}{2^n}(c\_2-c\_1)\right) $$ and hence $$ a\_n=a^{1/3}b^{2/3}\left(\frac{b}{a}\right)^{(-1)^n/2^{n-2}}\to a^{1/3}b^{2/3}, $$ since $c^{1/2^n}\to 1$, for every $c>0$. Note. Proving convergence, without finding the limit, is simpler, as $\{a\_{2n+1}\}$ is increasing, $\{a\_{2n}\}$ is decreasing, and $a\_{2n+2}/a\_{2n+1}=\sqrt{a\_{2n}/a\_{2n-1}}=(a\_2/a\_1)^{1/2^n}\to 1$.
* Assume WLOG $a<b$. * Now show that the even subsequence $\{a\_{2n}\}$ and the odd subsequence $\{a\_{2n-1}\}$ are individually monotonic. * Show that all the terms of one of these subsequences are greater than all the terms of the other subsequence. * So you have got bounded monotonic even subsequence and bounded monotonic odd subsequence. One of them is increasing and the other is decreasing. Show that the limits of these two subsequences are equal. * Conclude that this information is sufficient to show that the whole sequence converges to the same limit.
1,314,640
I used inequality between arithmetic and geometric means to show that a sequence $\{a\_{n}\}$ is bounded: $$a\_{n+2}=\sqrt{a\_{n+1}a\_{n}}\le \frac{a\_{n+1}+a\_{n}}{2}$$ Solving this, I get quadratic inequality $$a^2\_{n+1}-2a\_{n+1}a\_{n}+a^2\_{n}\ge 0$$ which gets me to $$0\le a\_{n}\le 1$$ thus, sequence is bounded. I get that sequence is not monotonic, because $$a\_{n}\le a\_{n+2} \le {a\_{n+1}}$$ or $$a\_{n+1}\le a\_{n+2} \le {a\_{n}}$$ Is this right?
2015/06/06
[ "https://math.stackexchange.com/questions/1314640", "https://math.stackexchange.com", "https://math.stackexchange.com/users/222321/" ]
Let $c\_n=\log a\_n$. Then the sequence $\{c\_n\}\_{n\in\mathbb N}$ satisfies the recursive relation: $$ c\_{n+2}=\frac{1}{2}c\_{n+1}+\frac{1}{2}c\_{n}, \quad c\_1=\log a,\,\,c\_2=\log b. $$ Then we have $$ c\_{n+2}-c\_{n+1}=-\frac{1}{2}\big(c\_{n+1}-c\_{n})=\cdots=\frac{(-1)^n}{2^n}(c\_2-c\_1). \tag{1} $$ Also $$ c\_{n+2}+\frac{1}{2}c\_{n+1}=c\_{n+1}+\frac{1}{2}c\_{n}=\cdots=c\_{2}+\frac{1}{2}c\_{1}. \tag{2} $$ Combining $(1)$ and $(2)$ we obtain $$ c\_{n+2}=\frac{1}{3}\left(2c\_2+c\_1+\frac{(-1)^n}{2^n}(c\_2-c\_1)\right) $$ and hence $$ a\_n=a^{1/3}b^{2/3}\left(\frac{b}{a}\right)^{(-1)^n/2^{n-2}}\to a^{1/3}b^{2/3}, $$ since $c^{1/2^n}\to 1$, for every $c>0$. Note. Proving convergence, without finding the limit, is simpler, as $\{a\_{2n+1}\}$ is increasing, $\{a\_{2n}\}$ is decreasing, and $a\_{2n+2}/a\_{2n+1}=\sqrt{a\_{2n}/a\_{2n-1}}=(a\_2/a\_1)^{1/2^n}\to 1$.
A shortcut: assume that a real sequence is given by some values of $c\_1,c\_2$ and the recurrence relation $c\_{n+2}=\frac{c\_n+c\_{n+1}}{2}$. Then it is convergent since: $$ \left|c\_{n+1}-c\_n\right|=\frac{1}{2}\left|c\_{n}-c\_{n-1}\right| \tag{1}$$ and it converges to $\frac{c\_1+2c\_2}{3}$ since: $$ c\_{n}+2 c\_{n+1} = c\_{n+1}+2 c\_{n+2}.\tag{2} $$ By setting $c\_n=\log a\_n$, it follows that: $$ \lim\_{n\to +\infty} a\_n = \sqrt[3]{a\_1 a\_2^2}.\tag{3}$$
15,367,474
I'm trying to get started using Selenium with Chrome, i've had no previous trouble dealing with Selenium+Firefox, but i cannot seem to launch a Chrome browser now - every time I try, a Firefox browser appears instead. Here is my setup: ``` $web_driver = new ChromeDriver("C:\chromedriver\chromedriver.exe"); $session = $web_driver->session('chrome'); ``` I realise the first line is likely not to be correct. But i cannot think of how else to initiate Chrome. Note: I have already downloaded the chrome web driver. Here are the sources i used: <http://edvanbeinum.com/using-selenium-2-phpunit-to-automate-browser-testing> <https://code.google.com/p/selenium/wiki/ChromeDriver> Many thanks.
2013/03/12
[ "https://Stackoverflow.com/questions/15367474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2030573/" ]
Try using ``` $session = $web_driver->session('googlechrome'); ``` instead of ``` $session = $web_driver->session('chrome'); ```
You might want to take a look [here](https://github.com/facebook/php-webdriver/wiki/ChromeDriver) and [here](https://github.com/facebook/php-webdriver). ``` $host = 'http://localhost:4444/wd/hub'; // this is the default $capabilities = DesiredCapabilities::htmlUnitWithJS(); { // For Chrome $options = new ChromeOptions(); $prefs = array('download.default_directory' => 'c:/temp'); $options->setExperimentalOption('prefs', $prefs); $capabilities = DesiredCapabilities::chrome(); $capabilities->setCapability(ChromeOptions::CAPABILITY, $options); } $driver = RemoteWebDriver::create($host, $capabilities, 5000); ```
56,746,385
I have some configurations in my application.properties file: ``` ... quarkus.datasource.url=jdbc:postgresql://...:5432/.... quarkus.datasource.driver=org.postgresql.Driver quarkus.datasource.username=user quarkus.datasource.password=password quarkus.hibernate-orm.database.generation=update ... ``` I have a scheduler with a @Transactional method that takes a long time to finish executing: ``` @ApplicationScoped class MyScheduler { ... @Transactional @Scheduled(every = "7200s") open fun process() { ... my slow proccess goes here... entityManager.persist(myObject) } } ``` And then, the transactional method receives a timeout error like that: ``` 2019-06-24 20:11:59,874 WARN [com.arj.ats.arjuna] (Transaction Reaper) ARJUNA012117: TransactionReaper::check timeout for TX 0:ffff0a000020:d58d:5cdad26e:81 in state RUN 2019-06-24 20:12:47,198 WARN [com.arj.ats.arjuna] (DefaultQuartzScheduler_Worker-3) ARJUNA012077: Abort called on already aborted atomic action 0:ffff0a000020:d58d:5cdad26e:81 Caused by: javax.transaction.RollbackException: ARJUNA016102: The transaction is not active! Uid is 0:ffff0a000020:d58d:5cdad26e:81 ``` I believe that I must increase the timeout of my transacional method. But I dont know how I can do this. Someone could help me, please? Thanks!
2019/06/25
[ "https://Stackoverflow.com/questions/56746385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11283188/" ]
Quarkus don't allow you to globally configure the default transaction timeout yet (see <https://github.com/quarkusio/quarkus/pull/2984>). But you should be able to do this at the user transaction level. You can inject the UserTransaction object and set the transaction timeout in a postconstruct bloc. Something like this should work : ``` @ApplicationScoped class MyScheduler { @Inject UserTransaction userTransaction; @PostConstruct fun init() { //set a timeout as high as you need userTransaction.setTransactionTimeout(3600); } @Transactional @Scheduled(every = "7200s") open fun process() { entityManager.persist(myObject) } } ``` If you extract the code that make the transaction inside a Service, you can have a service with a @Transactional annotation, inject the UserTransaction in your scheduler and set the transaction timeout before calling the service. All this works, I just tested both solution ;)
Thanks @loicmathieu for the answer! I will just append some more details below. You need to remove @Transactional and set transaction timeout before begin the transaction. In the end, you must commit the transaction: ``` import io.quarkus.scheduler.Scheduled import javax.enterprise.context.ApplicationScoped import javax.inject.Inject import javax.transaction.UserTransaction @ApplicationScoped open class MyScheduler { @Inject lateinit var em: EntityManager @Inject lateinit var ut: UserTransaction @Scheduled(every = "3600s") open fun process() { ut.setTransactionTimeout(3600) ut.begin() offerService.processOffers() ut.commit() } } ```
56,746,385
I have some configurations in my application.properties file: ``` ... quarkus.datasource.url=jdbc:postgresql://...:5432/.... quarkus.datasource.driver=org.postgresql.Driver quarkus.datasource.username=user quarkus.datasource.password=password quarkus.hibernate-orm.database.generation=update ... ``` I have a scheduler with a @Transactional method that takes a long time to finish executing: ``` @ApplicationScoped class MyScheduler { ... @Transactional @Scheduled(every = "7200s") open fun process() { ... my slow proccess goes here... entityManager.persist(myObject) } } ``` And then, the transactional method receives a timeout error like that: ``` 2019-06-24 20:11:59,874 WARN [com.arj.ats.arjuna] (Transaction Reaper) ARJUNA012117: TransactionReaper::check timeout for TX 0:ffff0a000020:d58d:5cdad26e:81 in state RUN 2019-06-24 20:12:47,198 WARN [com.arj.ats.arjuna] (DefaultQuartzScheduler_Worker-3) ARJUNA012077: Abort called on already aborted atomic action 0:ffff0a000020:d58d:5cdad26e:81 Caused by: javax.transaction.RollbackException: ARJUNA016102: The transaction is not active! Uid is 0:ffff0a000020:d58d:5cdad26e:81 ``` I believe that I must increase the timeout of my transacional method. But I dont know how I can do this. Someone could help me, please? Thanks!
2019/06/25
[ "https://Stackoverflow.com/questions/56746385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11283188/" ]
Quarkus don't allow you to globally configure the default transaction timeout yet (see <https://github.com/quarkusio/quarkus/pull/2984>). But you should be able to do this at the user transaction level. You can inject the UserTransaction object and set the transaction timeout in a postconstruct bloc. Something like this should work : ``` @ApplicationScoped class MyScheduler { @Inject UserTransaction userTransaction; @PostConstruct fun init() { //set a timeout as high as you need userTransaction.setTransactionTimeout(3600); } @Transactional @Scheduled(every = "7200s") open fun process() { entityManager.persist(myObject) } } ``` If you extract the code that make the transaction inside a Service, you can have a service with a @Transactional annotation, inject the UserTransaction in your scheduler and set the transaction timeout before calling the service. All this works, I just tested both solution ;)
Use the @TransactionConfiguration annotation and specify the seconds: ``` @Transactional @TransactionConfiguration(timeout = 9876) @Scheduled(every = "7200s") open fun process() { ... my slow proccess goes here... entityManager.persist(myObject) } ```
56,746,385
I have some configurations in my application.properties file: ``` ... quarkus.datasource.url=jdbc:postgresql://...:5432/.... quarkus.datasource.driver=org.postgresql.Driver quarkus.datasource.username=user quarkus.datasource.password=password quarkus.hibernate-orm.database.generation=update ... ``` I have a scheduler with a @Transactional method that takes a long time to finish executing: ``` @ApplicationScoped class MyScheduler { ... @Transactional @Scheduled(every = "7200s") open fun process() { ... my slow proccess goes here... entityManager.persist(myObject) } } ``` And then, the transactional method receives a timeout error like that: ``` 2019-06-24 20:11:59,874 WARN [com.arj.ats.arjuna] (Transaction Reaper) ARJUNA012117: TransactionReaper::check timeout for TX 0:ffff0a000020:d58d:5cdad26e:81 in state RUN 2019-06-24 20:12:47,198 WARN [com.arj.ats.arjuna] (DefaultQuartzScheduler_Worker-3) ARJUNA012077: Abort called on already aborted atomic action 0:ffff0a000020:d58d:5cdad26e:81 Caused by: javax.transaction.RollbackException: ARJUNA016102: The transaction is not active! Uid is 0:ffff0a000020:d58d:5cdad26e:81 ``` I believe that I must increase the timeout of my transacional method. But I dont know how I can do this. Someone could help me, please? Thanks!
2019/06/25
[ "https://Stackoverflow.com/questions/56746385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11283188/" ]
Seems that this has changed -> it is now possible to set the Transaction timeout: <https://quarkus.io/guides/transaction> You can configure the default transaction timeout, the timeout that applies to all transactions managed by the transaction manager, via the property: ``` quarkus.transaction-manager.default-transaction-timeout = 240s ``` -> specified as a duration (java.time.Duration format). Default is 60 sec
Thanks @loicmathieu for the answer! I will just append some more details below. You need to remove @Transactional and set transaction timeout before begin the transaction. In the end, you must commit the transaction: ``` import io.quarkus.scheduler.Scheduled import javax.enterprise.context.ApplicationScoped import javax.inject.Inject import javax.transaction.UserTransaction @ApplicationScoped open class MyScheduler { @Inject lateinit var em: EntityManager @Inject lateinit var ut: UserTransaction @Scheduled(every = "3600s") open fun process() { ut.setTransactionTimeout(3600) ut.begin() offerService.processOffers() ut.commit() } } ```
56,746,385
I have some configurations in my application.properties file: ``` ... quarkus.datasource.url=jdbc:postgresql://...:5432/.... quarkus.datasource.driver=org.postgresql.Driver quarkus.datasource.username=user quarkus.datasource.password=password quarkus.hibernate-orm.database.generation=update ... ``` I have a scheduler with a @Transactional method that takes a long time to finish executing: ``` @ApplicationScoped class MyScheduler { ... @Transactional @Scheduled(every = "7200s") open fun process() { ... my slow proccess goes here... entityManager.persist(myObject) } } ``` And then, the transactional method receives a timeout error like that: ``` 2019-06-24 20:11:59,874 WARN [com.arj.ats.arjuna] (Transaction Reaper) ARJUNA012117: TransactionReaper::check timeout for TX 0:ffff0a000020:d58d:5cdad26e:81 in state RUN 2019-06-24 20:12:47,198 WARN [com.arj.ats.arjuna] (DefaultQuartzScheduler_Worker-3) ARJUNA012077: Abort called on already aborted atomic action 0:ffff0a000020:d58d:5cdad26e:81 Caused by: javax.transaction.RollbackException: ARJUNA016102: The transaction is not active! Uid is 0:ffff0a000020:d58d:5cdad26e:81 ``` I believe that I must increase the timeout of my transacional method. But I dont know how I can do this. Someone could help me, please? Thanks!
2019/06/25
[ "https://Stackoverflow.com/questions/56746385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11283188/" ]
Seems that this has changed -> it is now possible to set the Transaction timeout: <https://quarkus.io/guides/transaction> You can configure the default transaction timeout, the timeout that applies to all transactions managed by the transaction manager, via the property: ``` quarkus.transaction-manager.default-transaction-timeout = 240s ``` -> specified as a duration (java.time.Duration format). Default is 60 sec
Use the @TransactionConfiguration annotation and specify the seconds: ``` @Transactional @TransactionConfiguration(timeout = 9876) @Scheduled(every = "7200s") open fun process() { ... my slow proccess goes here... entityManager.persist(myObject) } ```
60,520,685
I'm provided with a .txt file every day which contains semicolon-separated data. Users of my app are meant to upload this file to the database daily. Currently, I'm reading and storing the information as such: ``` $array = array(); $csv = str_getcsv($request->file, "\n"); foreach ($csv as &$row) { $row = str_getcsv($row, ";"); $array[] = $row; } array_splice($array, 0, 1); foreach ($array as &$row) { $query = Table::firstOrNew(['col2' => $row[1], 'col3' => $row[2]]); $query->col1 = $row[0]; $query->col2 = $row[1]; $query->col3 = $row[2]; $query->col4 = $row[3]; $query->col5 = $row[4]; // [...] $query->col72 = $row[71]; $query->col73 = $row[72]; $query->save(); } ``` The thing with this method is that it takes too long to run successfully (the volume of data is about 5000 entries a day, which takes ~2 minutes to complete with the above code). As you can see, the amount of columns is immense, and the data has to be read as if dealing with a.CSV file, plus I cannot discard any of them at all. Not to mention this problem increases in great magnitude if, for some reason, a user (or more) has to **upload multiple days or even a month worth of data at once**. I need to figure out a better way to handle this situation. I've searched around for a solution but the best I could find was that I should use a `for` loop instead of `foreach`, which didn't really solve the issue.
2020/03/04
[ "https://Stackoverflow.com/questions/60520685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The [`Start-Process`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process) cmdlet has a [`-AgumentList`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7#parameters) parameter: ``` $direct = "D:\Learn" Start-Process powershell.exe -WindowStyle Minimized ".\Testing.exe" -ArgumentList "-Path $direct" ```
I think they all were arguments of powershell.exe. The whole argument can be wrapped in one double quote in argumentlist. ``` Start-Process "powershell.exe" -ArgumentList "-windowstyle minimized '.\testing.exe' -path $direct" ``` Or even it can be done without start-process: ``` & "powershell.exe -windowstyle minimized '.\testing.exe' -path $direct" ```
60,520,685
I'm provided with a .txt file every day which contains semicolon-separated data. Users of my app are meant to upload this file to the database daily. Currently, I'm reading and storing the information as such: ``` $array = array(); $csv = str_getcsv($request->file, "\n"); foreach ($csv as &$row) { $row = str_getcsv($row, ";"); $array[] = $row; } array_splice($array, 0, 1); foreach ($array as &$row) { $query = Table::firstOrNew(['col2' => $row[1], 'col3' => $row[2]]); $query->col1 = $row[0]; $query->col2 = $row[1]; $query->col3 = $row[2]; $query->col4 = $row[3]; $query->col5 = $row[4]; // [...] $query->col72 = $row[71]; $query->col73 = $row[72]; $query->save(); } ``` The thing with this method is that it takes too long to run successfully (the volume of data is about 5000 entries a day, which takes ~2 minutes to complete with the above code). As you can see, the amount of columns is immense, and the data has to be read as if dealing with a.CSV file, plus I cannot discard any of them at all. Not to mention this problem increases in great magnitude if, for some reason, a user (or more) has to **upload multiple days or even a month worth of data at once**. I need to figure out a better way to handle this situation. I've searched around for a solution but the best I could find was that I should use a `for` loop instead of `foreach`, which didn't really solve the issue.
2020/03/04
[ "https://Stackoverflow.com/questions/60520685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you want to just run a *File* with some *arguments* ``` $filepath = ".\Testing.exe" $direct = "D:\Learn" Start-Process -FilePath $filepath -ArgumentList $direct -Wait -NoNewWindow ```
I think they all were arguments of powershell.exe. The whole argument can be wrapped in one double quote in argumentlist. ``` Start-Process "powershell.exe" -ArgumentList "-windowstyle minimized '.\testing.exe' -path $direct" ``` Or even it can be done without start-process: ``` & "powershell.exe -windowstyle minimized '.\testing.exe' -path $direct" ```
51,700,834
usNumber represents the sequence number. cUnitID represents the cassette identifier, but different vendors have different formats to represent it. Where can I find this format? Is there any other place where I can get the logical cash unit identifier (Type number)
2018/08/06
[ "https://Stackoverflow.com/questions/51700834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10180564/" ]
first of all, i do not know what you mean "different formats".usType defined by wosa/xfs library. below definition are from Xfscdm.h, and they are fixed. ``` /* values of WFSCDMCASHUNIT.usType */ #define WFS_CDM_TYPENA (1) #define WFS_CDM_TYPEREJECTCASSETTE (2) #define WFS_CDM_TYPEBILLCASSETTE (3) #define WFS_CDM_TYPECOINCYLINDER (4) #define WFS_CDM_TYPECOINDISPENSER (5) #define WFS_CDM_TYPERETRACTCASSETTE (6) #define WFS_CDM_TYPECOUPON (7) #define WFS_CDM_TYPEDOCUMENT (8) #define WFS_CDM_TYPEREPCONTAINER (11) #define WFS_CDM_TYPERECYCLING (12) ``` anyway, below function can hep you to get cash unit information: ``` #include "Xfsapi.h" #include "Xfscdm.h" HRESULT getCashUnitInfo(); HSERVICE hService; USHORT cashUnitCount; // Number of Logical Cash Units LPWFSCDMCASHUNIT cashUnitInfo[6]; int main() { if(getCashUnitInfo()==WFS_SUCCESS) { printf("Get CashUnit Info Failed\n"); return -1; } printf("Get Cash Unit Info Success.\n"); return 0; } HRESULT getCashUnitInfo() { LPWFSRESULT result; HRESULT r; r=WFSGetInfo(hService, WFS_INF_CDM_CASH_UNIT_INFO, NULL,20000, &result ); if ( r == WFS_SUCCESS) { LPWFSCDMCUINFO cuInfo = (LPWFSCDMCUINFO)result->lpBuffer; cashUnitCount = cuInfo->usCount; ZF_LOGI("m_CashUnitCount:%d",cashUnitCount); LPWFSCDMCASHUNIT * lppList = cuInfo->lppList; for ( int i = 0; i < cuInfo->usCount; ++i ) { USHORT no = lppList[i]->usNumber -1; if (cashUnitInfo[no] == NULL) cashUnitInfo[no] = new WFSCDMCASHUNIT(); //Copy logical Cash Unit info memcpy(cashUnitInfo[no], lppList[i], sizeof(WFSCDMCASHUNIT) ); printf("m_CashUnitInfo[%d]->bAppLock----------------->%d\n",i,cashUnitInfo[no]->bAppLock); printf("m_CashUnitInfo[%d]->bDevLock----------------->%d\n",i,cashUnitInfo[no]->bDevLock); printf("m_CashUnitInfo[%d]->cCurrencyID-------------->%s\n",i,cashUnitInfo[no]->cCurrencyID); printf("m_CashUnitInfo[%d]->cUnitID------------------>%s\n",i,cashUnitInfo[no]->cUnitID); printf("m_CashUnitInfo[%d]->lpszCashUnitName--------->%s\n",i,cashUnitInfo[no]->lpszCashUnitName); printf("m_CashUnitInfo[%d]->ulCount------------------>%ld\n",i,cashUnitInfo[no]->ulCount); printf("m_CashUnitInfo[%d]->ulInitialCount----------->%ld\n",i,cashUnitInfo[no]->ulInitialCount); printf("m_CashUnitInfo[%d]->ulMaximum---------------->%ld\n",i,cashUnitInfo[no]->ulMaximum); printf("m_CashUnitInfo[%d]->ulMinimum---------------->%ld\n",i,cashUnitInfo[no]->ulMinimum); printf("m_CashUnitInfo[%d]->ulRejectCount------------>%ld\n",i,cashUnitInfo[no]->ulRejectCount); printf("m_CashUnitInfo[%d]->ulValues----------------->%ld\n",i,cashUnitInfo[no]->ulValues); printf("m_CashUnitInfo[%d]->usNumber----------------->%hu\n",i,cashUnitInfo[no]->usNumber); printf("m_CashUnitInfo[%d]->usStatus----------------->%hu\n",i,cashUnitInfo[no]->usStatus); printf("m_CashUnitInfo[%d]->usType------------------->%hu\n",i,cashUnitInfo[no]->usType); printf("m_CashUnitInfo[%d]->usNumPhysicalCUs--------->%hu\n",i,cashUnitInfo[no]->usNumPhysicalCUs); printf("--------------------------------------------------------------------------------------------------\n"); } } WFSFreeResult( result ); printf("RESULT:%d\n",r); return r; } ```
In addition to the suggested answer which is OK, don't forget to allocate enough memory for printing out the results, e.g r = WFMAllocateMore(sizeof(WFSCDMCASHUNIT), result, (void\*\*)&cashUnitInfo[no]);
857
I have one portfolio with high beta stocks, and one with low beta stocks. Is it better to have higher expected return with high volatility, or medium expected return with medium volatility? (All from a asset allocation, efficient frontier, risk/reward prospective.)
2011/03/30
[ "https://quant.stackexchange.com/questions/857", "https://quant.stackexchange.com", "https://quant.stackexchange.com/users/520/" ]
Most portfolio managers look at the [Sharpe ratio](http://en.wikipedia.org/wiki/Sharpe_ratio), or occasionally the [Treynor ratio](http://en.wikipedia.org/wiki/Treynor_ratio). In general, you want to maximize one of the these metrics, though there could be other issues that you haven't currently considered, like turnover or transaction costs associated with obtaining the portfolio.
The empirical evidence shows that low to medium beta portfolios beat high beta portfolios on a risk adjusted basis. Search SSRN for "betting against beta." This flies completely in the face of CAPM but frankly CAPM is crap.
857
I have one portfolio with high beta stocks, and one with low beta stocks. Is it better to have higher expected return with high volatility, or medium expected return with medium volatility? (All from a asset allocation, efficient frontier, risk/reward prospective.)
2011/03/30
[ "https://quant.stackexchange.com/questions/857", "https://quant.stackexchange.com", "https://quant.stackexchange.com/users/520/" ]
Most portfolio managers look at the [Sharpe ratio](http://en.wikipedia.org/wiki/Sharpe_ratio), or occasionally the [Treynor ratio](http://en.wikipedia.org/wiki/Treynor_ratio). In general, you want to maximize one of the these metrics, though there could be other issues that you haven't currently considered, like turnover or transaction costs associated with obtaining the portfolio.
You still want to perform portfolio optimization. Put everything into one bucket, run 'global' portfolio optimization, build the portfolio. Even if you prefer Sharpe ratios, you should do that on the overall portfolio - not just on individual ones. Be careful of sharpe ratios for low risk, low return assets. Dividing one small number by another small number can sometimes give you a giant number and you can't always lever that up as you please (you hit the friction of overleverage => higher borrowing rate) Now if you *must* pick only one over the other (I'm assuming you've questioned why this limitation applies to you), then you should run a monte carlo simulation or perform some back testing of both portfolios. In a temporal way, the world is similar (same management, similar human attributes etc) but not exact (tech bust won't be *exactly* played out next time). Therefore I prefer Monte Carlo (using historical distributions from which to draw simulation outcomes) over straight up back testing ("In 2001, this portfolio would have looked like ...")
857
I have one portfolio with high beta stocks, and one with low beta stocks. Is it better to have higher expected return with high volatility, or medium expected return with medium volatility? (All from a asset allocation, efficient frontier, risk/reward prospective.)
2011/03/30
[ "https://quant.stackexchange.com/questions/857", "https://quant.stackexchange.com", "https://quant.stackexchange.com/users/520/" ]
From a theoretical point of view (you mentioned beta, so assume we're in a CAPM world), you should hold the market portfolio (let's assume S&P500 index) and be long (or short) the risk-free asset to decrease (or increase) your return and risk. That is, if you'd like higher returns than the S&P500 offers and are willing to accept the risk, trade the S&P500 index on margin. Again, theoretically, you want to hold a portfolio along the line tangent to the efficient frontier. In the real world, maybe you can't lever up and trade on margin (maybe borrowing from the bank to buy an S&P500 index fund), so then you'd want to look at an equity only portfolio with a beta greater than one. If you're looking at portfolio with a beta below one, then it seems that you should just hold the market and risk-free debt (maybe a money market savings account or low-yield corporate debt index fund, depending on your liquidity needs), which should outperform your low beta portfolio for a given level of risk. Assuming that you've minimized risk for a given return (i.e., you're on the efficient frontier), then ultimately your risk aversion will determine your trade off between risk and return (i.e., picking the right beta). I agree with Chris that the Sharpe and Treynor ratios are good ways of quantifying the risk-return trade-offs in each of these portfolios. Although not viewed as rational in the strict sense, given that you likely need this capital for retirement or buying a house, you may want to also look at value-at-risk (VaR) or expected shortfall (ES) to quantify how much you could lose in some hypothesized worst-case scenario. Of course, there are some problems with these measures, but they're illustrative.
The empirical evidence shows that low to medium beta portfolios beat high beta portfolios on a risk adjusted basis. Search SSRN for "betting against beta." This flies completely in the face of CAPM but frankly CAPM is crap.
857
I have one portfolio with high beta stocks, and one with low beta stocks. Is it better to have higher expected return with high volatility, or medium expected return with medium volatility? (All from a asset allocation, efficient frontier, risk/reward prospective.)
2011/03/30
[ "https://quant.stackexchange.com/questions/857", "https://quant.stackexchange.com", "https://quant.stackexchange.com/users/520/" ]
From a theoretical point of view (you mentioned beta, so assume we're in a CAPM world), you should hold the market portfolio (let's assume S&P500 index) and be long (or short) the risk-free asset to decrease (or increase) your return and risk. That is, if you'd like higher returns than the S&P500 offers and are willing to accept the risk, trade the S&P500 index on margin. Again, theoretically, you want to hold a portfolio along the line tangent to the efficient frontier. In the real world, maybe you can't lever up and trade on margin (maybe borrowing from the bank to buy an S&P500 index fund), so then you'd want to look at an equity only portfolio with a beta greater than one. If you're looking at portfolio with a beta below one, then it seems that you should just hold the market and risk-free debt (maybe a money market savings account or low-yield corporate debt index fund, depending on your liquidity needs), which should outperform your low beta portfolio for a given level of risk. Assuming that you've minimized risk for a given return (i.e., you're on the efficient frontier), then ultimately your risk aversion will determine your trade off between risk and return (i.e., picking the right beta). I agree with Chris that the Sharpe and Treynor ratios are good ways of quantifying the risk-return trade-offs in each of these portfolios. Although not viewed as rational in the strict sense, given that you likely need this capital for retirement or buying a house, you may want to also look at value-at-risk (VaR) or expected shortfall (ES) to quantify how much you could lose in some hypothesized worst-case scenario. Of course, there are some problems with these measures, but they're illustrative.
You still want to perform portfolio optimization. Put everything into one bucket, run 'global' portfolio optimization, build the portfolio. Even if you prefer Sharpe ratios, you should do that on the overall portfolio - not just on individual ones. Be careful of sharpe ratios for low risk, low return assets. Dividing one small number by another small number can sometimes give you a giant number and you can't always lever that up as you please (you hit the friction of overleverage => higher borrowing rate) Now if you *must* pick only one over the other (I'm assuming you've questioned why this limitation applies to you), then you should run a monte carlo simulation or perform some back testing of both portfolios. In a temporal way, the world is similar (same management, similar human attributes etc) but not exact (tech bust won't be *exactly* played out next time). Therefore I prefer Monte Carlo (using historical distributions from which to draw simulation outcomes) over straight up back testing ("In 2001, this portfolio would have looked like ...")
23,344,625
I would like to create a custom event in JavaScript. I have a WPF application with a WebBrowser inside, and a HTML page with JavaScript. I work with a printer. When the state of the printer changes, it triggers an event in .NET. Then, I call a JavaScript method `OnPrinterStateChanged(state)` with the `InvokeScript` function of the WebBrowser control. The problem is that I have to implement the method `OnPrinterStateChanged(state)` in my webpage. I can't change the name of the method or subscribe/unsubscribe to the event... I would like to move the JavaScript method `OnPrinterStateChanged(state)` in a separate JavaScript file. What I want : * Subscribe/Unsubscribe to the event in my HTML page and decide what I want to do when the event is triggered (ex. : "function ChangeState") * When the .NET event is triggered, it calls the `OnPrinterStateChanged(state)` of my separate .js file, then the JavaScript event is triggered and the function `ChangeState` is called. I found some solutions but I didn't manage to make it work... What is the simplest way to do it?
2014/04/28
[ "https://Stackoverflow.com/questions/23344625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558653/" ]
Perhaps something like this? ``` function OnPrinterStateChanged(state) { var evt = new CustomEvent('printerstatechanged', { detail: state }); window.dispatchEvent(evt); } //Listen to your custom event window.addEventListener('printerstatechanged', function (e) { console.log('printer state changed', e.detail); }); ``` An alternative solution would be to use function composition, but then it would be hard to remove specific listeners. ``` function OnPrinterStateChanged(state) {} function compose(fn1, fn2) { return function () { fn1.apply(this, arguments); fn2.apply(this, arguments); }; } //Add a new listener OnPrinterStateChanged = compose(OnPrinterStateChanged, function (state) { console.log('listener 1'); }); //Add another one OnPrinterStateChanged = compose(OnPrinterStateChanged, function (state) { console.log('listener 2'); }); ``` EDIT: Here's how you can do it with jQuery. ``` function OnPrinterStateChanged(state) { var evt = $.Event('printerstatechanged'); evt.state = state; $(window).trigger(evt); } //Listen to your custom event $(window).on('printerstatechanged', function (e) { console.log('printer state changed', e.state); }); ```
Ok I found a solution. I had to change the WebBrowser IE Version to Internet Explorer 11: <http://weblog.west-wind.com/posts/2011/May/21/Web-Browser-Control-Specifying-the-IE-Version> And then : ``` function OnPrinterStateChanged(state) { var evt = document.createEvent("Event"); evt.state = state; evt.initEvent("printerstatechanged", true, false); window.dispatchEvent(evt); } window.addEventListener('printerstatechanged', function (e) { // Do something }); ```
23,344,625
I would like to create a custom event in JavaScript. I have a WPF application with a WebBrowser inside, and a HTML page with JavaScript. I work with a printer. When the state of the printer changes, it triggers an event in .NET. Then, I call a JavaScript method `OnPrinterStateChanged(state)` with the `InvokeScript` function of the WebBrowser control. The problem is that I have to implement the method `OnPrinterStateChanged(state)` in my webpage. I can't change the name of the method or subscribe/unsubscribe to the event... I would like to move the JavaScript method `OnPrinterStateChanged(state)` in a separate JavaScript file. What I want : * Subscribe/Unsubscribe to the event in my HTML page and decide what I want to do when the event is triggered (ex. : "function ChangeState") * When the .NET event is triggered, it calls the `OnPrinterStateChanged(state)` of my separate .js file, then the JavaScript event is triggered and the function `ChangeState` is called. I found some solutions but I didn't manage to make it work... What is the simplest way to do it?
2014/04/28
[ "https://Stackoverflow.com/questions/23344625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558653/" ]
Perhaps something like this? ``` function OnPrinterStateChanged(state) { var evt = new CustomEvent('printerstatechanged', { detail: state }); window.dispatchEvent(evt); } //Listen to your custom event window.addEventListener('printerstatechanged', function (e) { console.log('printer state changed', e.detail); }); ``` An alternative solution would be to use function composition, but then it would be hard to remove specific listeners. ``` function OnPrinterStateChanged(state) {} function compose(fn1, fn2) { return function () { fn1.apply(this, arguments); fn2.apply(this, arguments); }; } //Add a new listener OnPrinterStateChanged = compose(OnPrinterStateChanged, function (state) { console.log('listener 1'); }); //Add another one OnPrinterStateChanged = compose(OnPrinterStateChanged, function (state) { console.log('listener 2'); }); ``` EDIT: Here's how you can do it with jQuery. ``` function OnPrinterStateChanged(state) { var evt = $.Event('printerstatechanged'); evt.state = state; $(window).trigger(evt); } //Listen to your custom event $(window).on('printerstatechanged', function (e) { console.log('printer state changed', e.state); }); ```
I like using this `EventDispatcher` constructor method, which, using a dummy element, isolates the events so they will not be fired on any existing DOM element, nor the `window` or `document`. > > I am using `CustomEvent` and not `createEvent` because it's the newer > approach. [Read more here](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events). > > > I like to wrap each native method with these names: `on`, `off`, `trigger` ---------------------- ```js function eventDispatcher(){ // Create a dummy DOM element, which is a local variable var dummy = document.createTextNode('') // Create custom wrappers with nicer names return { off(...args){ dummy.removeEventListener(...args) return this }, on(...args){ dummy.addEventListener(...args) return this }, trigger(eventName, data){ if( !eventName ) return // if the event should be allowed to bubble, // then "dummy" must be in the DOM var e = new CustomEvent(eventName, {detail:data}) dummy.dispatchEvent(e) return this } } } //////////////////////////////////// // initialize the event dispatcher by creating an instance in an isolated way var myEventDispatcher = eventDispatcher(); //////////////////////////////////// // listen to a "foo" event myEventDispatcher .on('foo', e => console.log(e.type, e.detail) ) .on('bar', e => console.log(e.type, e.detail) ) //////////////////////////////////// // trigger a "foo" event with some data myEventDispatcher .trigger('foo', 123) .trigger('bar', 987); ``` --- The above `eventDispatcher` could be integrated into another code, for example, a Constructor: *(for example some component)* ```js function eventDispatcher(){ var dummy = document.createTextNode('') return { off(...args){ dummy.removeEventListener(...args) return this }, on(...args){ dummy.addEventListener(...args) return this }, trigger(eventName, data){ if( !eventName ) return var e = new CustomEvent(eventName, {detail:data}) dummy.dispatchEvent(e) return this } } } ///////////////////////////// // Some component: var MyComponent = function(){ // merge `EventDispatcher` instance into "this" instance Object.assign(this, eventDispatcher()) // set some default value this.value = 1 } MyComponent.prototype = { set value(v){ this.trigger('change', v) } } var comp = new MyComponent(); // bind a listener to "comp" (which itself is an instance of "MyComponent") comp.on('change', e => console.log("Type:", e.type,", Value:", e.detail) ) // set some value comp.value = 3; ``` --- **See my related [answer](https://stackoverflow.com/a/44432013/104380), which shows a more complex implementation of the above**
23,344,625
I would like to create a custom event in JavaScript. I have a WPF application with a WebBrowser inside, and a HTML page with JavaScript. I work with a printer. When the state of the printer changes, it triggers an event in .NET. Then, I call a JavaScript method `OnPrinterStateChanged(state)` with the `InvokeScript` function of the WebBrowser control. The problem is that I have to implement the method `OnPrinterStateChanged(state)` in my webpage. I can't change the name of the method or subscribe/unsubscribe to the event... I would like to move the JavaScript method `OnPrinterStateChanged(state)` in a separate JavaScript file. What I want : * Subscribe/Unsubscribe to the event in my HTML page and decide what I want to do when the event is triggered (ex. : "function ChangeState") * When the .NET event is triggered, it calls the `OnPrinterStateChanged(state)` of my separate .js file, then the JavaScript event is triggered and the function `ChangeState` is called. I found some solutions but I didn't manage to make it work... What is the simplest way to do it?
2014/04/28
[ "https://Stackoverflow.com/questions/23344625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558653/" ]
Perhaps something like this? ``` function OnPrinterStateChanged(state) { var evt = new CustomEvent('printerstatechanged', { detail: state }); window.dispatchEvent(evt); } //Listen to your custom event window.addEventListener('printerstatechanged', function (e) { console.log('printer state changed', e.detail); }); ``` An alternative solution would be to use function composition, but then it would be hard to remove specific listeners. ``` function OnPrinterStateChanged(state) {} function compose(fn1, fn2) { return function () { fn1.apply(this, arguments); fn2.apply(this, arguments); }; } //Add a new listener OnPrinterStateChanged = compose(OnPrinterStateChanged, function (state) { console.log('listener 1'); }); //Add another one OnPrinterStateChanged = compose(OnPrinterStateChanged, function (state) { console.log('listener 2'); }); ``` EDIT: Here's how you can do it with jQuery. ``` function OnPrinterStateChanged(state) { var evt = $.Event('printerstatechanged'); evt.state = state; $(window).trigger(evt); } //Listen to your custom event $(window).on('printerstatechanged', function (e) { console.log('printer state changed', e.state); }); ```
Requirement: ES6 ```js let MyClass = (function () { let __sym = Symbol('MyClass'); class MyClass { constructor() { this[__sym] = {}; } on(event, callback) { this[__sym][event] = { callback: callback } } getError() { let event = this[__sym].error; if (event && event.callback) { event.callback('some parameter'); } } } return MyClass; }()); let myClass = new MyClass(); myClass.on('error', function (e) { console.log('error:', e); }); console.log('before getting error:'); myClass.getError(); ```
23,344,625
I would like to create a custom event in JavaScript. I have a WPF application with a WebBrowser inside, and a HTML page with JavaScript. I work with a printer. When the state of the printer changes, it triggers an event in .NET. Then, I call a JavaScript method `OnPrinterStateChanged(state)` with the `InvokeScript` function of the WebBrowser control. The problem is that I have to implement the method `OnPrinterStateChanged(state)` in my webpage. I can't change the name of the method or subscribe/unsubscribe to the event... I would like to move the JavaScript method `OnPrinterStateChanged(state)` in a separate JavaScript file. What I want : * Subscribe/Unsubscribe to the event in my HTML page and decide what I want to do when the event is triggered (ex. : "function ChangeState") * When the .NET event is triggered, it calls the `OnPrinterStateChanged(state)` of my separate .js file, then the JavaScript event is triggered and the function `ChangeState` is called. I found some solutions but I didn't manage to make it work... What is the simplest way to do it?
2014/04/28
[ "https://Stackoverflow.com/questions/23344625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558653/" ]
I like using this `EventDispatcher` constructor method, which, using a dummy element, isolates the events so they will not be fired on any existing DOM element, nor the `window` or `document`. > > I am using `CustomEvent` and not `createEvent` because it's the newer > approach. [Read more here](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events). > > > I like to wrap each native method with these names: `on`, `off`, `trigger` ---------------------- ```js function eventDispatcher(){ // Create a dummy DOM element, which is a local variable var dummy = document.createTextNode('') // Create custom wrappers with nicer names return { off(...args){ dummy.removeEventListener(...args) return this }, on(...args){ dummy.addEventListener(...args) return this }, trigger(eventName, data){ if( !eventName ) return // if the event should be allowed to bubble, // then "dummy" must be in the DOM var e = new CustomEvent(eventName, {detail:data}) dummy.dispatchEvent(e) return this } } } //////////////////////////////////// // initialize the event dispatcher by creating an instance in an isolated way var myEventDispatcher = eventDispatcher(); //////////////////////////////////// // listen to a "foo" event myEventDispatcher .on('foo', e => console.log(e.type, e.detail) ) .on('bar', e => console.log(e.type, e.detail) ) //////////////////////////////////// // trigger a "foo" event with some data myEventDispatcher .trigger('foo', 123) .trigger('bar', 987); ``` --- The above `eventDispatcher` could be integrated into another code, for example, a Constructor: *(for example some component)* ```js function eventDispatcher(){ var dummy = document.createTextNode('') return { off(...args){ dummy.removeEventListener(...args) return this }, on(...args){ dummy.addEventListener(...args) return this }, trigger(eventName, data){ if( !eventName ) return var e = new CustomEvent(eventName, {detail:data}) dummy.dispatchEvent(e) return this } } } ///////////////////////////// // Some component: var MyComponent = function(){ // merge `EventDispatcher` instance into "this" instance Object.assign(this, eventDispatcher()) // set some default value this.value = 1 } MyComponent.prototype = { set value(v){ this.trigger('change', v) } } var comp = new MyComponent(); // bind a listener to "comp" (which itself is an instance of "MyComponent") comp.on('change', e => console.log("Type:", e.type,", Value:", e.detail) ) // set some value comp.value = 3; ``` --- **See my related [answer](https://stackoverflow.com/a/44432013/104380), which shows a more complex implementation of the above**
Ok I found a solution. I had to change the WebBrowser IE Version to Internet Explorer 11: <http://weblog.west-wind.com/posts/2011/May/21/Web-Browser-Control-Specifying-the-IE-Version> And then : ``` function OnPrinterStateChanged(state) { var evt = document.createEvent("Event"); evt.state = state; evt.initEvent("printerstatechanged", true, false); window.dispatchEvent(evt); } window.addEventListener('printerstatechanged', function (e) { // Do something }); ```
23,344,625
I would like to create a custom event in JavaScript. I have a WPF application with a WebBrowser inside, and a HTML page with JavaScript. I work with a printer. When the state of the printer changes, it triggers an event in .NET. Then, I call a JavaScript method `OnPrinterStateChanged(state)` with the `InvokeScript` function of the WebBrowser control. The problem is that I have to implement the method `OnPrinterStateChanged(state)` in my webpage. I can't change the name of the method or subscribe/unsubscribe to the event... I would like to move the JavaScript method `OnPrinterStateChanged(state)` in a separate JavaScript file. What I want : * Subscribe/Unsubscribe to the event in my HTML page and decide what I want to do when the event is triggered (ex. : "function ChangeState") * When the .NET event is triggered, it calls the `OnPrinterStateChanged(state)` of my separate .js file, then the JavaScript event is triggered and the function `ChangeState` is called. I found some solutions but I didn't manage to make it work... What is the simplest way to do it?
2014/04/28
[ "https://Stackoverflow.com/questions/23344625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558653/" ]
I like using this `EventDispatcher` constructor method, which, using a dummy element, isolates the events so they will not be fired on any existing DOM element, nor the `window` or `document`. > > I am using `CustomEvent` and not `createEvent` because it's the newer > approach. [Read more here](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events). > > > I like to wrap each native method with these names: `on`, `off`, `trigger` ---------------------- ```js function eventDispatcher(){ // Create a dummy DOM element, which is a local variable var dummy = document.createTextNode('') // Create custom wrappers with nicer names return { off(...args){ dummy.removeEventListener(...args) return this }, on(...args){ dummy.addEventListener(...args) return this }, trigger(eventName, data){ if( !eventName ) return // if the event should be allowed to bubble, // then "dummy" must be in the DOM var e = new CustomEvent(eventName, {detail:data}) dummy.dispatchEvent(e) return this } } } //////////////////////////////////// // initialize the event dispatcher by creating an instance in an isolated way var myEventDispatcher = eventDispatcher(); //////////////////////////////////// // listen to a "foo" event myEventDispatcher .on('foo', e => console.log(e.type, e.detail) ) .on('bar', e => console.log(e.type, e.detail) ) //////////////////////////////////// // trigger a "foo" event with some data myEventDispatcher .trigger('foo', 123) .trigger('bar', 987); ``` --- The above `eventDispatcher` could be integrated into another code, for example, a Constructor: *(for example some component)* ```js function eventDispatcher(){ var dummy = document.createTextNode('') return { off(...args){ dummy.removeEventListener(...args) return this }, on(...args){ dummy.addEventListener(...args) return this }, trigger(eventName, data){ if( !eventName ) return var e = new CustomEvent(eventName, {detail:data}) dummy.dispatchEvent(e) return this } } } ///////////////////////////// // Some component: var MyComponent = function(){ // merge `EventDispatcher` instance into "this" instance Object.assign(this, eventDispatcher()) // set some default value this.value = 1 } MyComponent.prototype = { set value(v){ this.trigger('change', v) } } var comp = new MyComponent(); // bind a listener to "comp" (which itself is an instance of "MyComponent") comp.on('change', e => console.log("Type:", e.type,", Value:", e.detail) ) // set some value comp.value = 3; ``` --- **See my related [answer](https://stackoverflow.com/a/44432013/104380), which shows a more complex implementation of the above**
Requirement: ES6 ```js let MyClass = (function () { let __sym = Symbol('MyClass'); class MyClass { constructor() { this[__sym] = {}; } on(event, callback) { this[__sym][event] = { callback: callback } } getError() { let event = this[__sym].error; if (event && event.callback) { event.callback('some parameter'); } } } return MyClass; }()); let myClass = new MyClass(); myClass.on('error', function (e) { console.log('error:', e); }); console.log('before getting error:'); myClass.getError(); ```
4,928,128
There's a form with three checkboxes and a button. Upon clicking on the button a messagebox is suppose to show up and display all the items that were checked on the form with price before tax and total. The price before tax and total are taken care of, but how would I display what was checked by the user on that form in the message box that will serve as a bill. ``` if (checkCheeseSnackBread.Checked == true) { price += 10; items += "Cheese Snack Bread - $10"; } else { price -= 10; } ``` Just need some guidance.
2011/02/07
[ "https://Stackoverflow.com/questions/4928128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/606895/" ]
First I must say that the code you've written seems to hold a logical eror. If the checkbox isn't checked then you shouldn't do anything. In your code you subtract the item-price from the total price. This way you give a discount of 10. If they don't buy it, don't add it. That's all. So, now you know what they've bought, you can use a StringBuilder to populate the message. Quick and dirty: ``` StringBuilder builder = new StringBuilder(); builder.AppendLine("Ticket") builder.AppendLine(); if (checkCheeseSnackBread.Checked) // == true is not needed { price += 10; items += "Cheese Snack Bread - $10"; builder.AppendLine(Cheese Snack Bread - $10); } // Do the same for other checkboxes // Add the totals Messagebox.Show(builder.ToString()); ``` There is an other way: loop through the controls on the form, if it's a checkbox ==> add the text to the StringBuilder. This way it doesn't matter how much checkboxes there are. You just have to make sure that the text-property is used to print on the ticket (messagebox).
If you just want to display a string you generate. Check this out: <http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox.aspx>
9,975,041
Hi Why am i getting an inalid cast exception? ``` public class RootContainer2 { [DataMember] public string StopName { get; set; } [DataMember] public string StopId { get; set; } [DataMember] public string Stop { get; set; } [DataMember] public ObservableCollection<Stops> Stops { get; set; } } private void ContentPanel_Loaded(object sender, RoutedEventArgs e) { textRouteId.Text = this.NavigationContext.QueryString["name"]; string myvar = textRouteId.Text; try { WebClient webClient = new WebClient(); Uri uri = new Uri("websiteurl"); webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted); webClient.OpenReadAsync(uri); } catch (Exception ex) { MessageBox.Show(ex.Message); } } void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { DataContractJsonSerializer ser = null; try { ser = new DataContractJsonSerializer(typeof(RootContainer2)); RootContainer2 rootContainer = ser.ReadObject(e.Result) as RootContainer2; foreach (Stops em in rootContainer.Stops) { string df = em.StopName; string dt = em.StopId; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } ``` Here is the json output which I am trying to read but I get an invalid cast exception. ``` {"RouteId": "1231", "RouteName":"1 Whitehawk - Mile Oak", "Stops": [ { "StopId":"6882", "StopName":"Swanborough Drive", "OperatorsCode4":"bridmpj", "Lat":"50.8326729229821", "Lng":"-0.103217996656901" } , { "StopId":"6883", "StopName":"Haybourne Road", "OperatorsCode4":"brimapm", "Lat":"50.8317788816436", "Lng":"-0.10486427645364671" } , { "StopId":"6884", "StopName":"Coolham Drive", "OperatorsCode4":"brijtwm", "Lat":"50.829695439856089", "Lng":"-0.10512229365031489" } , { "StopId":"6885", "StopName":"St Cuthmans Church", "OperatorsCode4":"briapdg", "Lat":"50.8283233642578", "Lng":"-0.104808002710342" } , ``` Plus the class in stops.cs : ``` public class Stops { public string StopId { get; set; } public string StopName { get; set; } } ``` EDIT: So after creating my own url and then testing the data, it's something to do with the URL that I was given I think. Just doing further testing. Edit 2 If i put the data into a text file and debug the data, it works if i do the following. the end of the feed is like this: "Lng":"-0.277833998203278", "" } ] } If i remove the , and "" then it works. but how do i stop it getting there in the first place?
2012/04/02
[ "https://Stackoverflow.com/questions/9975041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1178083/" ]
**Use this regex :** (UPDATED) ``` <?php $str = '<h1>Page Title</h1><a href="http://www.google.com/">Google</a>'; $text = preg_replace("/href=\"http\:\/\/([a-zA-Z0-9\-]+\.[a-zA-Z0-9]+\.[a-zA-Z]{2,3}(\/*)?)/","href=\"http://www.mysite.com/tracking.php?url=$1\"",$str); echo $text; ?> ``` **Outputs :** ``` <h1>Page Title</h1><a href="http://www.mysite.com/tracking.php?url=www.google.com/"">Google</a> ```
``` $str = '<h1>Page Title</h1><a href="http://www.google.com">Google</a>'; $text = preg_replace('href=\"http\://([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?)\"', 'href=\"YOUR_TRACKING_URL=$1\"', $str); echo $text; ``` Warning: preg\_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash in /home/.... (sorry for the duplication)
28,057,228
I'm trying to install WKHTMLtoPDf 0.12.x on a Dreamhost VPS running Ubuntu 12.04.5. I found a realatively new [resource](https://askubuntu.com/questions/556667/how-to-install-wkhtmltopdf-0-12-1-on-ubuntu-server) and it seems like it should be pretty straight forward: ``` sudo add-apt-repository ppa:pov/wkhtmltopdf sudo apt-get update sudo apt-get install wkhtmltopdf ``` But, it tells me the user I'm SSH'd in with using Putty is not in the Sudoers file, and the incident will be reported. Is this the right way to install wkhtmltopdf on the Dreamhost VPS? and if so how do you add a user to the sudoers file? I'm not overly savy with SSH commands or servers so any explanations would be best at a high-level. **UPDATE** Dreamhost was able to help me get on the sudoers list with no issues, but the commands listed above don't seem to work. I'm at root after typing: ``` sudo -s ``` But now ``` add-apt-repository ppa:pov/wkhtmltopdf ERROR - add-apt-repository: command not found ``` and ``` apt-get ppa:pov/wkhtmltopdf (also tried it with just wkhtmltopdf) ERROR - Invalid operation ppa:pov/wkhtmltopdf ``` I also tried ``` apt-get install wkhtmltopdf ``` Which installed wkhtmltopdf, but it installed version 0.9.9.3, which is super old. How do I update this? Or just get rid of it? **UPDATE 2** To remove the package and all its dependencies I used this [resource](https://gist.github.com/ermand/67a4ce7cf01f380c7e84): ``` apt-get remove --purge wkhtmltopdf ``` and then as suggested by the command prompt ran autoremove afterwards to remove the dependencies. ``` apt-get autoremove ``` **UPDATE 3** Okay, so through a coordinated effect this bit of [help](http://lifeonubuntu.com/ubuntu-missing-add-apt-repository-command/) was found, so using: ``` apt-get install software-properties-common python-software-properties ``` I can now use ``` add-apt-repository ppa:pov/wkhtmltopdf ``` And that allows the use of all the commands above (minus sudo if you typed "sudo -s") **BUT** now I'm sitting in front of a freaky pink screen that is asking me to install Grub? and I have no idea what I should do? Should I say yes or no? Why? **UPDATE 4** I SSH'd in using another shell to check if you have grub installed or not and by typing: ``` grub-install -v ``` I have 1.99-21ubuntu3.17, so I thought I'd hit no, but then it just keeps asking me to if I want to install Grub, which apparently is issue with this version of Ubuntu. So I was forced to hit yes and everything seems to be working. In case this was a bad decision to hit yes let me know.
2015/01/20
[ "https://Stackoverflow.com/questions/28057228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1148107/" ]
The steps taken to install WKHTMLtoPDF 0.12.x onto Ubuntu 12.04.5 derived from the above question, using these resources ([1](https://askubuntu.com/questions/556667/how-to-install-wkhtmltopdf-0-12-1-on-ubuntu-server) and [2](http://lifeonubuntu.com/ubuntu-missing-add-apt-repository-command/)) where: ``` sudo -s add-apt-repository ppa:pov/wkhtmltopdf ``` If add-apt-repository is not a recognized command: ``` apt-get install software-properties-common python-software-properties ``` Continue if add-apt-repository was a recognized command, or after running the abov command to and rerunning the first command: ``` apt-get update apt-get install wkhtmltopdf ``` With regards to Grub, I don't know what you should choose. For me it was made by the fact I couldn't say no, and had to choose yes based on some issue related to Ubuntu. Once installed run: ``` wkhtmltopdf --version (should say wkhtmltopdf 0.12.1) ``` and then do a quick test of the install: ``` wkhtmltopdf http://www.google.com google.pdf ``` If this results in a command not found error you'll have to install xvfb: ``` apt-get install xvfb ``` And run the command below (found [here](https://stackoverflow.com/a/13604819/1148107)) to generate your PDFs: ``` xvfb-run --server-args="-screen 0, 1024x768x24" wkhtmltopdf http://www.google.com google.pdf ```
While doing setup on AWS Ubuntu 14.04 Trusty AMD64 Machine i got lot of issues as wkhtmltopdf is not running at all, Giving Cannot connect to X server issue. Finally the solution which worked for me is ``` $ sudo apt-get install xfonts-75dpi $ wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.2/wkhtmltox-0.12.2_linux-trusty-amd64.deb $ sudo dpkg -i wkhtmltox-0.12.2_linux-trusty-amd64.deb $ wkhtmltopdf http://www.google.com test.pdf ```
2,135,532
Find the function $f$, given that $$f'(x) = f(x)(1-f(x))$$ and that $f(0) = \frac12$ The answer is $$y = \frac{1}{1+e^{-x}}$$ What I tried doing is changing $f'(x)$ as \frac{dy}{dx} and all the $f(x)$ as $y$ to make it easier to read for myself. Manipulating the equation. I got $$\left(y + \frac1y\right)dy = 1dx$$ but when I integrate I'm not getting the correct answer, I'm pretty sure I'm doing this incorrectly. Any advice?
2017/02/08
[ "https://math.stackexchange.com/questions/2135532", "https://math.stackexchange.com", "https://math.stackexchange.com/users/371974/" ]
$$\frac{dy}{dx}=y(1-y)$$ $$\int\frac{dy}{y(1-y)}=\int dx$$ $$\int\frac{dy}{y}+\int\frac{dy}{1-y}=\int dx$$ $$\ln y-\ln(1-y)=x+c$$ $$\ln\left(\frac{y}{1-y}\right)=x+c$$ $$f(0)=\frac12$$ Thus, $c=0$. $$\frac{y}{1-y}=e^{x}$$ $$y=e^{x+c}-ye^{x}$$ $$y(1+e^{x+c})=e^{x}$$ $$y(1+e^{-x})=1$$ $$y=\frac{1}{1+e^{-x}}$$
If you expand the right hand side you'll obtain the differential equation: $y'-y= -y^2$ In that equation we let $u=y^{-1}$ so $u'=-y^{-2}y'$ Now we multiply the original equation with $-y^-{2}$. We now have the equation: $-y^{-2}y'+y^-{1}=1$ which by our substitution transforms into: $u'+u=1$ I guess you can take it from here!
35,743,615
I want to open login\_activity on first time entering app, and then on the second entering to app open main\_activity. I create something but it wont work. so I wonder what I'm doing wrong? this is my LoginActivity ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); userName = (EditText) findViewById(R.id.username); userPhone = (EditText) findViewById(R.id.userPhone); loginBtn = (Button) findViewById(R.id.buttonLogin); dbHandler = new LogsDBHandler(this); loginBtn.setOnClickListener(this); setTitle("AMS - biomasa | prijava"); SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); if (pref.getBoolean("activity_executed", false)) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } else { SharedPreferences.Editor edt = pref.edit(); edt.putBoolean("activity_executed", true); edt.commit(); } } public void insert() { User user = new User ( userName.getText().toString(), userPhone.getText().toString()); dbHandler.addUser(user); Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show(); } @Override public void onClick(View v) { if (v == loginBtn && validateUser()) { insert(); } } ``` In main activity i have only image and two buttons. And in manifest I add launcher to main and login activity. ``` <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ``` What am I doing wrong here?
2016/03/02
[ "https://Stackoverflow.com/questions/35743615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5512319/" ]
1. Create one start-up activity call it as SplashActivity ``` public class SplashActivity extends Activity{ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); // decide here whether to navigate to Login or Main Activity SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); if (pref.getBoolean("activity_executed", false)) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } else { Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); finish(); } } } ``` 2. In your LoginActivity simply set `activity_executed` to `true` ``` public void insert() { User user = new User ( userName.getText().toString(), userPhone.getText().toString()); dbHandler.addUser(user); Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show(); //set activity_executed inside insert() method. SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); SharedPreferences.Editor edt = pref.edit(); edt.putBoolean("activity_executed", true); edt.commit(); } ``` change manifest as below- ``` <activity android:name=".MainActivity"/> <activity android:name=".LoginActivity" /> <activity android:name=".SplashActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ```
You should add another empty activity (with no UI) that loads before anything. Then use `SharedPreferences` to store some value. Thus if the user has already opened your app once, the value is stored. And then use a condition to check this value. If its the value you saved skip `login_activity` and direct to `main_activity` else direct to `login_activity`.
35,743,615
I want to open login\_activity on first time entering app, and then on the second entering to app open main\_activity. I create something but it wont work. so I wonder what I'm doing wrong? this is my LoginActivity ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); userName = (EditText) findViewById(R.id.username); userPhone = (EditText) findViewById(R.id.userPhone); loginBtn = (Button) findViewById(R.id.buttonLogin); dbHandler = new LogsDBHandler(this); loginBtn.setOnClickListener(this); setTitle("AMS - biomasa | prijava"); SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); if (pref.getBoolean("activity_executed", false)) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } else { SharedPreferences.Editor edt = pref.edit(); edt.putBoolean("activity_executed", true); edt.commit(); } } public void insert() { User user = new User ( userName.getText().toString(), userPhone.getText().toString()); dbHandler.addUser(user); Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show(); } @Override public void onClick(View v) { if (v == loginBtn && validateUser()) { insert(); } } ``` In main activity i have only image and two buttons. And in manifest I add launcher to main and login activity. ``` <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ``` What am I doing wrong here?
2016/03/02
[ "https://Stackoverflow.com/questions/35743615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5512319/" ]
you can change launcher activity as **main activity**.so that when you open the application it is starting from **main activity** there you can check whether he is logged in or not.if he is not logged in you must navigate him to **login activity** or else you just do it as it is.Following is manifest file.. `<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginActivity"></activity>`
You should add another empty activity (with no UI) that loads before anything. Then use `SharedPreferences` to store some value. Thus if the user has already opened your app once, the value is stored. And then use a condition to check this value. If its the value you saved skip `login_activity` and direct to `main_activity` else direct to `login_activity`.
35,743,615
I want to open login\_activity on first time entering app, and then on the second entering to app open main\_activity. I create something but it wont work. so I wonder what I'm doing wrong? this is my LoginActivity ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); userName = (EditText) findViewById(R.id.username); userPhone = (EditText) findViewById(R.id.userPhone); loginBtn = (Button) findViewById(R.id.buttonLogin); dbHandler = new LogsDBHandler(this); loginBtn.setOnClickListener(this); setTitle("AMS - biomasa | prijava"); SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); if (pref.getBoolean("activity_executed", false)) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } else { SharedPreferences.Editor edt = pref.edit(); edt.putBoolean("activity_executed", true); edt.commit(); } } public void insert() { User user = new User ( userName.getText().toString(), userPhone.getText().toString()); dbHandler.addUser(user); Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show(); } @Override public void onClick(View v) { if (v == loginBtn && validateUser()) { insert(); } } ``` In main activity i have only image and two buttons. And in manifest I add launcher to main and login activity. ``` <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ``` What am I doing wrong here?
2016/03/02
[ "https://Stackoverflow.com/questions/35743615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5512319/" ]
1. Create one start-up activity call it as SplashActivity ``` public class SplashActivity extends Activity{ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); // decide here whether to navigate to Login or Main Activity SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); if (pref.getBoolean("activity_executed", false)) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } else { Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); finish(); } } } ``` 2. In your LoginActivity simply set `activity_executed` to `true` ``` public void insert() { User user = new User ( userName.getText().toString(), userPhone.getText().toString()); dbHandler.addUser(user); Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show(); //set activity_executed inside insert() method. SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); SharedPreferences.Editor edt = pref.edit(); edt.putBoolean("activity_executed", true); edt.commit(); } ``` change manifest as below- ``` <activity android:name=".MainActivity"/> <activity android:name=".LoginActivity" /> <activity android:name=".SplashActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ```
Problem about the line ``` if (pref.getBoolean("activity_executed", false)) { ``` You can Implement this method to call inside if(appIsLoggedIn) ``` public boolean appIsLoggedIn(){ return pref.getBoolean("activity_executed", false); } ```
35,743,615
I want to open login\_activity on first time entering app, and then on the second entering to app open main\_activity. I create something but it wont work. so I wonder what I'm doing wrong? this is my LoginActivity ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); userName = (EditText) findViewById(R.id.username); userPhone = (EditText) findViewById(R.id.userPhone); loginBtn = (Button) findViewById(R.id.buttonLogin); dbHandler = new LogsDBHandler(this); loginBtn.setOnClickListener(this); setTitle("AMS - biomasa | prijava"); SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); if (pref.getBoolean("activity_executed", false)) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } else { SharedPreferences.Editor edt = pref.edit(); edt.putBoolean("activity_executed", true); edt.commit(); } } public void insert() { User user = new User ( userName.getText().toString(), userPhone.getText().toString()); dbHandler.addUser(user); Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show(); } @Override public void onClick(View v) { if (v == loginBtn && validateUser()) { insert(); } } ``` In main activity i have only image and two buttons. And in manifest I add launcher to main and login activity. ``` <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ``` What am I doing wrong here?
2016/03/02
[ "https://Stackoverflow.com/questions/35743615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5512319/" ]
1. Create one start-up activity call it as SplashActivity ``` public class SplashActivity extends Activity{ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); // decide here whether to navigate to Login or Main Activity SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); if (pref.getBoolean("activity_executed", false)) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } else { Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); finish(); } } } ``` 2. In your LoginActivity simply set `activity_executed` to `true` ``` public void insert() { User user = new User ( userName.getText().toString(), userPhone.getText().toString()); dbHandler.addUser(user); Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show(); //set activity_executed inside insert() method. SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); SharedPreferences.Editor edt = pref.edit(); edt.putBoolean("activity_executed", true); edt.commit(); } ``` change manifest as below- ``` <activity android:name=".MainActivity"/> <activity android:name=".LoginActivity" /> <activity android:name=".SplashActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ```
you can change launcher activity as **main activity**.so that when you open the application it is starting from **main activity** there you can check whether he is logged in or not.if he is not logged in you must navigate him to **login activity** or else you just do it as it is.Following is manifest file.. `<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginActivity"></activity>`
35,743,615
I want to open login\_activity on first time entering app, and then on the second entering to app open main\_activity. I create something but it wont work. so I wonder what I'm doing wrong? this is my LoginActivity ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); userName = (EditText) findViewById(R.id.username); userPhone = (EditText) findViewById(R.id.userPhone); loginBtn = (Button) findViewById(R.id.buttonLogin); dbHandler = new LogsDBHandler(this); loginBtn.setOnClickListener(this); setTitle("AMS - biomasa | prijava"); SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE); if (pref.getBoolean("activity_executed", false)) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } else { SharedPreferences.Editor edt = pref.edit(); edt.putBoolean("activity_executed", true); edt.commit(); } } public void insert() { User user = new User ( userName.getText().toString(), userPhone.getText().toString()); dbHandler.addUser(user); Toast.makeText(getBaseContext(), "Prijavljeni ste!", Toast.LENGTH_SHORT).show(); } @Override public void onClick(View v) { if (v == loginBtn && validateUser()) { insert(); } } ``` In main activity i have only image and two buttons. And in manifest I add launcher to main and login activity. ``` <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ``` What am I doing wrong here?
2016/03/02
[ "https://Stackoverflow.com/questions/35743615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5512319/" ]
you can change launcher activity as **main activity**.so that when you open the application it is starting from **main activity** there you can check whether he is logged in or not.if he is not logged in you must navigate him to **login activity** or else you just do it as it is.Following is manifest file.. `<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginActivity"></activity>`
Problem about the line ``` if (pref.getBoolean("activity_executed", false)) { ``` You can Implement this method to call inside if(appIsLoggedIn) ``` public boolean appIsLoggedIn(){ return pref.getBoolean("activity_executed", false); } ```
664,932
Suppose that $\left(a\_n\right)$ is a sequence of real numbers and that $\left(\varepsilon\_n\right)$ is a sequence of IID RVs with $$P\left(\varepsilon\_n = \pm 1\right) = \frac{1}{2}$$ According to Williams (Probability with Martingales (1991), Section 12.3 "Random signs", pp. 113-114), the results below show that i. $\sum \varepsilon\_n a\_n$ converges (a.s.) if and only if $\sum a\_n^2 < \infty$, and that ii. $\sum \varepsilon\_n a\_n$ (a.s.) oscillates infinitely if $\sum a\_n^2 = \infty$ I understand why (i) follows from the results below, but I don't see how to prove (ii). --- **Theorem 12.2 (Sums of zero-mean independent variables in $\mathcal{L}^2$, pp. 112-113)**. Suppose that $\left(X\_k : k \in \mathbb{N}\right)$ is a sequence of independent random variables such that, for every $k$, $$E\left(X\_k\right) = 0,\ \sigma\_k^2 := \mathrm{Var}\left(X\_k\right) < \infty$$ a. Then $$\left(\sum \sigma\_k^2 < \infty\right)\ \textrm{implies that }\left(\sum X\_k\ \textrm{converges a.s.}\right)$$ b. If the variables $\left(X\_k\right)$ are bounded by some constant $K$ in $\left[0,\infty\right)$ in that $\left|X\_k\left(\omega\right)\right| \leq K$, $\forall k, \forall \omega$, then $$\left(\sum X\_k\ \textrm{converges, a.s.}\right)\ \textrm{implies that }\left(\sum \sigma\_k^2 < \infty\right)$$ **Notes to the theorem** 1. The Kolmogorov $0$-$1$ law implies that $$P\left(\sum X\_k\ \mathrm{converges}\right) = 0\ \mathrm{or}\ 1$$ 2. The proof of part b given in the book shows in fact that if $\left(X\_k\right)$ is a sequence of independent zero-mean RVs uniformly bounded by some constant $K$, then $$\left(P\left\{\textrm{partial sums of }\sum X\_k\ \textrm{are bounded}\right\} > 0\right) \implies \left(\sum X\_k\ \textrm{converges a.s.}\right)$$
2014/02/05
[ "https://math.stackexchange.com/questions/664932", "https://math.stackexchange.com", "https://math.stackexchange.com/users/37058/" ]
The events $$A := \left\{\sum \varepsilon\_k a\_k\ \textrm{diverges to }+\infty\right\}$$ and $$B := \left\{\sum \varepsilon\_k a\_k\ \textrm{diverges to }-\infty\right\}$$ are both tail events, hence by Kolmogorov's $0$-$1$ law $P\left(A\right),P\left(B\right)\in\left\{0,1\right\}$. However by symmetry $P\left(A\right)=P\left(B\right)$ and since $A \cap B = \emptyset$, we must have $P\left(A\right) = P\left(B\right) = 0$.
Since $ P(ε\_n=±1)=\frac{1}{2}, var(ε\_n ) = 1$ $\Sigma var(ε\_k a\_k)= \Sigma a^2\_k \times var( ε\_k )= \Sigma a^2\_k $
28,897,001
Giving m and n as integers, I can multiply them by successive sums like this: ``` m * n = m + m + m + ... + m (n times) ``` So, let's consider the pseudo code below: ``` m = ... (first number) n = ... (second number) Result = 0; while (n > 0) { Result = Result + m; n = n - 1; } ``` How can I implement this algorithm in F# knowing that variables are immutable? Put the question in another way, how can I update the variables *Result* and *n* along the successive iterations? Can someone write this algorithm in F#? Thank you Foot note: I'm start to study F# and I'm complete puzzled with functional programming.
2015/03/06
[ "https://Stackoverflow.com/questions/28897001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4640324/" ]
First of all, you can use mutable variables in F#, so your algorithm could be written like this: ``` let multiply1 m n = let mutable result = 0 for i = 1 to n do result <- result + m result ``` But if you want to do it a little more the functional way, you would use recursion. In this case, an inner function that accumulates the result: ``` let multiply2 m n = let rec loop x acc = if x = 0 then acc else loop (x - 1) (acc + m) loop n 0 ``` The `multiply2` function uses an inner recursive function called `loop` that accumulates the result of the multiplication in the `acc` argument. So loop calls itself `n` times and adds `m` each time to the accumulator. Once `x` reaches zero, this result is returned. Technically, you could also write the code without the accumulator argument: ``` let multiply3 m n = let rec loop x = if x = 0 then 0 else m + loop (x - 1) loop n ``` Maybe this code is easier to understand for a beginner, but it should be avoided, since it does not use [tail recursion](http://en.wikipedia.org/wiki/Tail_call) and this leads to problems. For example, this will result in a StackOverflowException: ``` multiply3 5 1000000 // This will cause a StackOverflowException. |> printfn "Result: %d" ```
You can use Seq (lazy list like in haskell / IEnumerable like in C#) and the pipe operator: ``` let mult n (m:int) = Seq.initInfinite (fun _ -> m) |> Seq.take n |> Seq.sum ```
14,557,720
I am implement Paypal standard payment in my site. I have a resource to receive notification when user issue a subscription and update data base in-order to tracking the sale and user payment. I do accidentally change the notification resource on my site which mean making it stop working. Is there any setting with paypal to alert me by email once user successful check out and notification url stop working?
2013/01/28
[ "https://Stackoverflow.com/questions/14557720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692176/" ]
Okay, got it compiled and ran a couple of experiments myself. Thus far it appears to not support this GCC extension: <http://gcc.gnu.org/onlinedocs/cpp/Directives-Within-Macro-Arguments.html#Directives-Within-Macro-Arguments> and also barfs on the Microsoft header file C:\Program Files (x86)\Microsoft Visual Studio 11.0\vc\include\xkeycheck.h containing the following construct: ``` #if defined(auto) /* check C keywords */ \ || defined(break) \ ... ```
The easiest way to find out if it supports your favorite extension is to just, you know, **try it**. Is probably even *way* faster to ask here and wait for enough comments/answers to accumulate to be able to conclude something. Or check the documentation, if it doesn't talk about GCC/MSC extensions at all, it probably just doesn't know of them.
41,104,615
In the latest version on Django REST Swagger (2.1.0) YAML docstrings have been deprecated. I cannot get swagger to show the POST request parameters. Here is my view ``` class UserAuthenticationView(APIView): def post(self, request, *args, **kwargs): serializer = UserAuthenticationSerializer(data=self.request.data) if serializer.is_valid(): user = serializer.validated_data['user'] return Response({'token': user.auth_token.key}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) ``` Here is my Serializer ``` class UserAuthenticationSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(username=username, password=password) if user: if not user.is_active: msg = 'User account is disabled.' raise serializers.ValidationError(msg, code='authorization') else: msg = 'Unable to log in with provided credentials.' raise serializers.ValidationError(msg, code='authorization') else: msg = 'Must include "username" and "password".' raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs ``` This is what I get in my generated [![enter image description here](https://i.stack.imgur.com/dJupV.png)](https://i.stack.imgur.com/dJupV.png) I do not get a form with the fields for the POST data. How do I get that?
2016/12/12
[ "https://Stackoverflow.com/questions/41104615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4364572/" ]
**django-rest-swagger** uses **rest\_framework.schemas.SchemaGenerator** to generate the schema and **SchemaGenerator** uses **get\_serializer\_fields** to get the serializer information of a view. get\_serializer\_fields checks if a view has a **get\_serializer** method to generate the form. **GenericAPIView** provides the **get\_serializer** so inheriting from it is enough. Inherit view from `GenericAPIView` rather than simple `APIView`. And add `serializer_class` attribute with appropriate serializer ``` from rest_framework.generics import GenericAPIView class UserAuthenticationView(GenericAPIView): serializer_class = UserAuthenticationSerializer def post(self, request, *args, **kwargs): serializer = UserAuthenticationSerializer(data=self.request.data) if serializer.is_valid(): user = serializer.validated_data['user'] return Response({'token': user.auth_token.key}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) ```
This is the rest framework get schema code (the part of it): ``` def get_serializer_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class. """ if method not in ('PUT', 'PATCH', 'POST'): return [] if not hasattr(view, 'get_serializer'): return [] serializer = view.get_serializer() if isinstance(serializer, serializers.ListSerializer): return [ coreapi.Field( name='data', location='body', required=True, type='array' ) ] ... ``` As you can see - it should work if you define the `get_serializer` method on your view - which returns the `UserAuthenticationSerializer`. -- EDIT -- Forget: Happy Coding.
41,104,615
In the latest version on Django REST Swagger (2.1.0) YAML docstrings have been deprecated. I cannot get swagger to show the POST request parameters. Here is my view ``` class UserAuthenticationView(APIView): def post(self, request, *args, **kwargs): serializer = UserAuthenticationSerializer(data=self.request.data) if serializer.is_valid(): user = serializer.validated_data['user'] return Response({'token': user.auth_token.key}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) ``` Here is my Serializer ``` class UserAuthenticationSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(username=username, password=password) if user: if not user.is_active: msg = 'User account is disabled.' raise serializers.ValidationError(msg, code='authorization') else: msg = 'Unable to log in with provided credentials.' raise serializers.ValidationError(msg, code='authorization') else: msg = 'Must include "username" and "password".' raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs ``` This is what I get in my generated [![enter image description here](https://i.stack.imgur.com/dJupV.png)](https://i.stack.imgur.com/dJupV.png) I do not get a form with the fields for the POST data. How do I get that?
2016/12/12
[ "https://Stackoverflow.com/questions/41104615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4364572/" ]
This is the rest framework get schema code (the part of it): ``` def get_serializer_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class. """ if method not in ('PUT', 'PATCH', 'POST'): return [] if not hasattr(view, 'get_serializer'): return [] serializer = view.get_serializer() if isinstance(serializer, serializers.ListSerializer): return [ coreapi.Field( name='data', location='body', required=True, type='array' ) ] ... ``` As you can see - it should work if you define the `get_serializer` method on your view - which returns the `UserAuthenticationSerializer`. -- EDIT -- Forget: Happy Coding.
A working example for a custom ViewSet, with django-rest-swagger==2.2.0: ``` from rest_framework import viewsets from rest_framework.schemas import AutoSchema from rest_framework.compat import coreapi, coreschema from rest_framework.decorators import action class DeviceViewSchema(AutoSchema): """ Schema customizations for DeviceViewSet """ def get_manual_fields(self, path, method): extra_fields = [] if path.endswith('/send_command/'): extra_fields = [ coreapi.Field( "command", required=True, location="form", schema=coreschema.String() ), coreapi.Field( "params", required=False, location="form", schema=coreschema.String() ), ] manual_fields = super().get_manual_fields(path, method) return manual_fields + extra_fields class DeviceViewSet(viewsets.ViewSet): lookup_field = 'channel' lookup_value_regex = '[\w-]+' schema = DeviceViewSchema() @action(methods=['post'], detail=True, url_name='send_command') def send_command(self, request, channel): """ Send command to device Parameters: - command: string - params: string (JSON encoded list or dict) """ ... ``` The final result is: [![enter image description here](https://i.stack.imgur.com/7H10A.png)](https://i.stack.imgur.com/7H10A.png)
41,104,615
In the latest version on Django REST Swagger (2.1.0) YAML docstrings have been deprecated. I cannot get swagger to show the POST request parameters. Here is my view ``` class UserAuthenticationView(APIView): def post(self, request, *args, **kwargs): serializer = UserAuthenticationSerializer(data=self.request.data) if serializer.is_valid(): user = serializer.validated_data['user'] return Response({'token': user.auth_token.key}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) ``` Here is my Serializer ``` class UserAuthenticationSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(username=username, password=password) if user: if not user.is_active: msg = 'User account is disabled.' raise serializers.ValidationError(msg, code='authorization') else: msg = 'Unable to log in with provided credentials.' raise serializers.ValidationError(msg, code='authorization') else: msg = 'Must include "username" and "password".' raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs ``` This is what I get in my generated [![enter image description here](https://i.stack.imgur.com/dJupV.png)](https://i.stack.imgur.com/dJupV.png) I do not get a form with the fields for the POST data. How do I get that?
2016/12/12
[ "https://Stackoverflow.com/questions/41104615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4364572/" ]
**django-rest-swagger** uses **rest\_framework.schemas.SchemaGenerator** to generate the schema and **SchemaGenerator** uses **get\_serializer\_fields** to get the serializer information of a view. get\_serializer\_fields checks if a view has a **get\_serializer** method to generate the form. **GenericAPIView** provides the **get\_serializer** so inheriting from it is enough. Inherit view from `GenericAPIView` rather than simple `APIView`. And add `serializer_class` attribute with appropriate serializer ``` from rest_framework.generics import GenericAPIView class UserAuthenticationView(GenericAPIView): serializer_class = UserAuthenticationSerializer def post(self, request, *args, **kwargs): serializer = UserAuthenticationSerializer(data=self.request.data) if serializer.is_valid(): user = serializer.validated_data['user'] return Response({'token': user.auth_token.key}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) ```
A working example for a custom ViewSet, with django-rest-swagger==2.2.0: ``` from rest_framework import viewsets from rest_framework.schemas import AutoSchema from rest_framework.compat import coreapi, coreschema from rest_framework.decorators import action class DeviceViewSchema(AutoSchema): """ Schema customizations for DeviceViewSet """ def get_manual_fields(self, path, method): extra_fields = [] if path.endswith('/send_command/'): extra_fields = [ coreapi.Field( "command", required=True, location="form", schema=coreschema.String() ), coreapi.Field( "params", required=False, location="form", schema=coreschema.String() ), ] manual_fields = super().get_manual_fields(path, method) return manual_fields + extra_fields class DeviceViewSet(viewsets.ViewSet): lookup_field = 'channel' lookup_value_regex = '[\w-]+' schema = DeviceViewSchema() @action(methods=['post'], detail=True, url_name='send_command') def send_command(self, request, channel): """ Send command to device Parameters: - command: string - params: string (JSON encoded list or dict) """ ... ``` The final result is: [![enter image description here](https://i.stack.imgur.com/7H10A.png)](https://i.stack.imgur.com/7H10A.png)
18,986,931
I am new to CodeIgniter and am having trouble figuring out routing. I am getting a 404 page not found error when I go to "/SimplePie1". Is my routing the issue, or have I messed up the controller or view? Thanks. My controller: ``` class Feeder extends CI_Controller { public function index() { $this->load->library('rss'); $feed = $this->rss; $feed->set_feed_url('http://www.theverge.com/rss/frontpage'); $success = $feed->init(); $feed->handle_content_type(); $this->load->view('feed_view', array('feed' => $feed)); } } ``` My view: ``` <?php include_once('header.php'); ?> <?php include_once('navbar.php'); ?> <?php foreach($feed as $item) : ?> <br /> <a href="<?php echo $item['permalink']; ?>"><?php echo $item['title']; ?></a> <?php endforeach; ?> <?php include_once('footer.php'); ?> ``` My routes: ``` $route['default_controller'] = "homeController"; $route['feed_views'] = "SimplePie1"; $route['404_override'] = ''; ```
2013/09/24
[ "https://Stackoverflow.com/questions/18986931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/866360/" ]
The following code means ``` $route['feed_views'] = "SimplePie1"; ``` If you have `feed_views` in the `url` then launch the `SimplePie1` controller and by default the `index` method will be invoked, so now the question is : do you have a controller class named `SimplePie1` ? If not then, it should show a`404` not found error. I think it should be ``` $route['feed_views'] = "Feeder"; ``` so, it'll be mapped to the `Feeder/index` (class/method). Read more on [documentation](http://ellislab.com/codeigniter/user-guide/general/routing.html).
What exactly are you trying to do? Assuming you default controller is feeder , so "/feeder" will load the index function which loads the feed\_view without no routes just default controller. In routes you rewrite controllers and it's methods,Not the views names like you mention in your route.php. Review [URI Roouting](http://ellislab.com/codeigniter/user-guide/general/routing.html)
22,798,333
I've seen questions regarding the same issue, but all of them are about strings. How about integers? Why am I getting the "unary operator expected" error? ``` if [ $(date +%k%M) -ge ${!BLOCK1FRAN} ] ; then whatever ; fi ```
2014/04/01
[ "https://Stackoverflow.com/questions/22798333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2589223/" ]
You are using indirection. If the variable `${BLOCK1FRAN}` points to an empty variable, you'll get the error message. Make sure that the variable pointed by `${BLOCK1FRAN}` contains a valid numeric value. If you want an empty string and nonnumeric values to be evaluated as zero (`0`), use the following syntax. ``` if [[ $(date +%k%M) -ge ${!BLOCK1FRAN} ]]; then whatever ; fi ```
It looks good to me. Are you sure you've set BLOCK1FRAN correctly? ``` whatever() { echo "it works"; } foo=42 BLOCK1FRAN=foo if [ $(date +%k%M) -ge ${!BLOCK1FRAN} ] ; then whatever ; fi it works ```
333,269
regarding the ESA Sentinel-3 file name convention I have got a question; which **time zone (GMT, CEST, ...)** does ESA use? I could not find anything yet, even it should be a critical point for many users... There is no information given on the official website of ESA for the Sentinel-3 SLSTR-product as you can see here URL:<https://sentinel.esa.int/web/sentinel/user-guides/sentinel-3-slstr/naming-convention>
2019/08/28
[ "https://gis.stackexchange.com/questions/333269", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/148002/" ]
This is the UTC time format according to the official [source1](https://sentinel.esa.int/web/sentinel/user-guides/sentinel-3-altimetry/definitions/conventions), [source2](https://sentinels.copernicus.eu/web/sentinel/technical-guides/sentinel-3-slstr/level-1/calibration-mode-desc): > > The time reference system in the SRAL/MWR Level-2 products is the Universal Time Coordinated (UTC). > > > [![enter image description here](https://i.stack.imgur.com/GoODM.png)](https://i.stack.imgur.com/GoODM.png)
It is right there in the link you provided: > > The file naming convention of SLSTR products (see this document for more details) is identified by the sequence of fields described below: > > > MMM\_SL\_L\_TTTTTT\_yyyymmddThhmmss\_YYYYMMDDTHHMMSS\_YYYYMMDDTHHMMSS\_[instance ID]*GGG*[class ID].SEN3 > > > [...] > > > yyyymmddThhmmss is the sensing start time > > > YYYYMMDDTHHMMSS is the sensing stop time > > > YYYYMMDDTHHMMSS is the product creation date > > > [...] > > >
14,138,098
in LLCP there are 2 transport possibilities: * connection-oriented * connectionless Does someone know which kind of this LLCP transports is used in combination with: * NPP * SNEP NPP is just 1-way, so maybe it is combines with connections-oriented because of the acknowledgements, but i don't know. SNEP has this acknowledgements for confirming received packages, so maybe it is combines with connectionless LLCP to avoid redundancy, but I'm not sure. I hope you can help me, thanks!
2013/01/03
[ "https://Stackoverflow.com/questions/14138098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269434/" ]
You don't say what OS you are deployed on, but on RHEL 6.7 adding the host name to /etc/hosts fixed this for us.
Its becoz of DB initialization problem ar localhost: You should use your DB server and web server on same url... your jdbc.url should be same as which you have configured in sonar server properties if it is not in your localhost.
22,814,102
I have a model with a scope and a method like so: ``` class Model < ActiveRecord::Base scope :editable, where('updated_at > ? OR (updated_at IS NULL AND created_at > ?)', (Date.today - 3.days).beginning_of_day, (Date.today - 3.days).beginning_of_day) def editable? return (self.updated_at || self.created_at) > (Date.today - 3.days).beginning_of_day end end ``` I have the feeling I should not be writing two times the same logic in both the scope and the method. Is there a way I can avoid that? I'm on Rails 3.2 Thanks
2014/04/02
[ "https://Stackoverflow.com/questions/22814102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1620081/" ]
Unfortunately there is no easy way to do this at the moment. The closest you can get is ``` def editable? self.class.editable.exists? self end ``` However it will call database to check whether given record exists or not, so it is useless for new records or for records you want to update. The reason why there is no such a functionality is that this would require translation from SQL/Arel to ruby code, which might not be simple at all (as other model may be involved with JOIN statement). However If you have squeel gem installed, you should be able to write: ``` class Model < ActiveRecord::Base editable = -> { (updated_at > (Date.today - 3.days).beginning_of_day) | ((updated_at == nil) & created_at > (Date.today - 3.days).beginning_of_day) } scope :editable, where &editable def editable? instance_eval &editable end end ``` which is pretty much what you need. (not tested!) UPDATE: Note that squeel gem is not currently maintained, which might be dangerous.
As far as I can see there is no code duplication there. The scope will be called on the class, `Model.editable`, retrieving all the records that match that scope. `editable?` will be called on an instance of `Model`, eg: `@model.editable?` returning true or false. The first is a query, the second a logic expression. One way to reuse your scope in the `editable?` method would be the following: ``` class Model < ActiveRecord::Base scope :editable, where('updated_at > ? OR (updated_at IS NULL AND created_at > ?)', (Date.today - 3.days).beginning_of_day, (Date.today - 3.days).beginning_of_day) def editable? Model.editable.include?(self) end end ``` However, this is not recommended as it will cause unnecessary query to the database.
20,186,146
The following HTML/CSS code is rendering in IE (Version 8) but not in Firefox (Version 25) Any reason why? HTML: ``` <img class="buttonmini" id="btn_Actual_Effort" onclick="showEffortDetail()" disabled="disabled"> ``` CSS: ``` .buttonmini { background: url(../newimages/effort_calendar.gif) no-repeat; height: 16px; width: 16px; font-family: Verdana; /*font-size: 8pt;*/ cursor: pointer; } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20186146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259889/" ]
``` select e.employee_id, e.employee_name , (select count(*) from dependent_table where employee_id=e.employee_id) as dependents from employee_table as e ```
Use Group By and Count ``` select em.Employee_id, count(*) from employee em inner join dependant dp on em.employee_id = dp.employee_id group by em.employee_id ```
20,186,146
The following HTML/CSS code is rendering in IE (Version 8) but not in Firefox (Version 25) Any reason why? HTML: ``` <img class="buttonmini" id="btn_Actual_Effort" onclick="showEffortDetail()" disabled="disabled"> ``` CSS: ``` .buttonmini { background: url(../newimages/effort_calendar.gif) no-repeat; height: 16px; width: 16px; font-family: Verdana; /*font-size: 8pt;*/ cursor: pointer; } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20186146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259889/" ]
Try this query: ``` select e.employee_id,e.employee_name,count(d.employee_id) as dependents from department d inner join employee e on (e.employee_id=d.employee_id) group by d.employee_id; ``` [Sql Fiddle Example](http://sqlfiddle.com/#!2/75a30/4)
Use Group By and Count ``` select em.Employee_id, count(*) from employee em inner join dependant dp on em.employee_id = dp.employee_id group by em.employee_id ```
20,186,146
The following HTML/CSS code is rendering in IE (Version 8) but not in Firefox (Version 25) Any reason why? HTML: ``` <img class="buttonmini" id="btn_Actual_Effort" onclick="showEffortDetail()" disabled="disabled"> ``` CSS: ``` .buttonmini { background: url(../newimages/effort_calendar.gif) no-repeat; height: 16px; width: 16px; font-family: Verdana; /*font-size: 8pt;*/ cursor: pointer; } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20186146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259889/" ]
``` select e.employee_id, e.employee_name , (select count(*) from dependent_table where employee_id=e.employee_id) as dependents from employee_table as e ```
``` select e.employee_id, e.employee_name, count(select * from dependent table where dependent table.employee_id=employee table.employee_id) from employee table e where e.employee_id=123 ``` try this
20,186,146
The following HTML/CSS code is rendering in IE (Version 8) but not in Firefox (Version 25) Any reason why? HTML: ``` <img class="buttonmini" id="btn_Actual_Effort" onclick="showEffortDetail()" disabled="disabled"> ``` CSS: ``` .buttonmini { background: url(../newimages/effort_calendar.gif) no-repeat; height: 16px; width: 16px; font-family: Verdana; /*font-size: 8pt;*/ cursor: pointer; } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20186146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259889/" ]
Try this query: ``` select e.employee_id,e.employee_name,count(d.employee_id) as dependents from department d inner join employee e on (e.employee_id=d.employee_id) group by d.employee_id; ``` [Sql Fiddle Example](http://sqlfiddle.com/#!2/75a30/4)
``` select e.employee_id, e.employee_name, count(select * from dependent table where dependent table.employee_id=employee table.employee_id) from employee table e where e.employee_id=123 ``` try this
20,186,146
The following HTML/CSS code is rendering in IE (Version 8) but not in Firefox (Version 25) Any reason why? HTML: ``` <img class="buttonmini" id="btn_Actual_Effort" onclick="showEffortDetail()" disabled="disabled"> ``` CSS: ``` .buttonmini { background: url(../newimages/effort_calendar.gif) no-repeat; height: 16px; width: 16px; font-family: Verdana; /*font-size: 8pt;*/ cursor: pointer; } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20186146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259889/" ]
``` select e.employee_id, e.employee_name , (select count(*) from dependent_table where employee_id=e.employee_id) as dependents from employee_table as e ```
try this its worked ``` select a.empid ,a.empname , count(b.deptname) from employee a , dependent b where a.empid = b.empid and b.empid=123; ```
20,186,146
The following HTML/CSS code is rendering in IE (Version 8) but not in Firefox (Version 25) Any reason why? HTML: ``` <img class="buttonmini" id="btn_Actual_Effort" onclick="showEffortDetail()" disabled="disabled"> ``` CSS: ``` .buttonmini { background: url(../newimages/effort_calendar.gif) no-repeat; height: 16px; width: 16px; font-family: Verdana; /*font-size: 8pt;*/ cursor: pointer; } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20186146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259889/" ]
Try this query: ``` select e.employee_id,e.employee_name,count(d.employee_id) as dependents from department d inner join employee e on (e.employee_id=d.employee_id) group by d.employee_id; ``` [Sql Fiddle Example](http://sqlfiddle.com/#!2/75a30/4)
``` select e.employee_id, e.employee_name , (select count(*) from dependent_table where employee_id=e.employee_id) as dependents from employee_table as e ```
20,186,146
The following HTML/CSS code is rendering in IE (Version 8) but not in Firefox (Version 25) Any reason why? HTML: ``` <img class="buttonmini" id="btn_Actual_Effort" onclick="showEffortDetail()" disabled="disabled"> ``` CSS: ``` .buttonmini { background: url(../newimages/effort_calendar.gif) no-repeat; height: 16px; width: 16px; font-family: Verdana; /*font-size: 8pt;*/ cursor: pointer; } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20186146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259889/" ]
Try this query: ``` select e.employee_id,e.employee_name,count(d.employee_id) as dependents from department d inner join employee e on (e.employee_id=d.employee_id) group by d.employee_id; ``` [Sql Fiddle Example](http://sqlfiddle.com/#!2/75a30/4)
try this its worked ``` select a.empid ,a.empname , count(b.deptname) from employee a , dependent b where a.empid = b.empid and b.empid=123; ```
38,983,642
I need to handle the following exception thrown by my suite when running the test on Chrome browser on Android real device using Appium 1.4.16.1. I believe the exception is thrown because of a timeout (set to 10s) on Appium, after which the session is deleted. However, once the exception is thrown by Selenium Webdriver (at line `wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(UILoc)))`), it is not caught using catch block and any further execution is hanged. Note that same test case when executed on desktop chrome browser is able to catch the exception. Please let me know if there is a way to catch this, as I need to do further handling. Note that I can avoid the situation by increasing timeout of Appium session. However, I still want to handle the max limit. **Appium Timeout Logs** ``` > info: --> POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/url {"url":"http://test.com"} > info: JSONWP Proxy: Proxying [POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/url] to [POST hubsession] with body: {"url":"http://test.com"} > info: [debug] Didn't get a new command in 10 secs, shutting down... > info: Shutting down appium session > info: Chromedriver: Changed state to 'stopping' > info: JSONWP Proxy: Proxying [DELETE /] to [DELETE hubsession] with no body > info: JSONWP Proxy: Got response with status 200: {"sessionId":"5ff4eaccea1df145b80f6df4af4c3d7b","status":0,"value":null} > info: JSONWP Proxy: Replacing sessionId 5ff4eaccea1df145b80f6df4af4c3d7b with 5ff4eaccea1df145b80f6df4af4c3d7b > info: <-- POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/url 200 110858.244 ms - 72 > info: --> POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/element {"using":"xpath","value":"//div[@id='form-1010']"} > info: JSONWP Proxy: Proxying [POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/element] to [POST hubsession] with body: {"using":"xpath","value":"//div[@id='form-1010']"} > info: JSONWP Proxy: Got response with status 200: "{\"sessionId\":\"5ff4eaccea1df145b80f6df4af4c3d7b\",\"status\":0,\"value\":null}" > info: JSONWP Proxy: Got response with status 200: {"sessionId":"","status":6,"value":{"message":"no such session\n (Driver info: chromedriver=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129),platform=Windows NT 10.0.10586 x86_64)"}} > info: <-- POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/element 200 743.048 ms - 189 > info: Chromedriver: Changed state to 'stopped' > info: [debug] [BOOTSTRAP] [debug] Got data from client: {"cmd":"shutdown"} > info: [debug] [BOOTSTRAP] [debug] Got command of type SHUTDOWN > info: [debug] [BOOTSTRAP] [debug] Returning result: {"value":"OK, shutting down","status":0} > info: [debug] [BOOTSTRAP] [debug] Closed client connection ``` **Webdriver Exception Logs** ``` Aug 17, 2016 12:49:44 AM org.openqa.selenium.support.ui.ExpectedConditions findElement WARNING: WebDriverException thrown by findElement(By.xpath: //div[@id='form-1010']) org.openqa.selenium.remote.SessionNotFoundException: no such session (Driver info: chromedriver=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129),platform=Windows NT 10.0.10586 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 753 milliseconds Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58' System info: host: 'Pune832', ip: '10.10.148.44', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_60' Driver info: org.openqa.selenium.remote.RemoteWebDriver Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, chrome={chromedriverVersion=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129)}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=true, version=52.0.2743.98, platform=ANDROID, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}] Session ID: 5ff4eaccea1df145b80f6df4af4c3d7b *** Element info: {Using=xpath, value=//div[@id='form-1010']} at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206) at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678) at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363) at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500) at org.openqa.selenium.By$ByXPath.findElement(By.java:361) at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355) at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:899) at org.openqa.selenium.support.ui.ExpectedConditions.access$0(ExpectedConditions.java:897) at org.openqa.selenium.support.ui.ExpectedConditions$6.apply(ExpectedConditions.java:181) at org.openqa.selenium.support.ui.ExpectedConditions$6.apply(ExpectedConditions.java:1) at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:238) ```
2016/08/16
[ "https://Stackoverflow.com/questions/38983642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2171158/" ]
Use express.js named route parameters: <http://expressjs.com/en/guide/routing.html#route-parameters>
What you are describing is what's referred to as a restful web api implemented with routing You'll typically want to build your site in a MVC (**M**odel **V**iew **C**ontroller) framework to get this functionality. Express.js is new hotness on the block - especially in the context of javascript and node.js categories tied to this question - but there are others out there as well. Ruby on Rails made MVC and restful routing popular, and MS has ASP.NET MVC. PHP even has CodeIgniter and others I'm sure, and Angular2 is Google's MVC baby at the moment. The point is, there are many frameworks to choose from that will give you the restful URL routing you're looking for. Find one you like, and run with it!
38,983,642
I need to handle the following exception thrown by my suite when running the test on Chrome browser on Android real device using Appium 1.4.16.1. I believe the exception is thrown because of a timeout (set to 10s) on Appium, after which the session is deleted. However, once the exception is thrown by Selenium Webdriver (at line `wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(UILoc)))`), it is not caught using catch block and any further execution is hanged. Note that same test case when executed on desktop chrome browser is able to catch the exception. Please let me know if there is a way to catch this, as I need to do further handling. Note that I can avoid the situation by increasing timeout of Appium session. However, I still want to handle the max limit. **Appium Timeout Logs** ``` > info: --> POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/url {"url":"http://test.com"} > info: JSONWP Proxy: Proxying [POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/url] to [POST hubsession] with body: {"url":"http://test.com"} > info: [debug] Didn't get a new command in 10 secs, shutting down... > info: Shutting down appium session > info: Chromedriver: Changed state to 'stopping' > info: JSONWP Proxy: Proxying [DELETE /] to [DELETE hubsession] with no body > info: JSONWP Proxy: Got response with status 200: {"sessionId":"5ff4eaccea1df145b80f6df4af4c3d7b","status":0,"value":null} > info: JSONWP Proxy: Replacing sessionId 5ff4eaccea1df145b80f6df4af4c3d7b with 5ff4eaccea1df145b80f6df4af4c3d7b > info: <-- POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/url 200 110858.244 ms - 72 > info: --> POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/element {"using":"xpath","value":"//div[@id='form-1010']"} > info: JSONWP Proxy: Proxying [POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/element] to [POST hubsession] with body: {"using":"xpath","value":"//div[@id='form-1010']"} > info: JSONWP Proxy: Got response with status 200: "{\"sessionId\":\"5ff4eaccea1df145b80f6df4af4c3d7b\",\"status\":0,\"value\":null}" > info: JSONWP Proxy: Got response with status 200: {"sessionId":"","status":6,"value":{"message":"no such session\n (Driver info: chromedriver=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129),platform=Windows NT 10.0.10586 x86_64)"}} > info: <-- POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/element 200 743.048 ms - 189 > info: Chromedriver: Changed state to 'stopped' > info: [debug] [BOOTSTRAP] [debug] Got data from client: {"cmd":"shutdown"} > info: [debug] [BOOTSTRAP] [debug] Got command of type SHUTDOWN > info: [debug] [BOOTSTRAP] [debug] Returning result: {"value":"OK, shutting down","status":0} > info: [debug] [BOOTSTRAP] [debug] Closed client connection ``` **Webdriver Exception Logs** ``` Aug 17, 2016 12:49:44 AM org.openqa.selenium.support.ui.ExpectedConditions findElement WARNING: WebDriverException thrown by findElement(By.xpath: //div[@id='form-1010']) org.openqa.selenium.remote.SessionNotFoundException: no such session (Driver info: chromedriver=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129),platform=Windows NT 10.0.10586 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 753 milliseconds Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58' System info: host: 'Pune832', ip: '10.10.148.44', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_60' Driver info: org.openqa.selenium.remote.RemoteWebDriver Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, chrome={chromedriverVersion=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129)}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=true, version=52.0.2743.98, platform=ANDROID, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}] Session ID: 5ff4eaccea1df145b80f6df4af4c3d7b *** Element info: {Using=xpath, value=//div[@id='form-1010']} at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206) at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678) at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363) at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500) at org.openqa.selenium.By$ByXPath.findElement(By.java:361) at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355) at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:899) at org.openqa.selenium.support.ui.ExpectedConditions.access$0(ExpectedConditions.java:897) at org.openqa.selenium.support.ui.ExpectedConditions$6.apply(ExpectedConditions.java:181) at org.openqa.selenium.support.ui.ExpectedConditions$6.apply(ExpectedConditions.java:1) at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:238) ```
2016/08/16
[ "https://Stackoverflow.com/questions/38983642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2171158/" ]
Use req.params as in express documentation Route path: `/users/:userId/books/:bookId` Request URL: `http://localhost:3000/users/34/books/8989` req.params: `{ "userId": "34", "bookId": "8989" }` **In case of using raw http** for using with raw http module you can use `str.split("/")[2]`; ``` var http = require('http'); function handleRequest(request, response){ response.end('It Works!! Path Hit: ' + request.url); var str = request.url; var exampleId = str.split("/")[2]; } var server = http.createServer(handleRequest); server.listen(8080, function(){}); ```
Use express.js named route parameters: <http://expressjs.com/en/guide/routing.html#route-parameters>
38,983,642
I need to handle the following exception thrown by my suite when running the test on Chrome browser on Android real device using Appium 1.4.16.1. I believe the exception is thrown because of a timeout (set to 10s) on Appium, after which the session is deleted. However, once the exception is thrown by Selenium Webdriver (at line `wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(UILoc)))`), it is not caught using catch block and any further execution is hanged. Note that same test case when executed on desktop chrome browser is able to catch the exception. Please let me know if there is a way to catch this, as I need to do further handling. Note that I can avoid the situation by increasing timeout of Appium session. However, I still want to handle the max limit. **Appium Timeout Logs** ``` > info: --> POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/url {"url":"http://test.com"} > info: JSONWP Proxy: Proxying [POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/url] to [POST hubsession] with body: {"url":"http://test.com"} > info: [debug] Didn't get a new command in 10 secs, shutting down... > info: Shutting down appium session > info: Chromedriver: Changed state to 'stopping' > info: JSONWP Proxy: Proxying [DELETE /] to [DELETE hubsession] with no body > info: JSONWP Proxy: Got response with status 200: {"sessionId":"5ff4eaccea1df145b80f6df4af4c3d7b","status":0,"value":null} > info: JSONWP Proxy: Replacing sessionId 5ff4eaccea1df145b80f6df4af4c3d7b with 5ff4eaccea1df145b80f6df4af4c3d7b > info: <-- POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/url 200 110858.244 ms - 72 > info: --> POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/element {"using":"xpath","value":"//div[@id='form-1010']"} > info: JSONWP Proxy: Proxying [POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/element] to [POST hubsession] with body: {"using":"xpath","value":"//div[@id='form-1010']"} > info: JSONWP Proxy: Got response with status 200: "{\"sessionId\":\"5ff4eaccea1df145b80f6df4af4c3d7b\",\"status\":0,\"value\":null}" > info: JSONWP Proxy: Got response with status 200: {"sessionId":"","status":6,"value":{"message":"no such session\n (Driver info: chromedriver=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129),platform=Windows NT 10.0.10586 x86_64)"}} > info: <-- POST /wd/hub/session/5ff4eaccea1df145b80f6df4af4c3d7b/element 200 743.048 ms - 189 > info: Chromedriver: Changed state to 'stopped' > info: [debug] [BOOTSTRAP] [debug] Got data from client: {"cmd":"shutdown"} > info: [debug] [BOOTSTRAP] [debug] Got command of type SHUTDOWN > info: [debug] [BOOTSTRAP] [debug] Returning result: {"value":"OK, shutting down","status":0} > info: [debug] [BOOTSTRAP] [debug] Closed client connection ``` **Webdriver Exception Logs** ``` Aug 17, 2016 12:49:44 AM org.openqa.selenium.support.ui.ExpectedConditions findElement WARNING: WebDriverException thrown by findElement(By.xpath: //div[@id='form-1010']) org.openqa.selenium.remote.SessionNotFoundException: no such session (Driver info: chromedriver=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129),platform=Windows NT 10.0.10586 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 753 milliseconds Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 17:00:58' System info: host: 'Pune832', ip: '10.10.148.44', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_60' Driver info: org.openqa.selenium.remote.RemoteWebDriver Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, chrome={chromedriverVersion=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129)}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=true, version=52.0.2743.98, platform=ANDROID, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}] Session ID: 5ff4eaccea1df145b80f6df4af4c3d7b *** Element info: {Using=xpath, value=//div[@id='form-1010']} at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206) at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678) at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363) at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500) at org.openqa.selenium.By$ByXPath.findElement(By.java:361) at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355) at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:899) at org.openqa.selenium.support.ui.ExpectedConditions.access$0(ExpectedConditions.java:897) at org.openqa.selenium.support.ui.ExpectedConditions$6.apply(ExpectedConditions.java:181) at org.openqa.selenium.support.ui.ExpectedConditions$6.apply(ExpectedConditions.java:1) at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:238) ```
2016/08/16
[ "https://Stackoverflow.com/questions/38983642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2171158/" ]
Use req.params as in express documentation Route path: `/users/:userId/books/:bookId` Request URL: `http://localhost:3000/users/34/books/8989` req.params: `{ "userId": "34", "bookId": "8989" }` **In case of using raw http** for using with raw http module you can use `str.split("/")[2]`; ``` var http = require('http'); function handleRequest(request, response){ response.end('It Works!! Path Hit: ' + request.url); var str = request.url; var exampleId = str.split("/")[2]; } var server = http.createServer(handleRequest); server.listen(8080, function(){}); ```
What you are describing is what's referred to as a restful web api implemented with routing You'll typically want to build your site in a MVC (**M**odel **V**iew **C**ontroller) framework to get this functionality. Express.js is new hotness on the block - especially in the context of javascript and node.js categories tied to this question - but there are others out there as well. Ruby on Rails made MVC and restful routing popular, and MS has ASP.NET MVC. PHP even has CodeIgniter and others I'm sure, and Angular2 is Google's MVC baby at the moment. The point is, there are many frameworks to choose from that will give you the restful URL routing you're looking for. Find one you like, and run with it!
28,165,647
I have a project using SpecFlow and NUnit 2.6.3 as my test provider. Currently it is working OK but now there is the requirement to run tests in parallel, as they become more and more heavy. Reading along, I can see that NUnit version 3 will support parallelism out of the box, but it is still in alpha. And I am unable to run the tests generated by SpecFlow with Nunit 3.. Does any one have an idea if it is possible to use SpecFlow and NUnit version 3 by this moment? Or some other approach, still using NUnit version 2.6.3 and SpecFlow for achieving parallelism? Thanks!
2015/01/27
[ "https://Stackoverflow.com/questions/28165647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2160353/" ]
Thanks a lot for the suggestions. I come out with own custom solution - just exploring the test dll with reflection from a custom command line app which then spawns separate OS processes each of them calling nunit-console.exe with the --include parameter specifying only a particular group of tests. This way I avoid any thread unsafely code and still achieving my goal. **Edit** Btw, [here is my solution](https://bitbucket.org/akrsmv/parallel-tests), I hope someone may find it useful. Even though now there is builtin parallelism in nunit 3+, this was battle tested against thousands of specflow / selenium tests. It also has a nice TeamCity integration. I think its simple enough (3-4 classes in total) and I tried to document all the console options available in the `README` file
I ran into the same situation. I came up with a solution using Selenium Grid, the task parallel library and the DynamicObject class. I wrote about it here <http://blog.dmbcllc.com/running-selenium-in-parallel-with-any-net-unit-testing-tool/>. (Too long to copy and paste). Hope it helps. As far as I know, until 3 releases, this is the best we can do.
28,165,647
I have a project using SpecFlow and NUnit 2.6.3 as my test provider. Currently it is working OK but now there is the requirement to run tests in parallel, as they become more and more heavy. Reading along, I can see that NUnit version 3 will support parallelism out of the box, but it is still in alpha. And I am unable to run the tests generated by SpecFlow with Nunit 3.. Does any one have an idea if it is possible to use SpecFlow and NUnit version 3 by this moment? Or some other approach, still using NUnit version 2.6.3 and SpecFlow for achieving parallelism? Thanks!
2015/01/27
[ "https://Stackoverflow.com/questions/28165647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2160353/" ]
I ran into the same situation. I came up with a solution using Selenium Grid, the task parallel library and the DynamicObject class. I wrote about it here <http://blog.dmbcllc.com/running-selenium-in-parallel-with-any-net-unit-testing-tool/>. (Too long to copy and paste). Hope it helps. As far as I know, until 3 releases, this is the best we can do.
I've tested parallel test case execution at fixture level with NUnit 3.2.0. As of writing, SpecFlow 2.0 does support parallelism and is working well with NUnit 3.2.0, however SpecFlow reporting engine is not able to produce HTML reports from NUnit test execution output. The [issue is being tracked here over GitHub](https://github.com/techtalk/SpecFlow/issues/539)
28,165,647
I have a project using SpecFlow and NUnit 2.6.3 as my test provider. Currently it is working OK but now there is the requirement to run tests in parallel, as they become more and more heavy. Reading along, I can see that NUnit version 3 will support parallelism out of the box, but it is still in alpha. And I am unable to run the tests generated by SpecFlow with Nunit 3.. Does any one have an idea if it is possible to use SpecFlow and NUnit version 3 by this moment? Or some other approach, still using NUnit version 2.6.3 and SpecFlow for achieving parallelism? Thanks!
2015/01/27
[ "https://Stackoverflow.com/questions/28165647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2160353/" ]
Thanks a lot for the suggestions. I come out with own custom solution - just exploring the test dll with reflection from a custom command line app which then spawns separate OS processes each of them calling nunit-console.exe with the --include parameter specifying only a particular group of tests. This way I avoid any thread unsafely code and still achieving my goal. **Edit** Btw, [here is my solution](https://bitbucket.org/akrsmv/parallel-tests), I hope someone may find it useful. Even though now there is builtin parallelism in nunit 3+, this was battle tested against thousands of specflow / selenium tests. It also has a nice TeamCity integration. I think its simple enough (3-4 classes in total) and I tried to document all the console options available in the `README` file
I've tested parallel test case execution at fixture level with NUnit 3.2.0. As of writing, SpecFlow 2.0 does support parallelism and is working well with NUnit 3.2.0, however SpecFlow reporting engine is not able to produce HTML reports from NUnit test execution output. The [issue is being tracked here over GitHub](https://github.com/techtalk/SpecFlow/issues/539)