qid
int64
2
74.7M
question
stringlengths
31
65.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
4
63.3k
response_k
stringlengths
4
60.5k
6,767,418
I am using Dotnet Web Browser to click an Input Element - Button. When this click event is fired, it performs a JS function, which generates captcha using Google Recaptcher, source of which looks like [Recaptcha link](http://www.google.com/recaptcha/api/image?c=03AHJ_Vusqkf0oZKUKbZvLFnuK8XBnPIR0SP_X97t6lCmLgrlgPwUhlpFTPybk4fWg9Nm4cSFc-DIxfIlJErIVLt_deEgfGZA3BJGsCxM5-CB-7YuEj_Gf-_qmnD5LDv3hbJJRqC44S4vwI-7JGZNyp7gJEIdAYcSoxsEEg7O49hHFSfuV6u43P5aGzA79T7ajZcqW-N20p2q2). Now the issue is that I am **unable to fire the onClick event**, I am using the following code: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); inputTag.InvokeMember("Click"); break; } } ``` I have checked everything, I am catching the right button, but don't know why the onClick event is not getting fired. Any suggestion is welcome.
2011/07/20
[ "https://Stackoverflow.com/questions/6767418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434685/" ]
1. Add reference to Microsoft.mshtml; 2. Look at the fixed example below: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); IHTMLElement nativeElement = el.DomElement as IHTMLElement; nativeElement.click(); break; } } ```
This should work for sure. I tested it on Anchors and DIvs that contain the onclick event. ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { obj = inputTag.DomElement; mi = obj.GetType().GetMethod("click"); mi.Invoke(obj, new object[0]); } } ``` I've not been able to open the link to see the code, therefore I did not try it on your case specifically. Anyway, if this does not work, may the TAG container is inserted into a Form, in that case you have to fire the submit event of the form, not firing the click on the sorm submit button. Anyway, may your code will work as well if you call "click" as lowercase ( I truly did not verify, just guessing, nut in C# case matter!). PS: See [Webbrowser: sequencing activites when no DocumentCompleted is fired by a link on hosted webpage](https://stackoverflow.com/questions/10155196/webbrowser-sequencing-activites-when-no-documentcompleted-is-fired-by-a-link-on) for some interesting side code for you case, hope it helps and may someone helps me by return!
6,767,418
I am using Dotnet Web Browser to click an Input Element - Button. When this click event is fired, it performs a JS function, which generates captcha using Google Recaptcher, source of which looks like [Recaptcha link](http://www.google.com/recaptcha/api/image?c=03AHJ_Vusqkf0oZKUKbZvLFnuK8XBnPIR0SP_X97t6lCmLgrlgPwUhlpFTPybk4fWg9Nm4cSFc-DIxfIlJErIVLt_deEgfGZA3BJGsCxM5-CB-7YuEj_Gf-_qmnD5LDv3hbJJRqC44S4vwI-7JGZNyp7gJEIdAYcSoxsEEg7O49hHFSfuV6u43P5aGzA79T7ajZcqW-N20p2q2). Now the issue is that I am **unable to fire the onClick event**, I am using the following code: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); inputTag.InvokeMember("Click"); break; } } ``` I have checked everything, I am catching the right button, but don't know why the onClick event is not getting fired. Any suggestion is welcome.
2011/07/20
[ "https://Stackoverflow.com/questions/6767418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434685/" ]
1. Add reference to Microsoft.mshtml; 2. Look at the fixed example below: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); IHTMLElement nativeElement = el.DomElement as IHTMLElement; nativeElement.click(); break; } } ```
As you already have the object in focus, try sending the `ENTER` key like this: ``` SendKeys.Send("{ENTER}") ```
6,767,418
I am using Dotnet Web Browser to click an Input Element - Button. When this click event is fired, it performs a JS function, which generates captcha using Google Recaptcher, source of which looks like [Recaptcha link](http://www.google.com/recaptcha/api/image?c=03AHJ_Vusqkf0oZKUKbZvLFnuK8XBnPIR0SP_X97t6lCmLgrlgPwUhlpFTPybk4fWg9Nm4cSFc-DIxfIlJErIVLt_deEgfGZA3BJGsCxM5-CB-7YuEj_Gf-_qmnD5LDv3hbJJRqC44S4vwI-7JGZNyp7gJEIdAYcSoxsEEg7O49hHFSfuV6u43P5aGzA79T7ajZcqW-N20p2q2). Now the issue is that I am **unable to fire the onClick event**, I am using the following code: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); inputTag.InvokeMember("Click"); break; } } ``` I have checked everything, I am catching the right button, but don't know why the onClick event is not getting fired. Any suggestion is welcome.
2011/07/20
[ "https://Stackoverflow.com/questions/6767418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434685/" ]
1. Add reference to Microsoft.mshtml; 2. Look at the fixed example below: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); IHTMLElement nativeElement = el.DomElement as IHTMLElement; nativeElement.click(); break; } } ```
Try ``` if (inputTag.InnerHtml == "sign up" || inputTag.InnerText.Contains("sign up")) { inputTag.InvokeMember("click"); } ``` Just play with the conditions, check if you get the right button. BTW, small case "click" on InvokeMember. This is what I use, and it works for me.
6,767,418
I am using Dotnet Web Browser to click an Input Element - Button. When this click event is fired, it performs a JS function, which generates captcha using Google Recaptcher, source of which looks like [Recaptcha link](http://www.google.com/recaptcha/api/image?c=03AHJ_Vusqkf0oZKUKbZvLFnuK8XBnPIR0SP_X97t6lCmLgrlgPwUhlpFTPybk4fWg9Nm4cSFc-DIxfIlJErIVLt_deEgfGZA3BJGsCxM5-CB-7YuEj_Gf-_qmnD5LDv3hbJJRqC44S4vwI-7JGZNyp7gJEIdAYcSoxsEEg7O49hHFSfuV6u43P5aGzA79T7ajZcqW-N20p2q2). Now the issue is that I am **unable to fire the onClick event**, I am using the following code: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); inputTag.InvokeMember("Click"); break; } } ``` I have checked everything, I am catching the right button, but don't know why the onClick event is not getting fired. Any suggestion is welcome.
2011/07/20
[ "https://Stackoverflow.com/questions/6767418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434685/" ]
This should work for sure. I tested it on Anchors and DIvs that contain the onclick event. ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { obj = inputTag.DomElement; mi = obj.GetType().GetMethod("click"); mi.Invoke(obj, new object[0]); } } ``` I've not been able to open the link to see the code, therefore I did not try it on your case specifically. Anyway, if this does not work, may the TAG container is inserted into a Form, in that case you have to fire the submit event of the form, not firing the click on the sorm submit button. Anyway, may your code will work as well if you call "click" as lowercase ( I truly did not verify, just guessing, nut in C# case matter!). PS: See [Webbrowser: sequencing activites when no DocumentCompleted is fired by a link on hosted webpage](https://stackoverflow.com/questions/10155196/webbrowser-sequencing-activites-when-no-documentcompleted-is-fired-by-a-link-on) for some interesting side code for you case, hope it helps and may someone helps me by return!
Are you sure "Click" is the correct name? I have some almost identical code, to do exactly the same thing, and the attribute name is "onclick". Have another look at the HTML for the page. ``` foreach (HtmlElement element in col) { if (element.GetAttribute(attribute).Equals(attName)) { // Invoke the "Click" member of the button element.InvokeMember("onclick"); } } ```
6,767,418
I am using Dotnet Web Browser to click an Input Element - Button. When this click event is fired, it performs a JS function, which generates captcha using Google Recaptcher, source of which looks like [Recaptcha link](http://www.google.com/recaptcha/api/image?c=03AHJ_Vusqkf0oZKUKbZvLFnuK8XBnPIR0SP_X97t6lCmLgrlgPwUhlpFTPybk4fWg9Nm4cSFc-DIxfIlJErIVLt_deEgfGZA3BJGsCxM5-CB-7YuEj_Gf-_qmnD5LDv3hbJJRqC44S4vwI-7JGZNyp7gJEIdAYcSoxsEEg7O49hHFSfuV6u43P5aGzA79T7ajZcqW-N20p2q2). Now the issue is that I am **unable to fire the onClick event**, I am using the following code: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); inputTag.InvokeMember("Click"); break; } } ``` I have checked everything, I am catching the right button, but don't know why the onClick event is not getting fired. Any suggestion is welcome.
2011/07/20
[ "https://Stackoverflow.com/questions/6767418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434685/" ]
Are you sure "Click" is the correct name? I have some almost identical code, to do exactly the same thing, and the attribute name is "onclick". Have another look at the HTML for the page. ``` foreach (HtmlElement element in col) { if (element.GetAttribute(attribute).Equals(attName)) { // Invoke the "Click" member of the button element.InvokeMember("onclick"); } } ```
As you already have the object in focus, try sending the `ENTER` key like this: ``` SendKeys.Send("{ENTER}") ```
6,767,418
I am using Dotnet Web Browser to click an Input Element - Button. When this click event is fired, it performs a JS function, which generates captcha using Google Recaptcher, source of which looks like [Recaptcha link](http://www.google.com/recaptcha/api/image?c=03AHJ_Vusqkf0oZKUKbZvLFnuK8XBnPIR0SP_X97t6lCmLgrlgPwUhlpFTPybk4fWg9Nm4cSFc-DIxfIlJErIVLt_deEgfGZA3BJGsCxM5-CB-7YuEj_Gf-_qmnD5LDv3hbJJRqC44S4vwI-7JGZNyp7gJEIdAYcSoxsEEg7O49hHFSfuV6u43P5aGzA79T7ajZcqW-N20p2q2). Now the issue is that I am **unable to fire the onClick event**, I am using the following code: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); inputTag.InvokeMember("Click"); break; } } ``` I have checked everything, I am catching the right button, but don't know why the onClick event is not getting fired. Any suggestion is welcome.
2011/07/20
[ "https://Stackoverflow.com/questions/6767418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434685/" ]
This should work for sure. I tested it on Anchors and DIvs that contain the onclick event. ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { obj = inputTag.DomElement; mi = obj.GetType().GetMethod("click"); mi.Invoke(obj, new object[0]); } } ``` I've not been able to open the link to see the code, therefore I did not try it on your case specifically. Anyway, if this does not work, may the TAG container is inserted into a Form, in that case you have to fire the submit event of the form, not firing the click on the sorm submit button. Anyway, may your code will work as well if you call "click" as lowercase ( I truly did not verify, just guessing, nut in C# case matter!). PS: See [Webbrowser: sequencing activites when no DocumentCompleted is fired by a link on hosted webpage](https://stackoverflow.com/questions/10155196/webbrowser-sequencing-activites-when-no-documentcompleted-is-fired-by-a-link-on) for some interesting side code for you case, hope it helps and may someone helps me by return!
As you already have the object in focus, try sending the `ENTER` key like this: ``` SendKeys.Send("{ENTER}") ```
6,767,418
I am using Dotnet Web Browser to click an Input Element - Button. When this click event is fired, it performs a JS function, which generates captcha using Google Recaptcher, source of which looks like [Recaptcha link](http://www.google.com/recaptcha/api/image?c=03AHJ_Vusqkf0oZKUKbZvLFnuK8XBnPIR0SP_X97t6lCmLgrlgPwUhlpFTPybk4fWg9Nm4cSFc-DIxfIlJErIVLt_deEgfGZA3BJGsCxM5-CB-7YuEj_Gf-_qmnD5LDv3hbJJRqC44S4vwI-7JGZNyp7gJEIdAYcSoxsEEg7O49hHFSfuV6u43P5aGzA79T7ajZcqW-N20p2q2). Now the issue is that I am **unable to fire the onClick event**, I am using the following code: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); inputTag.InvokeMember("Click"); break; } } ``` I have checked everything, I am catching the right button, but don't know why the onClick event is not getting fired. Any suggestion is welcome.
2011/07/20
[ "https://Stackoverflow.com/questions/6767418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434685/" ]
This should work for sure. I tested it on Anchors and DIvs that contain the onclick event. ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { obj = inputTag.DomElement; mi = obj.GetType().GetMethod("click"); mi.Invoke(obj, new object[0]); } } ``` I've not been able to open the link to see the code, therefore I did not try it on your case specifically. Anyway, if this does not work, may the TAG container is inserted into a Form, in that case you have to fire the submit event of the form, not firing the click on the sorm submit button. Anyway, may your code will work as well if you call "click" as lowercase ( I truly did not verify, just guessing, nut in C# case matter!). PS: See [Webbrowser: sequencing activites when no DocumentCompleted is fired by a link on hosted webpage](https://stackoverflow.com/questions/10155196/webbrowser-sequencing-activites-when-no-documentcompleted-is-fired-by-a-link-on) for some interesting side code for you case, hope it helps and may someone helps me by return!
Try ``` if (inputTag.InnerHtml == "sign up" || inputTag.InnerText.Contains("sign up")) { inputTag.InvokeMember("click"); } ``` Just play with the conditions, check if you get the right button. BTW, small case "click" on InvokeMember. This is what I use, and it works for me.
6,767,418
I am using Dotnet Web Browser to click an Input Element - Button. When this click event is fired, it performs a JS function, which generates captcha using Google Recaptcher, source of which looks like [Recaptcha link](http://www.google.com/recaptcha/api/image?c=03AHJ_Vusqkf0oZKUKbZvLFnuK8XBnPIR0SP_X97t6lCmLgrlgPwUhlpFTPybk4fWg9Nm4cSFc-DIxfIlJErIVLt_deEgfGZA3BJGsCxM5-CB-7YuEj_Gf-_qmnD5LDv3hbJJRqC44S4vwI-7JGZNyp7gJEIdAYcSoxsEEg7O49hHFSfuV6u43P5aGzA79T7ajZcqW-N20p2q2). Now the issue is that I am **unable to fire the onClick event**, I am using the following code: ``` HtmlElementCollection inputColl = HTMLDoc.GetElementsByTagName("input"); foreach (HtmlElement inputTag in inputColl) { string valueAttribute = inputTag.GetAttribute("value"); if (valueAttribute.ToLower() == "sign up") { inputTag.Focus(); inputTag.InvokeMember("Click"); break; } } ``` I have checked everything, I am catching the right button, but don't know why the onClick event is not getting fired. Any suggestion is welcome.
2011/07/20
[ "https://Stackoverflow.com/questions/6767418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434685/" ]
Try ``` if (inputTag.InnerHtml == "sign up" || inputTag.InnerText.Contains("sign up")) { inputTag.InvokeMember("click"); } ``` Just play with the conditions, check if you get the right button. BTW, small case "click" on InvokeMember. This is what I use, and it works for me.
As you already have the object in focus, try sending the `ENTER` key like this: ``` SendKeys.Send("{ENTER}") ```
21,692,553
I do have a table that is generated dynamically from MySQL table values. Each listed record has a checkbox. list.php ``` $query="SELECT * FROM drivers ORDER BY name"; $query=$mysqli->query($query); $queryN=mysqli_num_rows($query); if($queryN!=0){ while($row=mysqli_fetch_assoc($query)){ $id=$row['id']; $name=$row['name']; $output .='<tr id="'.$id.'"> <td>'.$name.'</td> <td><input type="checkbox" name="assign" class="assigned" value='.$id.'"/></td> </tr>'; } }else{ $output .='<tr> <td colspan="2">No data found</td> </tr>'; } ``` The HTML file ``` <input type="button" name="send" id="send" value="Send" /> ``` Now the JQuery script that will send only the values of the checked checkboxes in the table: ``` <script> $(document).ready(function(){ $('.send').click(function(){ var checkValues = $('input[name=assign]:checked').map(function() { return $(this).val(); }).get(); $.ajax({ url: 'assigndriver.php', type: 'post', data: { ids: checkValues }, success:function(data){ } }); }); }); </script> ``` Finally, the PHP file assigndriver.php that will insert the array with the values of only checked checkboxes: ``` include "../connect_to_mysql.php"; $id = array(); if(isset($_POST['ids'])){ $id = $_POST['ids']; for ($i = 0; $i < count($id); $i++) { $id_new = $id[$i]; $sql="INSERT INTO teste (campo) VALUES ('$id_new')"; } } ``` Well, I would like to know why it isn't working and if in this way the correct value of the checkbox, that must be the variable $id is being posted correctly to the PHP file. Thank you
2014/02/11
[ "https://Stackoverflow.com/questions/21692553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2855309/" ]
Try to change: ``` $('.send').click( ``` to: ``` $('#send').click( ``` since you assign `id="send"` not `class="send"` to your input button
You should change the name of the checkbox as name="something[]". So it will know it is an array and values will posted correctly. Hope this helps you.
21,692,553
I do have a table that is generated dynamically from MySQL table values. Each listed record has a checkbox. list.php ``` $query="SELECT * FROM drivers ORDER BY name"; $query=$mysqli->query($query); $queryN=mysqli_num_rows($query); if($queryN!=0){ while($row=mysqli_fetch_assoc($query)){ $id=$row['id']; $name=$row['name']; $output .='<tr id="'.$id.'"> <td>'.$name.'</td> <td><input type="checkbox" name="assign" class="assigned" value='.$id.'"/></td> </tr>'; } }else{ $output .='<tr> <td colspan="2">No data found</td> </tr>'; } ``` The HTML file ``` <input type="button" name="send" id="send" value="Send" /> ``` Now the JQuery script that will send only the values of the checked checkboxes in the table: ``` <script> $(document).ready(function(){ $('.send').click(function(){ var checkValues = $('input[name=assign]:checked').map(function() { return $(this).val(); }).get(); $.ajax({ url: 'assigndriver.php', type: 'post', data: { ids: checkValues }, success:function(data){ } }); }); }); </script> ``` Finally, the PHP file assigndriver.php that will insert the array with the values of only checked checkboxes: ``` include "../connect_to_mysql.php"; $id = array(); if(isset($_POST['ids'])){ $id = $_POST['ids']; for ($i = 0; $i < count($id); $i++) { $id_new = $id[$i]; $sql="INSERT INTO teste (campo) VALUES ('$id_new')"; } } ``` Well, I would like to know why it isn't working and if in this way the correct value of the checkbox, that must be the variable $id is being posted correctly to the PHP file. Thank you
2014/02/11
[ "https://Stackoverflow.com/questions/21692553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2855309/" ]
Try to change: ``` $('.send').click( ``` to: ``` $('#send').click( ``` since you assign `id="send"` not `class="send"` to your input button
In the jquery you call the send button using id **send** but while calling the function you use **.** operator insted of **#** operator. **Difference** ``` the difference between "." operator and "#" operator is when you calling a class you should use "." operator. Example: HTML: <input type="button" name="send" class="send" value="Send" /> JQUERY: $('.send').click(function(){ //insert your code here.. }); but if you are going to call an id of a html element than use "#" operetor Example: HTML: <input type="button" name="send" id="send" value="Send" onclick="send_data();" /> JQUERY: function send_data(){ $('#send').click(function(){ //insert your code here.. });} ``` Hope it will help you...
21,692,553
I do have a table that is generated dynamically from MySQL table values. Each listed record has a checkbox. list.php ``` $query="SELECT * FROM drivers ORDER BY name"; $query=$mysqli->query($query); $queryN=mysqli_num_rows($query); if($queryN!=0){ while($row=mysqli_fetch_assoc($query)){ $id=$row['id']; $name=$row['name']; $output .='<tr id="'.$id.'"> <td>'.$name.'</td> <td><input type="checkbox" name="assign" class="assigned" value='.$id.'"/></td> </tr>'; } }else{ $output .='<tr> <td colspan="2">No data found</td> </tr>'; } ``` The HTML file ``` <input type="button" name="send" id="send" value="Send" /> ``` Now the JQuery script that will send only the values of the checked checkboxes in the table: ``` <script> $(document).ready(function(){ $('.send').click(function(){ var checkValues = $('input[name=assign]:checked').map(function() { return $(this).val(); }).get(); $.ajax({ url: 'assigndriver.php', type: 'post', data: { ids: checkValues }, success:function(data){ } }); }); }); </script> ``` Finally, the PHP file assigndriver.php that will insert the array with the values of only checked checkboxes: ``` include "../connect_to_mysql.php"; $id = array(); if(isset($_POST['ids'])){ $id = $_POST['ids']; for ($i = 0; $i < count($id); $i++) { $id_new = $id[$i]; $sql="INSERT INTO teste (campo) VALUES ('$id_new')"; } } ``` Well, I would like to know why it isn't working and if in this way the correct value of the checkbox, that must be the variable $id is being posted correctly to the PHP file. Thank you
2014/02/11
[ "https://Stackoverflow.com/questions/21692553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2855309/" ]
Try to change: ``` $('.send').click( ``` to: ``` $('#send').click( ``` since you assign `id="send"` not `class="send"` to your input button
The right way to make the values of each checked checkbox be posted to the PHP file is doing the following script: ``` $(document).ready(function(){ $('#btnadd').click(function(){ var checkValues = $('input[name="assign[]"]:checked').map(function() { return $(this).val(); }).get(); $.ajax({ url: 'assigndriver.php', type: 'post', data: { ids: checkValues }, success:function(data){ } }); }); }); ``` Also, we need to change the dynamic output in the PHP file: ``` $output .='<td align="center"><input type="checkbox" name="assign[]" id="add_driver'.$id.'" value="'.$id.'"/></td>'; ``` If the checkbox is checked, the values will be posted correctly.
28,574,079
I have some Ruby on Rails / ActiveRecord code that is giving me the following Postgres error: PG::SyntaxError: ERROR: non-integer constant in ORDER I'm not sure why since it is a simple fetch ordered by created\_at ``` self.posts.order(created_at: :desc).limit(25) ``` What do I do to change this?
2015/02/18
[ "https://Stackoverflow.com/questions/28574079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2989664/" ]
I am not sure that syntax is supported in older versions of Rails, which is where I suspect you are. Try this instead: ``` self.posts.order("created_at desc").limit(25) ```
I have experienced this error as well after switching my Rails app from MySQL to PostgreSQL (my development environment and Gem list are at the bottom of this post). The error appears to be caused by PostgreSQL expecting the column names in a SQL query to be double-quoted, as I am able to eliminate the error by changing my ".order()" parameter from hash-format to a literal string: This Rails code triggers the error: ``` ModelName.where(:attribute => self.id).order(col1: :desc, col2: :asc) ``` ...and the resulting error: ``` Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms) ModelName Load (1.0ms) SELECT "model_name".* FROM "model_name" WHERE ("model_name"."attribute" = 14) ORDER BY '{:col1=>:desc, :col2=>:asc}' PG::SyntaxError: ERROR: non-integer constant in ORDER BY LINE 1: ...E ("model_name"."attribute" = 14) ORDER BY '{:col1=... ^ ``` Whereas this Rails code works without triggering the error message: ``` ModelName.where(:attribute => self.id).order("\"col1\" desc, \"col2\" asc") ``` I know that PostgreSQL is able to correctly interpret non-quoted identifiers, but the format of the query that ActiveRecord generates in this case appears to be ambiguous to Postgresql. Here's a description of PostgreSQL query syntax: <http://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html> Here's my development environment: * Windows 7 * Ruby 2.1.5p273 * Rails 3.0.3 (I know it's old...) * PostgreSQL 9.4 (on windows) ...and here's the pertinent part of my gem list: ``` *** LOCAL GEMS *** abstract (1.0.0) afm (0.2.2) arel (2.0.10) builder (2.1.2) bundler (1.7.7) hashery (2.1.1) i18n (0.6.11) mysql (2.9.1) pg (0.18.1 x86-mingw32) rack (1.2.8) rails (3.0.3) railties (3.0.3) rake (0.9.2.2) ruby-rc4 (0.1.5) sequel (3.31.0) valkyrie (0.0.2) ```
20,618,583
I have two JavaScript arrays. My first array looks like this: ``` teams: [ { id: 1, name:'Flyers' }, { id: 2, name:'Hawks' }, { id: 3, name:'Bats' }, { id: 4, name:'Ninjas' }, { id: 5, name:'Seals' } ]; selected: ["1", "3", "4"]; ``` How do I return an array of teams that have an ID in selected? I'm trying to do this with underscore.js Currently, I have: ``` var selected = _.filter(teams, function (team) { return _.contains(selected, team.id); }); ``` However, that's not working. What am I doing wrong?
2013/12/16
[ "https://Stackoverflow.com/questions/20618583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2871401/" ]
Since `team.id` is a number, it will never appear in an array of strings.
I would use a two step process for this. Using [`_.contains`](http://underscorejs.org/#contains) inside a loop is a bad habit and you can skip it by precomputing a simple lookup table using [`_.object`](http://underscorejs.org/#object): ``` var selected_has = _(selected).object(selected); ``` Since all the values in `selected` are truthy, we can say things like `if(select_has[id])` to see if `id` is in `selected`. ``` var matches = _(teams).filter(function(o) { return selected_has[o.id] }); ``` Of course, you pay a little bit for the type conversions but you gain expressiveness. Demo: <http://jsfiddle.net/ambiguous/b4XyU/>
53,525,975
I am trying to create a template for a Kubernetes cluster having 1 master and 2 worker nodes. I have installed all the pre-req software and have run the kubeadmn init on my master node. But when i try to run the kubeadmn join which i get as an output of the init command i am getting an error. > > > ```sh > [discovery] Created cluster-info discovery client, requesting info > from "https://10.31.2.33:6443" [discovery] Requesting info from > "https://10.31.2.33:6443" again to validate TLS against the pinned > public key [discovery] Cluster info signature and contents are valid > and TLS certificate validates against pinned roots, will use API > Server "10.31.2.33:6443" [discovery] Successfully established > connection with API Server "10.31.2.33:6443" [kubelet] Downloading > configuration for the kubelet from the "kubelet-config-1.12" ConfigMap > in the kube-system namespace [kubelet] Writing kubelet configuration > to file "/var/lib/kubelet/config.yaml" [kubelet] Writing kubelet > environment file with flags to file > "/var/lib/kubelet/kubeadm-flags.env" [preflight] Activating the > kubelet service [tlsbootstrap] Waiting for the kubelet to perform the > TLS Bootstrap... [patchnode] Uploading the CRI Socket information > "/var/run/dockershim.sock" to the Node API object "<workernode2>" as > an annotation error uploading crisocket: timed out waiting for the > condition``` > > ``` > > I have done a swapoff -a before running this on the workdernode2 I was able to run the join once but after that, as a part of a script, I ran the kubeadmn reset followed by init and join few times where this has started showing up. Not able to figure out what or where I am doing a mistake. My main intent is to put all the commands in the form of a shell script (on master node) so that it can be run on a cluster to create a network.
2018/11/28
[ "https://Stackoverflow.com/questions/53525975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10718697/" ]
I had the encountered the following issue after node was rebooted: ```sh [kubelet] Creating a ConfigMap "kubelet-config-1.13" in namespace kube-system with the configuration for the kubelets in the cluster [patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "k8smaster" as an annotation [kubelet-check] Initial timeout of 40s passed. error execution phase upload-config/kubelet: Error writing Crisocket information for the control-plane node: timed out waiting for the condition ``` Steps to get rid of this issue: 1. Check the hostname again, after reboot it might have changed. ```sh sudo vi /etc/hostname sudo vi /etc/hosts ``` 2. Perform the following clean-up actions Code: ```sh sudo kubeadm reset rm -rf /var/lib/cni/ sudo rm -rf /var/lib/cni/ systemctl daemon-reload systemctl restart kubelet sudo iptables -F && sudo iptables -t nat -F && sudo iptables -t mangle -F && sudo iptables -X ``` 3. Execute the init action with the special tag as below Code: ```sh sudo kubeadm init --pod-network-cidr=192.168.0.0/16 --apiserver-advertise-address=10.10.10.2 --ignore-preflight-errors=all ``` (where 10.10.10.2 is the IP of master node and 192.168.0.0/16 is the private subnet assigned for Pods)
I’ve had the same problem on Ubuntu 16.04 amd64, fixed it with these commands: ``` swapoff -a # will turn off the swap kubeadm reset systemctl daemon-reload systemctl restart kubelet iptables -F && iptables -t nat -F && iptables -t mangle -F && iptables -X # will reset iptables ``` Also, look at that issue in kubeadm GitHub [kubeadm swap on the related issue](https://github.com/kubernetes/kubeadm/issues/610) where people still report having the problem after turning swap off. You may also try to add *--fail-swap-on=false* flag in /etc/default/kubelet file, it didn't help in my case though. It seems to be fixed in the latest k8 version because after upgrading the cluster, I haven't experienced the issue.
67,093,632
I have an issue about submitting a form via ajax and open a modal Dialog after the ajax function is completed successfully. When I click a submitButton, the process cannot be completed. Where is the problem in an ajax method or anywhere? How can I fix it? Here is my form HTML part. ``` <form id="contactForm" role="form" class="php-email-form"> @Html.AntiForgeryToken() <div class="row"> <div class="col-md-6 form-group"> <input type="text" name="nameSurname" class="form-control" id="nameSurname" placeholder="Name Surname" required> </div> <div class="col-md-6 form-group mt-3 mt-md-0"> <input type="email" class="form-control" name="email" id="email" placeholder="Email" required> </div> </div> <div class="form-group mt-3"> <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required> </div> <div class="form-group mt-3"> <textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea> </div> <div class="my-3"></div> <div class="text-center"> <button type="submit" id="submitButton" data-bs-toggle="modal">Submit</button> <!-- data-bs-target="#modalDialog"--> </div> </form> ``` Here is my modal part. ``` <div class="modal fade" id="modalDialog" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> @ViewBag.Success </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Kapat</button> </div> </div> </div> </div> ``` Here is my javascript part. ``` <script type="text/javascript"> $(document).ready(function () { $("#submitButton").click(function () { var nameSurname = $("#nameSurname").val(); var email = $("#email").val(); var subject = $("#subject").val(); var message = $("#message").val(); var form = $('#contactForm'); var token = $('input[name="__RequestVerificationToken"]', form).val(); $.ajax({ url: '/Home/Contract/', data: { __RequestVerificationToken: token, nameSurname: nameSurname, email: email, subject: subject, message: message }, type: 'POST', success: function (data) { $("#modalDialog").show(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert('custom message. Error: ' + errorThrown); } }); }); }) </script> ``` Here is my Contract action in Home Controller ``` [HttpPost] [ValidateAntiForgeryToken] public ActionResult Contract(string nameSurname = null, string email = null, string subject = null, string message = null) { if (nameSurname != null && email != null) { SmtpClient smtpClient = new SmtpClient("smtp.gmail.com"); smtpClient.Port = 587; smtpClient.Credentials = new System.Net.NetworkCredential("gmail address", "gmail address password"); // smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.EnableSsl = true; MailMessage mail = new MailMessage(); mail.Subject = subject; mail.IsBodyHtml = true; mail.Body = message; //Setting From , To and CC mail.From = new MailAddress(email); mail.To.Add(new MailAddress("gmail address")); smtpClient.Send(mail); ViewBag.Success = "Success"; } else { ViewBag.Error = "Error"; } return View(); } ```
2021/04/14
[ "https://Stackoverflow.com/questions/67093632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5719229/" ]
To me this looks like a configuration issue somewhere. Without more information, it's difficult to find out the root cause of the issue. It could be that: * The table was not actually created. * The grants were not set up correctly. * The account may be different in PROD. * May have a different case in the table name, or a prefix, or a suffix. * you name it... A trick that can help you diagnose the issue can take que form of a query on the `information_schema`, ran from the application itself, to find out what the application is seeing. I have a few "extra" queries in my MyBatis mappers that look like: ``` <select id="searchTable" resultType="FoundTableVO"> select table_schema, table_name from information_schema.tables where lower(table_name) like '%equ_config%' </select> ``` The above query will list all the tables that look like your table, and the schema where they are located. A few queries like this one will shed light on the issue.
Make sure that the table equ\_config is in the schema public. If it's not, try this syntax using qweries with your table: "schema\_name.equ\_config"
2,716,910
I do a lot of JRuby on Rails apps, and we have a fair amount of Java .jar dependencies. These become quite annoying in textmate as it really muddies up my lib directory, and I never (obviously) need to actually open these files. Can someone tell me how I might hide .jar files from my file listing in Textmate??
2010/04/26
[ "https://Stackoverflow.com/questions/2716910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/74389/" ]
You need to modify File Pattern regex in : ``` TextMate-->Preferences-->Advanced-->FolderReferences ``` You just have to add `|\.(jar)` to your regex: ``` !(/\.(?!htaccess)[^/]*|\.(tmproj|o|pyc)|\.(jar)|/Icon\r|/svn-commit(\.[2-9])?\.tmp)$ ``` Have a look at [this](http://www.wil-linssen.com/musings/entry/getting-.hidden-files-to-appear-in-the-textmate-project-drawer/).
You can do this for a specific Textmate project too: 1. Save the project somewhere, for example in `myproject.tmproj`. 2. Make sure the project isn't open in Textmate (otherwise Textmate will overwrite your changes when you close the project) 3. Open up the `myproject.tmproj` file with a **different** text editor 4. Add a pattern for the files you want to ignore to the `<string>` value on the line immediately following the `regexFolderFilter` line. In this case you would add `|\.jar` just before the `)$</string>`. 5. Save the file. 6. Re-open the project in Textmate. You can also open the `.tmproj` file in step 3 with Textmate if you use the command line command `mate`, too.
8,103,664
I've a URL that its contents are also JavaScript codes, I want to get the contents of this URL via JavaScript something like to `file_get_contents()` in PHP and show them to the user using the `alert()` function.
2011/11/12
[ "https://Stackoverflow.com/questions/8103664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1020526/" ]
You can use XMLHttpRequest in Javascript to fetch datas from an external URL. Here is a good resource : <http://www.w3schools.com/ajax/default.asp> (I usually don't recommend them, but the AJAX tutorial is really good). Also, this had to be there : ![jQuery ownz](https://i.stack.imgur.com/ERoHj.png)
you can get the contents from that URL by using jQuery ``` $.get('website_url', function(data) { alert(data); }); ```
45,619,873
The layout of my form is three columns: the first the label, the second for the input, and the third for the units (cm, kg etc.). Everything has been given inside a table in the form. But the first column takes more more (horizontal) space than it should. It has no padding, margin nor border. Here's my code: ```css body { font-family: 'Source Sans Pro', sans-serif; font-size: 14px; color: #222222; } table { width: 100%; white-space: nowrap; } input { background-color: #DACBDF; padding: 8px 10px 8px 10px; width: 91.5%; font-family: Georgia; font-size: 13px; border: 1px solid #EEEEEE; } input:hover { border: 1px solid green; } input:focus { background-color: #DACBFF; border: 1px solid #FF0000; } input[type="submit"] { font: 13px "Lucida Sans Unicode", "Lucida Grande", sans-serif; padding: 8px 15px 8px 15px; width: auto; border: 1px solid #EEEEEE; color: #222222; } input[type="submit"]:hover { background: #4691A4; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none; } #wgCalc, #hsCalc, #bfCalc, #ccCalc, #apCalc { height: 33px; width: 16.5%; z-index: 2; float: left; margin-left: 8px; } #container { background-color: #EEEEEE; padding: 10px 10px 10px 10px; border: 3px solid #888888; width: 30%; z-index: 1; margin: 0px auto; } #container h3 { text-align: center; } .menu { width: 30%; height: 35px; margin: 60px auto; margin-bottom: 0px; } .tabOn { background-color: #EEEEEE; border-bottom: 3px solid #EEEEEE !important; border: 2px solid blue; font-weight: bold; text-align: center; } .tabOff { background-color: #BBBBBB; border-bottom: 3px solid #888888 !important; border: 2px solid navy; text-align: center; } .tabOff a { color: #4422FF; text-decoration: none; } .tabOff a:hover { color: #4691A4; } .image-holder { width: 40%; margin: 0px auto; } .warning { font-weight: bold; color: #FF0000; } .result { font-weight: bold; } ``` ```html <!DOCTYPE HTML> <html> <head> <title>Body Fat Calculator</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro"> <link rel="stylesheet" type="text/css" href="main.css" /> <script type="text/javascript" src="fcalc.js"></script> </head> <body> <div class="menu"> <div id="wgCalc" class="tabOff"><a href="weightGoal.html">Weight Goal</a></div> <div id="hsCalc" class="tabOff"><a href="howSexy.html">How Sexy</a></div> <div id="bfCalc" class="tabOn">Body Fat</div> <div id="ccCalc" class="tabOff"><a href="circExp.html">Circ. Expect.</a></div> <div id="apCalc" class="tabOff"><a href="absPower.html">Absolute Power</a></div> </div> <div id="container"> <div class="image-holder"> <img src="EnData.png" width="100%" /> </div> <h3>BODY FAT CALCULATOR</h3> <form id="bodyFatCalc" name="bodyFatCalc" method="post" autocomplete="off" onSubmit="formData(); return false;"> <table> <tr> <td><label>Height:</label></td> <td><input type="text" id="height" name="height" value="" maxlength="5" /></td> <td>cm</td> </tr><tr> <td><label>Navel:</label></td> <td><input type="text" id="navel" name="navel" value="" maxlength="5" /></td> <td>cm</td> </tr><tr> <td><label>Neck:</label></td> <td><input type="text" id="neck" name="neck" value="" maxlength="4" /></td> <td>cm</td> </tr><tr> <td><label>Weight:</label></td> <td><input type="text" id="weight" name="weight" value="" maxlength="4" /></td> <td>kg</td> </tr><tr> <td></td> <td><input type="submit" id="calculate" name="calculate" value="Calculate" /></td> <td></td> </tr> </table> </form> <p id="warning" class="warning"></p> <p id="result_p" class="result"></p> <p id ="result_w" class="result"></p> </div></body> </html> ``` Can you please help me find out why? BTW, I tried giving `td {width: auto}` but it only worsened the case. UPDATE: It seems my question is not clear and concise enough. What I want is that `td` tags to take the width of whatever is inside them...
2017/08/10
[ "https://Stackoverflow.com/questions/45619873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you add `border-collapse: collapse;` to `table`, that helps a little bit...: ```css body { font-family: 'Source Sans Pro', sans-serif; font-size: 14px; color: #222222; } table { width: 100%; white-space: nowrap; border-collapse: collapse; } input { background-color: #DACBDF; padding: 8px 10px 8px 10px; width: 91.5%; font-family: Georgia; font-size: 13px; border: 1px solid #EEEEEE; } input:hover { border: 1px solid green; } input:focus { background-color: #DACBFF; border: 1px solid #FF0000; } input[type="submit"] { font: 13px "Lucida Sans Unicode", "Lucida Grande", sans-serif; padding: 8px 15px 8px 15px; width: auto; border: 1px solid #EEEEEE; color: #222222; } input[type="submit"]:hover { background: #4691A4; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none; } #wgCalc, #hsCalc, #bfCalc, #ccCalc, #apCalc { height: 33px; width: 16.5%; z-index: 2; float: left; margin-left: 8px; } #container { background-color: #EEEEEE; padding: 10px 10px 10px 10px; border: 3px solid #888888; width: 30%; z-index: 1; margin: 0px auto; } #container h3 { text-align: center; } .menu { width: 30%; height: 35px; margin: 60px auto; margin-bottom: 0px; } .tabOn { background-color: #EEEEEE; border-bottom: 3px solid #EEEEEE !important; border: 2px solid blue; font-weight: bold; text-align: center; } .tabOff { background-color: #BBBBBB; border-bottom: 3px solid #888888 !important; border: 2px solid navy; text-align: center; } .tabOff a { color: #4422FF; text-decoration: none; } .tabOff a:hover { color: #4691A4; } .image-holder { width: 40%; margin: 0px auto; } .warning { font-weight: bold; color: #FF0000; } .result { font-weight: bold; } ``` ```html <!DOCTYPE HTML> <html> <head> <title>Body Fat Calculator</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro"> <link rel="stylesheet" type="text/css" href="main.css" /> <script type="text/javascript" src="fcalc.js"></script> </head> <body> <div class="menu"> <div id="wgCalc" class="tabOff"><a href="weightGoal.html">Weight Goal</a></div> <div id="hsCalc" class="tabOff"><a href="howSexy.html">How Sexy</a></div> <div id="bfCalc" class="tabOn">Body Fat</div> <div id="ccCalc" class="tabOff"><a href="circExp.html">Circ. Expect.</a></div> <div id="apCalc" class="tabOff"><a href="absPower.html">Absolute Power</a></div> </div> <div id="container"> <div class="image-holder"> <img src="EnData.png" width="100%" /> </div> <h3>BODY FAT CALCULATOR</h3> <form id="bodyFatCalc" name="bodyFatCalc" method="post" autocomplete="off" onSubmit="formData(); return false;"> <table> <tr> <td><label>Height:</label></td> <td><input type="text" id="height" name="height" value="" maxlength="5" /></td> <td>cm</td> </tr><tr> <td><label>Navel:</label></td> <td><input type="text" id="navel" name="navel" value="" maxlength="5" /></td> <td>cm</td> </tr><tr> <td><label>Neck:</label></td> <td><input type="text" id="neck" name="neck" value="" maxlength="4" /></td> <td>cm</td> </tr><tr> <td><label>Weight:</label></td> <td><input type="text" id="weight" name="weight" value="" maxlength="4" /></td> <td>kg</td> </tr><tr> <td></td> <td><input type="submit" id="calculate" name="calculate" value="Calculate" /></td> <td></td> </tr> </table> </form> <p id="warning" class="warning"></p> <p id="result_p" class="result"></p> <p id ="result_w" class="result"></p> </div></body> </html> ```
``` table{table-layout: fixed;} td:first-of-type{width: your-width;} ```
45,619,873
The layout of my form is three columns: the first the label, the second for the input, and the third for the units (cm, kg etc.). Everything has been given inside a table in the form. But the first column takes more more (horizontal) space than it should. It has no padding, margin nor border. Here's my code: ```css body { font-family: 'Source Sans Pro', sans-serif; font-size: 14px; color: #222222; } table { width: 100%; white-space: nowrap; } input { background-color: #DACBDF; padding: 8px 10px 8px 10px; width: 91.5%; font-family: Georgia; font-size: 13px; border: 1px solid #EEEEEE; } input:hover { border: 1px solid green; } input:focus { background-color: #DACBFF; border: 1px solid #FF0000; } input[type="submit"] { font: 13px "Lucida Sans Unicode", "Lucida Grande", sans-serif; padding: 8px 15px 8px 15px; width: auto; border: 1px solid #EEEEEE; color: #222222; } input[type="submit"]:hover { background: #4691A4; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none; } #wgCalc, #hsCalc, #bfCalc, #ccCalc, #apCalc { height: 33px; width: 16.5%; z-index: 2; float: left; margin-left: 8px; } #container { background-color: #EEEEEE; padding: 10px 10px 10px 10px; border: 3px solid #888888; width: 30%; z-index: 1; margin: 0px auto; } #container h3 { text-align: center; } .menu { width: 30%; height: 35px; margin: 60px auto; margin-bottom: 0px; } .tabOn { background-color: #EEEEEE; border-bottom: 3px solid #EEEEEE !important; border: 2px solid blue; font-weight: bold; text-align: center; } .tabOff { background-color: #BBBBBB; border-bottom: 3px solid #888888 !important; border: 2px solid navy; text-align: center; } .tabOff a { color: #4422FF; text-decoration: none; } .tabOff a:hover { color: #4691A4; } .image-holder { width: 40%; margin: 0px auto; } .warning { font-weight: bold; color: #FF0000; } .result { font-weight: bold; } ``` ```html <!DOCTYPE HTML> <html> <head> <title>Body Fat Calculator</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro"> <link rel="stylesheet" type="text/css" href="main.css" /> <script type="text/javascript" src="fcalc.js"></script> </head> <body> <div class="menu"> <div id="wgCalc" class="tabOff"><a href="weightGoal.html">Weight Goal</a></div> <div id="hsCalc" class="tabOff"><a href="howSexy.html">How Sexy</a></div> <div id="bfCalc" class="tabOn">Body Fat</div> <div id="ccCalc" class="tabOff"><a href="circExp.html">Circ. Expect.</a></div> <div id="apCalc" class="tabOff"><a href="absPower.html">Absolute Power</a></div> </div> <div id="container"> <div class="image-holder"> <img src="EnData.png" width="100%" /> </div> <h3>BODY FAT CALCULATOR</h3> <form id="bodyFatCalc" name="bodyFatCalc" method="post" autocomplete="off" onSubmit="formData(); return false;"> <table> <tr> <td><label>Height:</label></td> <td><input type="text" id="height" name="height" value="" maxlength="5" /></td> <td>cm</td> </tr><tr> <td><label>Navel:</label></td> <td><input type="text" id="navel" name="navel" value="" maxlength="5" /></td> <td>cm</td> </tr><tr> <td><label>Neck:</label></td> <td><input type="text" id="neck" name="neck" value="" maxlength="4" /></td> <td>cm</td> </tr><tr> <td><label>Weight:</label></td> <td><input type="text" id="weight" name="weight" value="" maxlength="4" /></td> <td>kg</td> </tr><tr> <td></td> <td><input type="submit" id="calculate" name="calculate" value="Calculate" /></td> <td></td> </tr> </table> </form> <p id="warning" class="warning"></p> <p id="result_p" class="result"></p> <p id ="result_w" class="result"></p> </div></body> </html> ``` Can you please help me find out why? BTW, I tried giving `td {width: auto}` but it only worsened the case. UPDATE: It seems my question is not clear and concise enough. What I want is that `td` tags to take the width of whatever is inside them...
2017/08/10
[ "https://Stackoverflow.com/questions/45619873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What you are asking for is not possible. If your table is set to have a `width:100%` then the `td`s will widen-up to take up the space available so that the table is using its prescribed width. What you might have to do is define which columns need to have a variable width and which ones will be static. (you cannot have it both ways) Something along the lines of: ``` tr > td:last-of-type, tr > td:first-of-type { width: 50px !important; /* adjust width as necessary to fit longest word */ } /* changed this to 'input' */ input{ width: 95%; /* other properties */ } ``` I reduced your given code to a [MCVE](https://stackoverflow.com/help/mcve). **See running demo:** ```css table { width: 100%; white-space: nowrap; } input { background-color: #DACBDF; padding: 8px 10px 8px 10px; width: 95%; font-family: Georgia; font-size: 13px; border: 1px solid #EEEEEE; } input:hover { border: 1px solid green; } input:focus { background-color: #DACBFF; border: 1px solid #FF0000; } input[type="submit"] { font: 13px "Lucida Sans Unicode", "Lucida Grande", sans-serif; padding: 8px 15px 8px 15px; width: auto; border: 1px solid #EEEEEE; color: #222222; } input[type="submit"]:hover { background: #4691A4; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none; } tr > td:last-of-type, tr > td:first-of-type { width: 50px !important; /* adjust width as necessary to fit longest word */ } ``` ```html <table> <tr> <td><label>Height:</label></td> <td><input type="text" id="height" name="height" value="" maxlength="5" /></td> <td>cm</td> </tr> <tr> <td><label>Navel:</label></td> <td><input type="text" id="navel" name="navel" value="" maxlength="5" /></td> <td>cm</td> </tr> <tr> <td><label>Neck:</label></td> <td><input type="text" id="neck" name="neck" value="" maxlength="4" /></td> <td>cm</td> </tr> <tr> <td><label>Weight:</label></td> <td><input type="text" id="weight" name="weight" value="" maxlength="4" /></td> <td>kg</td> </tr> <tr> <td></td> <td><input type="submit" id="calculate" name="calculate" value="Calculate" /></td> <td></td> </tr> </table> ```
``` table{table-layout: fixed;} td:first-of-type{width: your-width;} ```
45,619,873
The layout of my form is three columns: the first the label, the second for the input, and the third for the units (cm, kg etc.). Everything has been given inside a table in the form. But the first column takes more more (horizontal) space than it should. It has no padding, margin nor border. Here's my code: ```css body { font-family: 'Source Sans Pro', sans-serif; font-size: 14px; color: #222222; } table { width: 100%; white-space: nowrap; } input { background-color: #DACBDF; padding: 8px 10px 8px 10px; width: 91.5%; font-family: Georgia; font-size: 13px; border: 1px solid #EEEEEE; } input:hover { border: 1px solid green; } input:focus { background-color: #DACBFF; border: 1px solid #FF0000; } input[type="submit"] { font: 13px "Lucida Sans Unicode", "Lucida Grande", sans-serif; padding: 8px 15px 8px 15px; width: auto; border: 1px solid #EEEEEE; color: #222222; } input[type="submit"]:hover { background: #4691A4; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none; } #wgCalc, #hsCalc, #bfCalc, #ccCalc, #apCalc { height: 33px; width: 16.5%; z-index: 2; float: left; margin-left: 8px; } #container { background-color: #EEEEEE; padding: 10px 10px 10px 10px; border: 3px solid #888888; width: 30%; z-index: 1; margin: 0px auto; } #container h3 { text-align: center; } .menu { width: 30%; height: 35px; margin: 60px auto; margin-bottom: 0px; } .tabOn { background-color: #EEEEEE; border-bottom: 3px solid #EEEEEE !important; border: 2px solid blue; font-weight: bold; text-align: center; } .tabOff { background-color: #BBBBBB; border-bottom: 3px solid #888888 !important; border: 2px solid navy; text-align: center; } .tabOff a { color: #4422FF; text-decoration: none; } .tabOff a:hover { color: #4691A4; } .image-holder { width: 40%; margin: 0px auto; } .warning { font-weight: bold; color: #FF0000; } .result { font-weight: bold; } ``` ```html <!DOCTYPE HTML> <html> <head> <title>Body Fat Calculator</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro"> <link rel="stylesheet" type="text/css" href="main.css" /> <script type="text/javascript" src="fcalc.js"></script> </head> <body> <div class="menu"> <div id="wgCalc" class="tabOff"><a href="weightGoal.html">Weight Goal</a></div> <div id="hsCalc" class="tabOff"><a href="howSexy.html">How Sexy</a></div> <div id="bfCalc" class="tabOn">Body Fat</div> <div id="ccCalc" class="tabOff"><a href="circExp.html">Circ. Expect.</a></div> <div id="apCalc" class="tabOff"><a href="absPower.html">Absolute Power</a></div> </div> <div id="container"> <div class="image-holder"> <img src="EnData.png" width="100%" /> </div> <h3>BODY FAT CALCULATOR</h3> <form id="bodyFatCalc" name="bodyFatCalc" method="post" autocomplete="off" onSubmit="formData(); return false;"> <table> <tr> <td><label>Height:</label></td> <td><input type="text" id="height" name="height" value="" maxlength="5" /></td> <td>cm</td> </tr><tr> <td><label>Navel:</label></td> <td><input type="text" id="navel" name="navel" value="" maxlength="5" /></td> <td>cm</td> </tr><tr> <td><label>Neck:</label></td> <td><input type="text" id="neck" name="neck" value="" maxlength="4" /></td> <td>cm</td> </tr><tr> <td><label>Weight:</label></td> <td><input type="text" id="weight" name="weight" value="" maxlength="4" /></td> <td>kg</td> </tr><tr> <td></td> <td><input type="submit" id="calculate" name="calculate" value="Calculate" /></td> <td></td> </tr> </table> </form> <p id="warning" class="warning"></p> <p id="result_p" class="result"></p> <p id ="result_w" class="result"></p> </div></body> </html> ``` Can you please help me find out why? BTW, I tried giving `td {width: auto}` but it only worsened the case. UPDATE: It seems my question is not clear and concise enough. What I want is that `td` tags to take the width of whatever is inside them...
2017/08/10
[ "https://Stackoverflow.com/questions/45619873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What you are asking for is not possible. If your table is set to have a `width:100%` then the `td`s will widen-up to take up the space available so that the table is using its prescribed width. What you might have to do is define which columns need to have a variable width and which ones will be static. (you cannot have it both ways) Something along the lines of: ``` tr > td:last-of-type, tr > td:first-of-type { width: 50px !important; /* adjust width as necessary to fit longest word */ } /* changed this to 'input' */ input{ width: 95%; /* other properties */ } ``` I reduced your given code to a [MCVE](https://stackoverflow.com/help/mcve). **See running demo:** ```css table { width: 100%; white-space: nowrap; } input { background-color: #DACBDF; padding: 8px 10px 8px 10px; width: 95%; font-family: Georgia; font-size: 13px; border: 1px solid #EEEEEE; } input:hover { border: 1px solid green; } input:focus { background-color: #DACBFF; border: 1px solid #FF0000; } input[type="submit"] { font: 13px "Lucida Sans Unicode", "Lucida Grande", sans-serif; padding: 8px 15px 8px 15px; width: auto; border: 1px solid #EEEEEE; color: #222222; } input[type="submit"]:hover { background: #4691A4; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none; } tr > td:last-of-type, tr > td:first-of-type { width: 50px !important; /* adjust width as necessary to fit longest word */ } ``` ```html <table> <tr> <td><label>Height:</label></td> <td><input type="text" id="height" name="height" value="" maxlength="5" /></td> <td>cm</td> </tr> <tr> <td><label>Navel:</label></td> <td><input type="text" id="navel" name="navel" value="" maxlength="5" /></td> <td>cm</td> </tr> <tr> <td><label>Neck:</label></td> <td><input type="text" id="neck" name="neck" value="" maxlength="4" /></td> <td>cm</td> </tr> <tr> <td><label>Weight:</label></td> <td><input type="text" id="weight" name="weight" value="" maxlength="4" /></td> <td>kg</td> </tr> <tr> <td></td> <td><input type="submit" id="calculate" name="calculate" value="Calculate" /></td> <td></td> </tr> </table> ```
If you add `border-collapse: collapse;` to `table`, that helps a little bit...: ```css body { font-family: 'Source Sans Pro', sans-serif; font-size: 14px; color: #222222; } table { width: 100%; white-space: nowrap; border-collapse: collapse; } input { background-color: #DACBDF; padding: 8px 10px 8px 10px; width: 91.5%; font-family: Georgia; font-size: 13px; border: 1px solid #EEEEEE; } input:hover { border: 1px solid green; } input:focus { background-color: #DACBFF; border: 1px solid #FF0000; } input[type="submit"] { font: 13px "Lucida Sans Unicode", "Lucida Grande", sans-serif; padding: 8px 15px 8px 15px; width: auto; border: 1px solid #EEEEEE; color: #222222; } input[type="submit"]:hover { background: #4691A4; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none; } #wgCalc, #hsCalc, #bfCalc, #ccCalc, #apCalc { height: 33px; width: 16.5%; z-index: 2; float: left; margin-left: 8px; } #container { background-color: #EEEEEE; padding: 10px 10px 10px 10px; border: 3px solid #888888; width: 30%; z-index: 1; margin: 0px auto; } #container h3 { text-align: center; } .menu { width: 30%; height: 35px; margin: 60px auto; margin-bottom: 0px; } .tabOn { background-color: #EEEEEE; border-bottom: 3px solid #EEEEEE !important; border: 2px solid blue; font-weight: bold; text-align: center; } .tabOff { background-color: #BBBBBB; border-bottom: 3px solid #888888 !important; border: 2px solid navy; text-align: center; } .tabOff a { color: #4422FF; text-decoration: none; } .tabOff a:hover { color: #4691A4; } .image-holder { width: 40%; margin: 0px auto; } .warning { font-weight: bold; color: #FF0000; } .result { font-weight: bold; } ``` ```html <!DOCTYPE HTML> <html> <head> <title>Body Fat Calculator</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro"> <link rel="stylesheet" type="text/css" href="main.css" /> <script type="text/javascript" src="fcalc.js"></script> </head> <body> <div class="menu"> <div id="wgCalc" class="tabOff"><a href="weightGoal.html">Weight Goal</a></div> <div id="hsCalc" class="tabOff"><a href="howSexy.html">How Sexy</a></div> <div id="bfCalc" class="tabOn">Body Fat</div> <div id="ccCalc" class="tabOff"><a href="circExp.html">Circ. Expect.</a></div> <div id="apCalc" class="tabOff"><a href="absPower.html">Absolute Power</a></div> </div> <div id="container"> <div class="image-holder"> <img src="EnData.png" width="100%" /> </div> <h3>BODY FAT CALCULATOR</h3> <form id="bodyFatCalc" name="bodyFatCalc" method="post" autocomplete="off" onSubmit="formData(); return false;"> <table> <tr> <td><label>Height:</label></td> <td><input type="text" id="height" name="height" value="" maxlength="5" /></td> <td>cm</td> </tr><tr> <td><label>Navel:</label></td> <td><input type="text" id="navel" name="navel" value="" maxlength="5" /></td> <td>cm</td> </tr><tr> <td><label>Neck:</label></td> <td><input type="text" id="neck" name="neck" value="" maxlength="4" /></td> <td>cm</td> </tr><tr> <td><label>Weight:</label></td> <td><input type="text" id="weight" name="weight" value="" maxlength="4" /></td> <td>kg</td> </tr><tr> <td></td> <td><input type="submit" id="calculate" name="calculate" value="Calculate" /></td> <td></td> </tr> </table> </form> <p id="warning" class="warning"></p> <p id="result_p" class="result"></p> <p id ="result_w" class="result"></p> </div></body> </html> ```
39,267,732
I need to retrieve the entire single object hierarchy from the database as a JSON. I decided to use MongoDB with its `$lookup` support. So I have three collections: **1. Restaurants** ``` { "_id" : ObjectId("57c6a02021c8b8d04443aa7c"), "name" : "KFC", "city" : "Lahore", "area" : "Johar town", "min_order" : "500", "del_time" : "1 hour", "del_fees" : "5", "pre_order" : "no", "rating_star" : "0", "rating_no" : 0, "status" : "1", "working_hours" : { "monday" : "2pm 6am", "tuesday" : "6am 8pm", "wednesday" : "9pm 5pm", "thursday" : "3pm 6pm", "friday" : "1pm 9pm", "saturday" : "4pm 5pm", "sunday" : "4pm 8pm" }, "cuisines" : [ "fast food, pizza" ], "payments" : [ "cash,credit card,paypal" ] } ``` **2. categories** ``` "categories" : [ { "_id" : ObjectId("57c6a05421c8b8d04443aa7e"), "restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"), "name" : "Breakfast", "category_id" : "1", "__v" : 0 }, { "_id" : ObjectId("57c6a06021c8b8d04443aa7f"), "restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"), "name" : "Special", "category_id" : "2", "__v" : 0 } ] ``` **3. items** ``` "items" : [ { "_id" : ObjectId("57c6da8cc8d053e8310dfe65"), "restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"), "category_id" : ObjectId("57c6a05421c8b8d04443aa7e"), "name" : "Water", "price" : "55", "rating" : "0", "__v" : 0 }, { "_id" : ObjectId("57c6da96c8d053e8310dfe66"), "restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"), "category_id" : ObjectId("57c6a05421c8b8d04443aa7e"), "name" : "Milk", "price" : "55", "rating" : "0", "__v" : 0 } ] ``` I want an output in Json response like this ``` { "_id" : ObjectId("57c6a02021c8b8d04443aa7c"), "name" : "KFC", "city" : "Lahore", "area" : "Johar town", "min_order" : "500", "del_time" : "1 hour", "del_fees" : "5", "pre_order" : "no", "rating_star" : "0", "rating_no" : 0, "status" : "1", "working_hours" : { "monday" : "2pm 6am", "tuesday" : "6am 8pm", "wednesday" : "9pm 5pm", "thursday" : "3pm 6pm", "friday" : "1pm 9pm", "saturday" : "4pm 5pm", "sunday" : "4pm 8pm" }, "cuisines" : [ "fast food, pizza" ], "payments" : [ "cash,credit card,paypal" ], "__v" : 0, "categories" : [{ "_id" : ObjectId("57c6a05421c8b8d04443aa7e"), "restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"), "name" : "Breakfast", "category_id" : "1", "__v" : 0, "items" : [ { "_id" : ObjectId("57c6da8cc8d053e8310dfe65"), "restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"), "category_id" : ObjectId("57c6a05421c8b8d04443aa7e"), "name" : "Water", "price" : "55", "rating" : "0", "__v" : 0 }, { "_id" : ObjectId("57c6da96c8d053e8310dfe66"), "restaurant_id" : ObjectId("57c6a02021c8b8d04443aa7c"), "category_id" : ObjectId("57c6a05421c8b8d04443aa7e"), "name" : "Milk", "price" : "55", "rating" : "0", "__v" : 0 } ] }] } ``` Still, I'm doing like this ``` db.restaurants.aggregate([{ $lookup: { from: "categories", localField: "_id", foreignField: "restaurant_id", as: "categories" } }]) ``` It's working fine for `Restaurants` and `categories` but how I do it for each categories item that I have in `categories`?
2016/09/01
[ "https://Stackoverflow.com/questions/39267732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5006101/" ]
This approach works for the simple example given, but fails if the name has more than 2 uppercase letters in it. If this is coursework as expected, maybe the requirements are not too difficult for the names to parse as we all know that is fraught with heartache and you can never account for 100% of names from all nationalities. Anyway my approach was to move through the string looking for uppercase letters and if found replace them with a space followed by the letter. I used the ASCII function to test their ascii value to see if they were an uppercase character. The CONNECT BY construct (needed to loop through each character of the string) returns each character in its own row so LISTAGG() was employed to reassemble back into a string and ltrim to remove the leading space. I suspect if this is coursework it may be using some features you should not be using yet. At least you should get out of this the importance of receiving and/or giving complete specifications! ``` SQL> with tbl(name) as ( select 'MarkJones' from dual ) select ltrim(listagg(case when ascii(substr(name, level, 1)) >= 65 AND ascii(substr(name, level, 1)) <= 90 THEN ' ' || substr(name, level, 1) else substr(name, level, 1) end, '') within group (order by level)) fixed from tbl connect by level <= length(name); FIXED ------------------------------------ Mark Jones ``` When you are ready, here's the regexp\_replace version anyway :-) Find and "remember" the 2nd occurrence of an uppercase character then replace it with a space and the "remembered" uppercase character. ``` SQL> with tbl(name) as ( select 'MarkJones' from dual ) select regexp_replace(name, '([A-Z])', ' \1', 1, 2) fixed from tbl; FIXED ---------- Mark Jones ```
Not sure we should go against @Alex Poole advice, but it looks like an homework assignment. So my idea is to point the second Upper Case. Its doable if you create a set of the upper cases, on which you valuate the position in input string `iStr`. Then if you're allowed to use `length`, you can use this position to build `firstName` too: ``` SELECT substr(iStr, 1, length(iStr)-length(substr(iStr, instr(iStr, u)))) firstName , substr(iStr, instr(iStr, u)) lastName , substr(iStr, 1, length(iStr)-length(substr(iStr, instr(iStr, u)))) ||' '|| substr(iStr, instr(iStr, u)) BINGO FROM ( select 'MarkJones' iStr from dual union all select 'SomeOtherNames' from dual -- 2 u-cases gives 2 different results union all select 'SomeOtherOols' from dual -- only one result union all select 'AndJim' from dual union all select 'JohnLenon' from dual union all select 'LemingWay' from dual ), ( select 'A' U from dual union all select 'B' from dual union all select 'C' from dual union all select 'D' from dual union all select 'E' from dual union all select 'F' from dual union all select 'G' from dual union all select 'H' from dual union all select 'I' from dual union all select 'J' from dual union all select 'K' from dual union all select 'L' from dual union all select 'M' from dual union all select 'N' from dual union all select 'O' from dual union all select 'P' from dual union all select 'Q' from dual union all select 'R' from dual union all select 'S' from dual union all select 'T' from dual union all select 'U' from dual union all select 'V' from dual union all select 'W' from dual union all select 'X' from dual union all select 'Y' from dual union all select 'Z' from dual ) upper_cases where instr(iStr, U) > 1 ; ```
36,083,156
I have the following ASP Repeater in a table: ``` <asp:Repeater ID="rptPage" runat="server" OnItemCommand="rptPage_ItemCommand" OnItemDataBound="rptPage_ItemDataBound"> <ItemTemplate> <tr> <td id="ArticleTitle"> <%# DataBinder.Eval(Container.DataItem,"Title") %> </td> <td> <%# DataBinder.Eval(Container.DataItem,"AuthorName") %> </td> <td> <asp:Button ID="EditButton" runat="server" CommandName="edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Edit" /> </td> <td> <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete(this)" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> </td> <td> <a href="<%# String.Format("/news/Article={0}", processTitle(Eval("Title"))) %>">View Here</a> </td> </tr> </ItemTemplate> </asp:Repeater> ``` This all works fine. There is a confirm button on the delete function, using the following method: ``` function fnConfirmDelete(ArticleTitle) { return confirm("Delete Article " + ArticleTitle); } ``` Now, what I want to do is pass the text from this: ``` <%# DataBinder.Eval(Container.DataItem,"Title") %> ``` into the confirm box. I have tried adding a 'name' field: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete(this)" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" name='<%# DataBinder.Eval(Container.DataItem,"Title") %>'/> ``` But this does not display the text in the name field, but some kind of server side change. I have also tried passing the value into the JavaScript function: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete('<%# DataBinder.Eval(Container.DataItem,"Title") %>')" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> ``` But this says the server tag is not well formed. I have also tried to pass in an id from the cell that has the value, but again server tag is not well formed. Does anyone know how I can achieve this? Also, once I get it to the JavaScript function, how would I retrieve the value? EDIT: I tried: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete('"<%# DataBinder.Eval(Container.DataItem,"Title") %>"')" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> ``` as suggested by @Reddy below, but it also gave a server tag not well formed error.
2016/03/18
[ "https://Stackoverflow.com/questions/36083156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4436077/" ]
1. Rectify your **Root** section with proper **Tag** **Finally** ``` xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" ``` Then **Clean-Rebuild-Sync** . ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <item android:icon="@drawable/ic_camera_iris_white_36dp" android:id="@+id/video_camera" app:showAsAction="always" android:title="@string/menu_camera_label"></item> </menu> ```
``` <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.sixmod.MainActivity"> <item android:id="@+id/action_settings" android:orderInCategory="100" android:title="@string/action_settings" app:showAsAction="never" /> <item android:id="@+id/title" android:orderInCategory="100" android:title="@string/titlename" app:showAsAction="always" /> <item android:id="@+id/video_camera" android:icon="@drawable/ic_camera_iris_white_36dp" android:showAsAction="always" android:title="@string/menu_camera_label"/> </menu> ```
36,083,156
I have the following ASP Repeater in a table: ``` <asp:Repeater ID="rptPage" runat="server" OnItemCommand="rptPage_ItemCommand" OnItemDataBound="rptPage_ItemDataBound"> <ItemTemplate> <tr> <td id="ArticleTitle"> <%# DataBinder.Eval(Container.DataItem,"Title") %> </td> <td> <%# DataBinder.Eval(Container.DataItem,"AuthorName") %> </td> <td> <asp:Button ID="EditButton" runat="server" CommandName="edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Edit" /> </td> <td> <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete(this)" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> </td> <td> <a href="<%# String.Format("/news/Article={0}", processTitle(Eval("Title"))) %>">View Here</a> </td> </tr> </ItemTemplate> </asp:Repeater> ``` This all works fine. There is a confirm button on the delete function, using the following method: ``` function fnConfirmDelete(ArticleTitle) { return confirm("Delete Article " + ArticleTitle); } ``` Now, what I want to do is pass the text from this: ``` <%# DataBinder.Eval(Container.DataItem,"Title") %> ``` into the confirm box. I have tried adding a 'name' field: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete(this)" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" name='<%# DataBinder.Eval(Container.DataItem,"Title") %>'/> ``` But this does not display the text in the name field, but some kind of server side change. I have also tried passing the value into the JavaScript function: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete('<%# DataBinder.Eval(Container.DataItem,"Title") %>')" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> ``` But this says the server tag is not well formed. I have also tried to pass in an id from the cell that has the value, but again server tag is not well formed. Does anyone know how I can achieve this? Also, once I get it to the JavaScript function, how would I retrieve the value? EDIT: I tried: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete('"<%# DataBinder.Eval(Container.DataItem,"Title") %>"')" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> ``` as suggested by @Reddy below, but it also gave a server tag not well formed error.
2016/03/18
[ "https://Stackoverflow.com/questions/36083156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4436077/" ]
1. Rectify your **Root** section with proper **Tag** **Finally** ``` xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" ``` Then **Clean-Rebuild-Sync** . ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <item android:icon="@drawable/ic_camera_iris_white_36dp" android:id="@+id/video_camera" app:showAsAction="always" android:title="@string/menu_camera_label"></item> </menu> ```
Resolved such issue with the following code: ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/tools" xmlns:android1="http://schemas.android.com/apk/res/android"> ```
36,083,156
I have the following ASP Repeater in a table: ``` <asp:Repeater ID="rptPage" runat="server" OnItemCommand="rptPage_ItemCommand" OnItemDataBound="rptPage_ItemDataBound"> <ItemTemplate> <tr> <td id="ArticleTitle"> <%# DataBinder.Eval(Container.DataItem,"Title") %> </td> <td> <%# DataBinder.Eval(Container.DataItem,"AuthorName") %> </td> <td> <asp:Button ID="EditButton" runat="server" CommandName="edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Edit" /> </td> <td> <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete(this)" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> </td> <td> <a href="<%# String.Format("/news/Article={0}", processTitle(Eval("Title"))) %>">View Here</a> </td> </tr> </ItemTemplate> </asp:Repeater> ``` This all works fine. There is a confirm button on the delete function, using the following method: ``` function fnConfirmDelete(ArticleTitle) { return confirm("Delete Article " + ArticleTitle); } ``` Now, what I want to do is pass the text from this: ``` <%# DataBinder.Eval(Container.DataItem,"Title") %> ``` into the confirm box. I have tried adding a 'name' field: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete(this)" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" name='<%# DataBinder.Eval(Container.DataItem,"Title") %>'/> ``` But this does not display the text in the name field, but some kind of server side change. I have also tried passing the value into the JavaScript function: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete('<%# DataBinder.Eval(Container.DataItem,"Title") %>')" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> ``` But this says the server tag is not well formed. I have also tried to pass in an id from the cell that has the value, but again server tag is not well formed. Does anyone know how I can achieve this? Also, once I get it to the JavaScript function, how would I retrieve the value? EDIT: I tried: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete('"<%# DataBinder.Eval(Container.DataItem,"Title") %>"')" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> ``` as suggested by @Reddy below, but it also gave a server tag not well formed error.
2016/03/18
[ "https://Stackoverflow.com/questions/36083156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4436077/" ]
> > Error:(4) No resource identifier found for attribute 'id' in package > 'com.google.rabbit' > > > Accordingly to the compile time error, you have the wrong namespace in your xml ``` <menu xmlns:android="http://schemas.android.com/apk/res-auto" xmlns:xmls="http://schemas.android.com/apk/res/android"> ``` should be ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" > ```
``` <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.sixmod.MainActivity"> <item android:id="@+id/action_settings" android:orderInCategory="100" android:title="@string/action_settings" app:showAsAction="never" /> <item android:id="@+id/title" android:orderInCategory="100" android:title="@string/titlename" app:showAsAction="always" /> <item android:id="@+id/video_camera" android:icon="@drawable/ic_camera_iris_white_36dp" android:showAsAction="always" android:title="@string/menu_camera_label"/> </menu> ```
36,083,156
I have the following ASP Repeater in a table: ``` <asp:Repeater ID="rptPage" runat="server" OnItemCommand="rptPage_ItemCommand" OnItemDataBound="rptPage_ItemDataBound"> <ItemTemplate> <tr> <td id="ArticleTitle"> <%# DataBinder.Eval(Container.DataItem,"Title") %> </td> <td> <%# DataBinder.Eval(Container.DataItem,"AuthorName") %> </td> <td> <asp:Button ID="EditButton" runat="server" CommandName="edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Edit" /> </td> <td> <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete(this)" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> </td> <td> <a href="<%# String.Format("/news/Article={0}", processTitle(Eval("Title"))) %>">View Here</a> </td> </tr> </ItemTemplate> </asp:Repeater> ``` This all works fine. There is a confirm button on the delete function, using the following method: ``` function fnConfirmDelete(ArticleTitle) { return confirm("Delete Article " + ArticleTitle); } ``` Now, what I want to do is pass the text from this: ``` <%# DataBinder.Eval(Container.DataItem,"Title") %> ``` into the confirm box. I have tried adding a 'name' field: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete(this)" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" name='<%# DataBinder.Eval(Container.DataItem,"Title") %>'/> ``` But this does not display the text in the name field, but some kind of server side change. I have also tried passing the value into the JavaScript function: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete('<%# DataBinder.Eval(Container.DataItem,"Title") %>')" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> ``` But this says the server tag is not well formed. I have also tried to pass in an id from the cell that has the value, but again server tag is not well formed. Does anyone know how I can achieve this? Also, once I get it to the JavaScript function, how would I retrieve the value? EDIT: I tried: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete('"<%# DataBinder.Eval(Container.DataItem,"Title") %>"')" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> ``` as suggested by @Reddy below, but it also gave a server tag not well formed error.
2016/03/18
[ "https://Stackoverflow.com/questions/36083156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4436077/" ]
``` <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.sixmod.MainActivity"> <item android:id="@+id/action_settings" android:orderInCategory="100" android:title="@string/action_settings" app:showAsAction="never" /> <item android:id="@+id/title" android:orderInCategory="100" android:title="@string/titlename" app:showAsAction="always" /> <item android:id="@+id/video_camera" android:icon="@drawable/ic_camera_iris_white_36dp" android:showAsAction="always" android:title="@string/menu_camera_label"/> </menu> ```
Resolved such issue with the following code: ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/tools" xmlns:android1="http://schemas.android.com/apk/res/android"> ```
36,083,156
I have the following ASP Repeater in a table: ``` <asp:Repeater ID="rptPage" runat="server" OnItemCommand="rptPage_ItemCommand" OnItemDataBound="rptPage_ItemDataBound"> <ItemTemplate> <tr> <td id="ArticleTitle"> <%# DataBinder.Eval(Container.DataItem,"Title") %> </td> <td> <%# DataBinder.Eval(Container.DataItem,"AuthorName") %> </td> <td> <asp:Button ID="EditButton" runat="server" CommandName="edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Edit" /> </td> <td> <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete(this)" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> </td> <td> <a href="<%# String.Format("/news/Article={0}", processTitle(Eval("Title"))) %>">View Here</a> </td> </tr> </ItemTemplate> </asp:Repeater> ``` This all works fine. There is a confirm button on the delete function, using the following method: ``` function fnConfirmDelete(ArticleTitle) { return confirm("Delete Article " + ArticleTitle); } ``` Now, what I want to do is pass the text from this: ``` <%# DataBinder.Eval(Container.DataItem,"Title") %> ``` into the confirm box. I have tried adding a 'name' field: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete(this)" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" name='<%# DataBinder.Eval(Container.DataItem,"Title") %>'/> ``` But this does not display the text in the name field, but some kind of server side change. I have also tried passing the value into the JavaScript function: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete('<%# DataBinder.Eval(Container.DataItem,"Title") %>')" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> ``` But this says the server tag is not well formed. I have also tried to pass in an id from the cell that has the value, but again server tag is not well formed. Does anyone know how I can achieve this? Also, once I get it to the JavaScript function, how would I retrieve the value? EDIT: I tried: ``` <asp:Button ID="DeleteButton" runat="server" OnClientClick="return fnConfirmDelete('"<%# DataBinder.Eval(Container.DataItem,"Title") %>"')" CommandName="delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"ID") %>' Text="Delete" /> ``` as suggested by @Reddy below, but it also gave a server tag not well formed error.
2016/03/18
[ "https://Stackoverflow.com/questions/36083156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4436077/" ]
> > Error:(4) No resource identifier found for attribute 'id' in package > 'com.google.rabbit' > > > Accordingly to the compile time error, you have the wrong namespace in your xml ``` <menu xmlns:android="http://schemas.android.com/apk/res-auto" xmlns:xmls="http://schemas.android.com/apk/res/android"> ``` should be ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" > ```
Resolved such issue with the following code: ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/tools" xmlns:android1="http://schemas.android.com/apk/res/android"> ```
12,675,608
> > **Possible Duplicate:** > > [Check if JavaScript is enabled with PHP](https://stackoverflow.com/questions/4454551/check-if-javascript-is-enabled-with-php) > > > I need a way to detect if javascript is enabled or disabled in the user-agent in the codeigniter framework
2012/10/01
[ "https://Stackoverflow.com/questions/12675608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1334333/" ]
You cannot detect this directly on the server-side. Please take a look at this article for alternative solutions: <http://www.untwistedvortex.com/detect-javascript-enabled-php/>
There is no way to do a reliable detection in CodeIgniter or other framework/plain PHP. Besides, that information is not part of the standard browser header/user-agent.
12,675,608
> > **Possible Duplicate:** > > [Check if JavaScript is enabled with PHP](https://stackoverflow.com/questions/4454551/check-if-javascript-is-enabled-with-php) > > > I need a way to detect if javascript is enabled or disabled in the user-agent in the codeigniter framework
2012/10/01
[ "https://Stackoverflow.com/questions/12675608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1334333/" ]
You don't get this information with the HTTP-headers. But i have a little workaround: You can store this information in the User-Session. By default you suggest, that JS is disabled. The first delivered Page should execute a Ajax-Call to a script which tells the USER-Session, that Javascript is enabled. Of course this has some disadvantages: * The first Page-Call is allways no-script * You don't get the information, if the User suddenly disables Javascript * Searching-Engines could rate your page down, if you make big differences between the script- and the noscript version Some times it is enough to have the information, if JS is enabled or not, in the CSS. You can do it like this: ``` <head> <script type="text/javascript"> // Jquery version $(function() { $('body').removeClass('noJs'); }); </script> <style type="text/css"> .noJs #hello { display: none; } </style> </head> <body class="noJs"> <div id="hello">Hello</div> </body> ```
There is no way to do a reliable detection in CodeIgniter or other framework/plain PHP. Besides, that information is not part of the standard browser header/user-agent.
49,088,302
I updated my website (development version) to wagtail 2.0 and all RichTextField attributes of my pages are totally uneditable, with Draftail.js. I added the following lines, in my settings.py: ``` WAGTAILADMIN_RICH_TEXT_EDITORS = { 'default': { 'WIDGET': 'wagtail.admin.rich_text.HalloRichTextArea' } } ``` to revert back to the former Hallo.js editor, and it works correctly. But when I remove it, the content that is already saved is not printed and there is no editing feature anymore. Here is the model definition: ``` from django.db import models from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class BlogIndexPage(Page): intro = RichTextField(blank=True,features=[ 'h2', 'h3', 'ol', 'ul', 'bold', 'italic', 'link' ]) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] ``` And my settings.py file: ``` import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'django.contrib.sitemaps', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'homepage', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] ROOT_URLCONF = 'lsvwebsite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'site.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('NAME_DB'), 'USER': config('USER_DB'), 'PASSWORD': config('PASSWORD_DB'), 'HOST': config('HOST_DB'), 'PORT': '', } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password- validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] #media files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #wagtail site name WAGTAIL_SITE_NAME = 'Site Name' WAGTAILADMIN_RICH_TEXT_EDITORS = { 'default': { 'WIDGET': 'wagtail.admin.rich_text.HalloRichTextArea' } } ``` It looks like an issue, with the new Draftail.js editor… Edit 1: errors printed in web console, with Firefox Quantum 58.0.2 ``` TypeError: o.a.createElement is not a function draftail.js:1:241051 TypeError: window.draftail is undefined edit:560:1 ``` Edit 2: errors printed in web console, with Opera 51.0 ``` draftail.js:1 Uncaught TypeError: o.a.createElement is not a function at Object.<anonymous> (draftail.js:1) at t (vendor.js:1) at Object.<anonymous> (draftail.js:1) at t (vendor.js:1) at Object.<anonymous> (draftail.js:1) at t (vendor.js:1) at window.webpackJsonp (vendor.js:1) at draftail.js:1 (index):560 Uncaught TypeError: Cannot read property 'initEditor' of undefined at (index):560 rangy-core.js:80 [Deprecation] The behavior that Selection.addRange() merges existing Range and the specified Range was removed. See https://www.chromestatus.com/features/6680566019653632 for more details. (anonymous) @ rangy-core.js:80 ```
2018/03/03
[ "https://Stackoverflow.com/questions/49088302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5034485/" ]
So, first I tried I clearing the cache, it didn't work. Then I remembered I’m used to set firefox to clear the cache automatically, when it closes, so I checked my firefox settings and it was indeed set like so. Then, I tried @fixgoats solution, I cleared the static files I did not created myself and run collectstatic, it did not work. And I remembered I should not have to run collectstatic in the dev environment, so I deleted them without running collectstatic again, it did not work, so I cleared the cache (since I did not close firefox during the process) and it there worked. My guess is, I had the outdated static files stored directly in dev static directory and firefox was using and caching those outdated files (one problem hiding the other). Now, it all works fine, really big thank to all of you.
I believe I had the same issue, at least the titles of the error messages are the same and the description is quite similar. What worked for me was deleting the static wagtailadmin javascript directory and running collectstatic again. Though I still have no idea what actually caused the bug.
49,719,223
***Summary:*** Jenkins in K8s minikkube works fine and scales well in case of default jnlp agent but stuck with "Waiting for agent to connect" in case of custom jnlp image. ***Detailed description:*** I'm running the local minikube with Jenkins setup. **Jenkins master dockerfile:** ``` from jenkins/jenkins:alpine # Distributed Builds plugins RUN /usr/local/bin/install-plugins.sh ssh-slaves # install Notifications and Publishing plugins RUN /usr/local/bin/install-plugins.sh email-ext RUN /usr/local/bin/install-plugins.sh mailer RUN /usr/local/bin/install-plugins.sh slack # Artifacts RUN /usr/local/bin/install-plugins.sh htmlpublisher # UI RUN /usr/local/bin/install-plugins.sh greenballs RUN /usr/local/bin/install-plugins.sh simple-theme-plugin # Scaling RUN /usr/local/bin/install-plugins.sh kubernetes # install Maven USER root RUN apk update && \ apk upgrade && \ apk add maven USER jenkins ``` **Deployment:** ``` apiVersion: extensions/v1beta1 kind: Deployment metadata: name: jenkins spec: replicas: 1 template: metadata: labels: app: jenkins spec: containers: - name: jenkins image: ybushnev/my-jenkins-image:1.3 env: - name: JAVA_OPTS value: -Djenkins.install.runSetupWizard=false ports: - name: http-port containerPort: 8080 - name: jnlp-port containerPort: 50000 volumeMounts: - name: jenkins-home mountPath: /var/jenkins_home volumes: - name: jenkins-home emptyDir: {} ``` **Service:** ``` apiVersion: v1 kind: Service metadata: name: jenkins spec: type: NodePort ports: - port: 8080 name: "http" targetPort: 8080 - port: 50000 name: "slave" targetPort: 50000 selector: app: jenkins ``` **After deployment I have such services:** ``` Yuris-MBP-2% kubectl get services NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE jenkins NodePort 10.108.30.10 <none> 8080:30267/TCP,50000:31588/TCP 1h kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 1h ``` **Kubernetes master running on:** ``` Yuris-MBP-2% kubectl cluster-info | grep master Kubernetes master is running at https://192.168.99.100:8443 ``` **Based on configuration above I specify the cloud config in Jenkins:** [![enter image description here](https://i.stack.imgur.com/PUxHF.png)](https://i.stack.imgur.com/PUxHF.png) **And finally I put such configuration for slave pod template:** [![enter image description here](https://i.stack.imgur.com/zloN0.png)](https://i.stack.imgur.com/zloN0.png) As a result, via k8s logs I see such logs on the master: ``` Waiting for agent to connect (41/100): kubernetes-agent-tgskx Waiting for agent to connect (42/100): kubernetes-agent-tgskx Waiting for agent to connect (43/100): kubernetes-agent-tgskx Waiting for agent to connect (44/100): kubernetes-agent-tgskx Waiting for agent to connect (45/100): kubernetes-agent-tgskx ``` Jenkins container seems to be green. No logs in K8s but there are such events happened: ``` Successfully assigned kubernetes-agent-517tl to minikube MountVolume.SetUp succeeded for volume "workspace-volume" MountVolume.SetUp succeeded for volume "default-token-8sgh6" ``` **IMPORTANT** If I do not put 'jnlp' inside the container name (I guess this is the important as in another case it takes some default jnlp agent image) slave is spinning up and connecting to the master just fine but even if I have custom docker image inside the 'Docker image' field it doesn't take it as a reference as I can see that Jenkins slave doesn't have such tools/files which it suppose to have based in provided image. Last time I tried to use this image: "gcr.io/cloud-solutions-images/jenkins-k8s-slave" but for me it fails for any image in case I put 'jnlp' as container template name. I tried to play with many images with no luck... Will be very glad for any hint!
2018/04/08
[ "https://Stackoverflow.com/questions/49719223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7125614/" ]
I think you should set credentials for your master jenkins to start new pods. ``` --- apiVersion: v1 kind: ServiceAccount metadata: name: jenkins --- kind: Role apiVersion: rbac.authorization.k8s.io/v1beta1 metadata: name: jenkins rules: - apiGroups: [""] resources: ["pods"] verbs: ["create","delete","get","list","patch","update","watch"] - apiGroups: [""] resources: ["pods/exec"] verbs: ["create","delete","get","list","patch","update","watch"] - apiGroups: [""] resources: ["pods/log"] verbs: ["get","list","watch"] - apiGroups: [""] resources: ["secrets"] verbs: ["get"] --- apiVersion: rbac.authorization.k8s.io/v1beta1 kind: RoleBinding metadata: name: jenkins roleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: jenkins subjects: - kind: ServiceAccount name: jenkins ``` And then in your Deployment use the account: ``` spec: serviceAccountName: jenkins ``` Take a look to my previous answer at <https://stackoverflow.com/a/47874390/2718151> I hope this helps.
custom jnlp container image should have entrypoint script for provide necessary argument to agent.jar file. Example is [here](https://github.com/jenkinsci/docker-inbound-agent/blob/master/jenkins-agent) additionally put argument in Jenkins configuration GUI for container templatein field "Arguments to pass to the command" as: `${computer.jnlpmac} ${computer.name}`
49,719,223
***Summary:*** Jenkins in K8s minikkube works fine and scales well in case of default jnlp agent but stuck with "Waiting for agent to connect" in case of custom jnlp image. ***Detailed description:*** I'm running the local minikube with Jenkins setup. **Jenkins master dockerfile:** ``` from jenkins/jenkins:alpine # Distributed Builds plugins RUN /usr/local/bin/install-plugins.sh ssh-slaves # install Notifications and Publishing plugins RUN /usr/local/bin/install-plugins.sh email-ext RUN /usr/local/bin/install-plugins.sh mailer RUN /usr/local/bin/install-plugins.sh slack # Artifacts RUN /usr/local/bin/install-plugins.sh htmlpublisher # UI RUN /usr/local/bin/install-plugins.sh greenballs RUN /usr/local/bin/install-plugins.sh simple-theme-plugin # Scaling RUN /usr/local/bin/install-plugins.sh kubernetes # install Maven USER root RUN apk update && \ apk upgrade && \ apk add maven USER jenkins ``` **Deployment:** ``` apiVersion: extensions/v1beta1 kind: Deployment metadata: name: jenkins spec: replicas: 1 template: metadata: labels: app: jenkins spec: containers: - name: jenkins image: ybushnev/my-jenkins-image:1.3 env: - name: JAVA_OPTS value: -Djenkins.install.runSetupWizard=false ports: - name: http-port containerPort: 8080 - name: jnlp-port containerPort: 50000 volumeMounts: - name: jenkins-home mountPath: /var/jenkins_home volumes: - name: jenkins-home emptyDir: {} ``` **Service:** ``` apiVersion: v1 kind: Service metadata: name: jenkins spec: type: NodePort ports: - port: 8080 name: "http" targetPort: 8080 - port: 50000 name: "slave" targetPort: 50000 selector: app: jenkins ``` **After deployment I have such services:** ``` Yuris-MBP-2% kubectl get services NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE jenkins NodePort 10.108.30.10 <none> 8080:30267/TCP,50000:31588/TCP 1h kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 1h ``` **Kubernetes master running on:** ``` Yuris-MBP-2% kubectl cluster-info | grep master Kubernetes master is running at https://192.168.99.100:8443 ``` **Based on configuration above I specify the cloud config in Jenkins:** [![enter image description here](https://i.stack.imgur.com/PUxHF.png)](https://i.stack.imgur.com/PUxHF.png) **And finally I put such configuration for slave pod template:** [![enter image description here](https://i.stack.imgur.com/zloN0.png)](https://i.stack.imgur.com/zloN0.png) As a result, via k8s logs I see such logs on the master: ``` Waiting for agent to connect (41/100): kubernetes-agent-tgskx Waiting for agent to connect (42/100): kubernetes-agent-tgskx Waiting for agent to connect (43/100): kubernetes-agent-tgskx Waiting for agent to connect (44/100): kubernetes-agent-tgskx Waiting for agent to connect (45/100): kubernetes-agent-tgskx ``` Jenkins container seems to be green. No logs in K8s but there are such events happened: ``` Successfully assigned kubernetes-agent-517tl to minikube MountVolume.SetUp succeeded for volume "workspace-volume" MountVolume.SetUp succeeded for volume "default-token-8sgh6" ``` **IMPORTANT** If I do not put 'jnlp' inside the container name (I guess this is the important as in another case it takes some default jnlp agent image) slave is spinning up and connecting to the master just fine but even if I have custom docker image inside the 'Docker image' field it doesn't take it as a reference as I can see that Jenkins slave doesn't have such tools/files which it suppose to have based in provided image. Last time I tried to use this image: "gcr.io/cloud-solutions-images/jenkins-k8s-slave" but for me it fails for any image in case I put 'jnlp' as container template name. I tried to play with many images with no luck... Will be very glad for any hint!
2018/04/08
[ "https://Stackoverflow.com/questions/49719223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7125614/" ]
Under the "container template", You need to change the name "jnlp" to something else. Kubernetes plugin will run a sidecar container with the name jnlp for connecting to the master server. If you use the name jnlp for the main container, it will conflict.
custom jnlp container image should have entrypoint script for provide necessary argument to agent.jar file. Example is [here](https://github.com/jenkinsci/docker-inbound-agent/blob/master/jenkins-agent) additionally put argument in Jenkins configuration GUI for container templatein field "Arguments to pass to the command" as: `${computer.jnlpmac} ${computer.name}`
36,077,891
How we can pass array like below in postman and how can we get this array in node JavaScript using express? Following array to be passed in postman: ``` data : [ { name: 'ABC', amount: '1500', }, { name: 'NNS', amount: '5800', }, { name: 'GED', amount: '3500', }, { name: 'PQR', amount: '5500', } ] ``` **Edit :** // in app.js ``` app.use( bodyParser.json() ); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); ``` [![enter image description here](https://i.stack.imgur.com/SU97i.png)](https://i.stack.imgur.com/SU97i.png) //users.js { router } ``` router.post('/test', function(req, res, next){ console.log(req.body.data); res.send(req.body.data); }); ```
2016/03/18
[ "https://Stackoverflow.com/questions/36077891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4891333/" ]
You can send your array with the Postman by following the steps below: [![enter image description here](https://i.stack.imgur.com/kjQGS.jpg)](https://i.stack.imgur.com/kjQGS.jpg) your json must be like this: ``` { "data" : [ { "name": "ABC", "amount": 1500 }, { "name": "NNS", "amount": 5800 }, { "name": "GED", "amount": 3500 }, { "name": "PQ", "amount": 5500 } ] } ``` and you can retrieve this POST query in node (express) like this: ``` var bodyParser = require('body-parser') app.use( bodyParser.json() ); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.post('/people', function(req, res, next) { //show received data console.log(req.body.data); }); ```
send in data parameters ``` key => value data[] => {"name": "ABC", "amount": "1500"} data[] => {"name": "ABC", "amount": "1500"} data[] => {"name": "ABC", "amount": "1500"} ``` but i think this will convert the value to string ["{name:value}",...]
31,213,738
I am working on a JavaScript challenge that asks you to write a function to: "Return the lowest index at which a value (second argument) should be inserted into a sorted array (first argument). For example, `where([1,2,3,4], 1.5)` should return `1` because it is greater than `1 (0th index)`, but less than `2 (1st index)`." The hint indicates to use a built-in "`.sort()`" method that I am unfamiliar with before this challenge. below is what I have so far and I think I am far off. ``` function where(arr, num) { arr.push(num).sort(function(a,b){return a-b;}); return arr.indexOf(num); } console.log(where([40, 60], 50)); // returns "unexpected identifier" ```
2015/07/03
[ "https://Stackoverflow.com/questions/31213738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4844280/" ]
As rightly put by @Xufox, `push` returns the new length of the array and **not** the array itself. Reorder your code as shown: ``` function where(arr, num) { arr.push(num); // Carry out push operation. arr.sort(function(a,b){return a-b;}); // Sort array. return arr.indexOf(num); // Return index of 'num'. } console.log(where([40, 60], 50)); ```
Split the two statments. ```js function where(arr, num) { arr.push(num); arr.sort(function(a, b) { return a - b; }); return arr.indexOf(num); } console.log(where([40, 60], 30)); // 0 console.log(where([40, 60], 50)); // 1 console.log(where([40, 60], 70)); // 2 ```
31,213,738
I am working on a JavaScript challenge that asks you to write a function to: "Return the lowest index at which a value (second argument) should be inserted into a sorted array (first argument). For example, `where([1,2,3,4], 1.5)` should return `1` because it is greater than `1 (0th index)`, but less than `2 (1st index)`." The hint indicates to use a built-in "`.sort()`" method that I am unfamiliar with before this challenge. below is what I have so far and I think I am far off. ``` function where(arr, num) { arr.push(num).sort(function(a,b){return a-b;}); return arr.indexOf(num); } console.log(where([40, 60], 50)); // returns "unexpected identifier" ```
2015/07/03
[ "https://Stackoverflow.com/questions/31213738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4844280/" ]
As rightly put by @Xufox, `push` returns the new length of the array and **not** the array itself. Reorder your code as shown: ``` function where(arr, num) { arr.push(num); // Carry out push operation. arr.sort(function(a,b){return a-b;}); // Sort array. return arr.indexOf(num); // Return index of 'num'. } console.log(where([40, 60], 50)); ```
``` function where(arr, num) { let index = arr.sort((x,y) => x-y) .find(x => num <= x); return index === undefined? arr.length: arr.indexOf(index); } ```
31,213,738
I am working on a JavaScript challenge that asks you to write a function to: "Return the lowest index at which a value (second argument) should be inserted into a sorted array (first argument). For example, `where([1,2,3,4], 1.5)` should return `1` because it is greater than `1 (0th index)`, but less than `2 (1st index)`." The hint indicates to use a built-in "`.sort()`" method that I am unfamiliar with before this challenge. below is what I have so far and I think I am far off. ``` function where(arr, num) { arr.push(num).sort(function(a,b){return a-b;}); return arr.indexOf(num); } console.log(where([40, 60], 50)); // returns "unexpected identifier" ```
2015/07/03
[ "https://Stackoverflow.com/questions/31213738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4844280/" ]
As rightly put by @Xufox, `push` returns the new length of the array and **not** the array itself. Reorder your code as shown: ``` function where(arr, num) { arr.push(num); // Carry out push operation. arr.sort(function(a,b){return a-b;}); // Sort array. return arr.indexOf(num); // Return index of 'num'. } console.log(where([40, 60], 50)); ```
``` function getIndexToIns(arr, num) { arr.sort(function(a, b) { return a - b; }); var i=0; while(num>arr[i]) i++; return i; } ```
31,213,738
I am working on a JavaScript challenge that asks you to write a function to: "Return the lowest index at which a value (second argument) should be inserted into a sorted array (first argument). For example, `where([1,2,3,4], 1.5)` should return `1` because it is greater than `1 (0th index)`, but less than `2 (1st index)`." The hint indicates to use a built-in "`.sort()`" method that I am unfamiliar with before this challenge. below is what I have so far and I think I am far off. ``` function where(arr, num) { arr.push(num).sort(function(a,b){return a-b;}); return arr.indexOf(num); } console.log(where([40, 60], 50)); // returns "unexpected identifier" ```
2015/07/03
[ "https://Stackoverflow.com/questions/31213738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4844280/" ]
Split the two statments. ```js function where(arr, num) { arr.push(num); arr.sort(function(a, b) { return a - b; }); return arr.indexOf(num); } console.log(where([40, 60], 30)); // 0 console.log(where([40, 60], 50)); // 1 console.log(where([40, 60], 70)); // 2 ```
``` function where(arr, num) { let index = arr.sort((x,y) => x-y) .find(x => num <= x); return index === undefined? arr.length: arr.indexOf(index); } ```
31,213,738
I am working on a JavaScript challenge that asks you to write a function to: "Return the lowest index at which a value (second argument) should be inserted into a sorted array (first argument). For example, `where([1,2,3,4], 1.5)` should return `1` because it is greater than `1 (0th index)`, but less than `2 (1st index)`." The hint indicates to use a built-in "`.sort()`" method that I am unfamiliar with before this challenge. below is what I have so far and I think I am far off. ``` function where(arr, num) { arr.push(num).sort(function(a,b){return a-b;}); return arr.indexOf(num); } console.log(where([40, 60], 50)); // returns "unexpected identifier" ```
2015/07/03
[ "https://Stackoverflow.com/questions/31213738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4844280/" ]
Split the two statments. ```js function where(arr, num) { arr.push(num); arr.sort(function(a, b) { return a - b; }); return arr.indexOf(num); } console.log(where([40, 60], 30)); // 0 console.log(where([40, 60], 50)); // 1 console.log(where([40, 60], 70)); // 2 ```
``` function getIndexToIns(arr, num) { arr.sort(function(a, b) { return a - b; }); var i=0; while(num>arr[i]) i++; return i; } ```
31,213,738
I am working on a JavaScript challenge that asks you to write a function to: "Return the lowest index at which a value (second argument) should be inserted into a sorted array (first argument). For example, `where([1,2,3,4], 1.5)` should return `1` because it is greater than `1 (0th index)`, but less than `2 (1st index)`." The hint indicates to use a built-in "`.sort()`" method that I am unfamiliar with before this challenge. below is what I have so far and I think I am far off. ``` function where(arr, num) { arr.push(num).sort(function(a,b){return a-b;}); return arr.indexOf(num); } console.log(where([40, 60], 50)); // returns "unexpected identifier" ```
2015/07/03
[ "https://Stackoverflow.com/questions/31213738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4844280/" ]
``` function where(arr, num) { let index = arr.sort((x,y) => x-y) .find(x => num <= x); return index === undefined? arr.length: arr.indexOf(index); } ```
``` function getIndexToIns(arr, num) { arr.sort(function(a, b) { return a - b; }); var i=0; while(num>arr[i]) i++; return i; } ```
18,580,991
This is something I cannot get my head round. It was my understanding that JavaScript had **truthy** and **falsy** values: ### Falsy values: 0 false undefined null NaN "" (empty string) ### Truthy values: Anything that isn't a falsy value If window.jQuery has loaded correctly, then it shouldn't evaluate to false (or rather, `undefined`). The following condition will return **`true`**: ``` window.jQuery != false ``` However, the following condition will return **`false`**: ``` window.jQuery == true ``` (I'm using `==` for all of these, rather than `===`, otherwise window.jQuery will always evaluate to `false` unless it is literally a boolean containing the value `false`). What is happening here? Surely if a condition doesn't evaluate to `false`, then it must evaluate to `true`?
2013/09/02
[ "https://Stackoverflow.com/questions/18580991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2176546/" ]
`jQuery` is a function, and it's not `== true`, so you get `false`, and it's `!= false` so you get `true`. I think you've got the idea that a `==` comparison is the same as a boolean conversion. It's not. To do a boolean conversion, you could do `Boolean(window.jQuery) == true`, and you'll get `true`. Or just `!!window.jQuery == true`. When you convert to a boolean value, *then* you get conversion to `true` in all cases except `false`, `null`, `undefined`, `NaN`, `""` and `0`. Ultimately if you want to see if jQuery is loaded, then you'd just do... ``` if (window.jQuery) { ``` Which will perform the boolean conversion for you.
When comparing values of different types, some internal conversions happen implicitly. Assuming jQuery is being used, you would have the following: For window.jQuery != false: 1. window.jQuery != false 2. window.jQuery.toString() != 0 3. "function (e,t){return new x.fn.init(e,t,r)}" != 0 4. Number("function (e,t){return new x.fn.init(e,t,r)}") != 0 5. NaN != 0 6. true For window.jQuery == true, something similar happens: 1. window.jQuery == true 2. window.jQuery.toString() == 1 3. "function (e,t){return new x.fn.init(e,t,r)}" == 1 4. Number("function (e,t){return new x.fn.init(e,t,r)}") == 1 5. NaN == 1 6. false Source: <http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/>
18,580,991
This is something I cannot get my head round. It was my understanding that JavaScript had **truthy** and **falsy** values: ### Falsy values: 0 false undefined null NaN "" (empty string) ### Truthy values: Anything that isn't a falsy value If window.jQuery has loaded correctly, then it shouldn't evaluate to false (or rather, `undefined`). The following condition will return **`true`**: ``` window.jQuery != false ``` However, the following condition will return **`false`**: ``` window.jQuery == true ``` (I'm using `==` for all of these, rather than `===`, otherwise window.jQuery will always evaluate to `false` unless it is literally a boolean containing the value `false`). What is happening here? Surely if a condition doesn't evaluate to `false`, then it must evaluate to `true`?
2013/09/02
[ "https://Stackoverflow.com/questions/18580991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2176546/" ]
`jQuery` is a function, and it's not `== true`, so you get `false`, and it's `!= false` so you get `true`. I think you've got the idea that a `==` comparison is the same as a boolean conversion. It's not. To do a boolean conversion, you could do `Boolean(window.jQuery) == true`, and you'll get `true`. Or just `!!window.jQuery == true`. When you convert to a boolean value, *then* you get conversion to `true` in all cases except `false`, `null`, `undefined`, `NaN`, `""` and `0`. Ultimately if you want to see if jQuery is loaded, then you'd just do... ``` if (window.jQuery) { ``` Which will perform the boolean conversion for you.
When you compare values with `true` or `false`, it doesn't just compare their truthiness. `true` and `false` are specific values, just like different numbers and strings. Just because two values have the same truthiness, doesn't mean they actually compare equal. If you want to compare the truthiness of two values, you can do it by forcing them to boolean types. A simple way to do this is with boolean inversion: ``` if (!foo == !bar) ``` will tell if `foo` and `bar` have the same truthiness.
18,580,991
This is something I cannot get my head round. It was my understanding that JavaScript had **truthy** and **falsy** values: ### Falsy values: 0 false undefined null NaN "" (empty string) ### Truthy values: Anything that isn't a falsy value If window.jQuery has loaded correctly, then it shouldn't evaluate to false (or rather, `undefined`). The following condition will return **`true`**: ``` window.jQuery != false ``` However, the following condition will return **`false`**: ``` window.jQuery == true ``` (I'm using `==` for all of these, rather than `===`, otherwise window.jQuery will always evaluate to `false` unless it is literally a boolean containing the value `false`). What is happening here? Surely if a condition doesn't evaluate to `false`, then it must evaluate to `true`?
2013/09/02
[ "https://Stackoverflow.com/questions/18580991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2176546/" ]
`jQuery` is a function, and it's not `== true`, so you get `false`, and it's `!= false` so you get `true`. I think you've got the idea that a `==` comparison is the same as a boolean conversion. It's not. To do a boolean conversion, you could do `Boolean(window.jQuery) == true`, and you'll get `true`. Or just `!!window.jQuery == true`. When you convert to a boolean value, *then* you get conversion to `true` in all cases except `false`, `null`, `undefined`, `NaN`, `""` and `0`. Ultimately if you want to see if jQuery is loaded, then you'd just do... ``` if (window.jQuery) { ``` Which will perform the boolean conversion for you.
If you're trying to see if jQuery is loaded or not. This will tell you. ``` if (jQuery) { // jQuery is loaded } else { // jQuery is not loaded } ``` Check out this blog post: [Check if jQuery is Loaded](http://jquery-howto.blogspot.com/2009/03/check-if-jqueryjs-is-loaded.html)
18,580,991
This is something I cannot get my head round. It was my understanding that JavaScript had **truthy** and **falsy** values: ### Falsy values: 0 false undefined null NaN "" (empty string) ### Truthy values: Anything that isn't a falsy value If window.jQuery has loaded correctly, then it shouldn't evaluate to false (or rather, `undefined`). The following condition will return **`true`**: ``` window.jQuery != false ``` However, the following condition will return **`false`**: ``` window.jQuery == true ``` (I'm using `==` for all of these, rather than `===`, otherwise window.jQuery will always evaluate to `false` unless it is literally a boolean containing the value `false`). What is happening here? Surely if a condition doesn't evaluate to `false`, then it must evaluate to `true`?
2013/09/02
[ "https://Stackoverflow.com/questions/18580991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2176546/" ]
When comparing values of different types, some internal conversions happen implicitly. Assuming jQuery is being used, you would have the following: For window.jQuery != false: 1. window.jQuery != false 2. window.jQuery.toString() != 0 3. "function (e,t){return new x.fn.init(e,t,r)}" != 0 4. Number("function (e,t){return new x.fn.init(e,t,r)}") != 0 5. NaN != 0 6. true For window.jQuery == true, something similar happens: 1. window.jQuery == true 2. window.jQuery.toString() == 1 3. "function (e,t){return new x.fn.init(e,t,r)}" == 1 4. Number("function (e,t){return new x.fn.init(e,t,r)}") == 1 5. NaN == 1 6. false Source: <http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/>
When you compare values with `true` or `false`, it doesn't just compare their truthiness. `true` and `false` are specific values, just like different numbers and strings. Just because two values have the same truthiness, doesn't mean they actually compare equal. If you want to compare the truthiness of two values, you can do it by forcing them to boolean types. A simple way to do this is with boolean inversion: ``` if (!foo == !bar) ``` will tell if `foo` and `bar` have the same truthiness.
18,580,991
This is something I cannot get my head round. It was my understanding that JavaScript had **truthy** and **falsy** values: ### Falsy values: 0 false undefined null NaN "" (empty string) ### Truthy values: Anything that isn't a falsy value If window.jQuery has loaded correctly, then it shouldn't evaluate to false (or rather, `undefined`). The following condition will return **`true`**: ``` window.jQuery != false ``` However, the following condition will return **`false`**: ``` window.jQuery == true ``` (I'm using `==` for all of these, rather than `===`, otherwise window.jQuery will always evaluate to `false` unless it is literally a boolean containing the value `false`). What is happening here? Surely if a condition doesn't evaluate to `false`, then it must evaluate to `true`?
2013/09/02
[ "https://Stackoverflow.com/questions/18580991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2176546/" ]
When comparing values of different types, some internal conversions happen implicitly. Assuming jQuery is being used, you would have the following: For window.jQuery != false: 1. window.jQuery != false 2. window.jQuery.toString() != 0 3. "function (e,t){return new x.fn.init(e,t,r)}" != 0 4. Number("function (e,t){return new x.fn.init(e,t,r)}") != 0 5. NaN != 0 6. true For window.jQuery == true, something similar happens: 1. window.jQuery == true 2. window.jQuery.toString() == 1 3. "function (e,t){return new x.fn.init(e,t,r)}" == 1 4. Number("function (e,t){return new x.fn.init(e,t,r)}") == 1 5. NaN == 1 6. false Source: <http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/>
If you're trying to see if jQuery is loaded or not. This will tell you. ``` if (jQuery) { // jQuery is loaded } else { // jQuery is not loaded } ``` Check out this blog post: [Check if jQuery is Loaded](http://jquery-howto.blogspot.com/2009/03/check-if-jqueryjs-is-loaded.html)
18,580,991
This is something I cannot get my head round. It was my understanding that JavaScript had **truthy** and **falsy** values: ### Falsy values: 0 false undefined null NaN "" (empty string) ### Truthy values: Anything that isn't a falsy value If window.jQuery has loaded correctly, then it shouldn't evaluate to false (or rather, `undefined`). The following condition will return **`true`**: ``` window.jQuery != false ``` However, the following condition will return **`false`**: ``` window.jQuery == true ``` (I'm using `==` for all of these, rather than `===`, otherwise window.jQuery will always evaluate to `false` unless it is literally a boolean containing the value `false`). What is happening here? Surely if a condition doesn't evaluate to `false`, then it must evaluate to `true`?
2013/09/02
[ "https://Stackoverflow.com/questions/18580991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2176546/" ]
When you compare values with `true` or `false`, it doesn't just compare their truthiness. `true` and `false` are specific values, just like different numbers and strings. Just because two values have the same truthiness, doesn't mean they actually compare equal. If you want to compare the truthiness of two values, you can do it by forcing them to boolean types. A simple way to do this is with boolean inversion: ``` if (!foo == !bar) ``` will tell if `foo` and `bar` have the same truthiness.
If you're trying to see if jQuery is loaded or not. This will tell you. ``` if (jQuery) { // jQuery is loaded } else { // jQuery is not loaded } ``` Check out this blog post: [Check if jQuery is Loaded](http://jquery-howto.blogspot.com/2009/03/check-if-jqueryjs-is-loaded.html)
58,546,643
I am making a blog using React and MongoDB. I retrieve the data from MongoDB, here is my component: ``` import React, { Component } from 'react'; import axios from 'axios'; export default class Post extends Component { constructor(props) { super(props); this.state = { posts: [] }; } truncateText = text => { return text.substring(0, 500) + "..."; } allPosts = () => { return this.state.posts.map(function(astroPost, i){ return <div class="post-container"> <img className="post-info-container__image" src={astroPost.picture} alt=""/> <div className="post" posts={astroPost} key={i}> <div class="post-container__text"> <h2>{astroPost.title}</h2> <p className="date">{astroPost.date}</p> <p className="post-info-container__text">{this.truncateText(astroPost.postContent)}</p> <button>Read more</button> </div> </div> </div> }) } componentDidMount() { axios.get('http://localhost:4000/') .then(response => { this.setState({posts: response.data}) console.log(response) }) .catch(function(error) { console.log(error) }) } render() { return ( <div> { this.allPosts() } </div> ) } } ``` I want to truncate the text of my post so that a post shows only 500 symbols. I achieved this by doing so: ``` return this.state.posts.map(function(astroPost, i){ return <div class="post-container"> <img className="post-info-container__image" src={astroPost.picture} alt=""/> <div className="post" posts={astroPost} key={i}> <div class="post-container__text"> <h2>{astroPost.title}</h2> <p className="date">{astroPost.date}</p> <p className="post-info-container__text">{astroPost.postContent.substring(0, 500) + "..."}</p> <button>Read more</button> </div> </div> </div> ``` But I want to do it with a function that get's called on the text, so I kept the same logic in a function called truncateText, but when I call it like this: ``` return this.state.posts.map(function(astroPost, i){ return <div class="post-container"> <img className="post-info-container__image" src={astroPost.picture} alt=""/> <div className="post" posts={astroPost} key={i}> <div class="post-container__text"> <h2>{astroPost.title}</h2> <p className="date">{astroPost.date}</p> <p className="post-info-container__text">{astroPost.postContent.truncateText()}</p> <button>Read more</button> </div> </div> </div> }) } ``` It says that `TypeError: astroPost.postContent.truncateText is not a function` How can I call that function and perform the truncation properly?
2019/10/24
[ "https://Stackoverflow.com/questions/58546643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11587190/" ]
You have not bound `truncatetext` to the component: [that causes problems with the context](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this). In the constructor, you can use `this.truncatetext = this.truncatetext.bind(this)`: ``` constructor(props) { super(props); this.state = { posts: [] }; this.truncateText = this.truncateText.bind(this); } ```
astroPost is just the element inside the array you are iterating. Also, if you create a function in your class, you have to do one of this things: or bind the function to the "this" element, or create the function as an arrow function. I recommend second option. So, for your case, you would end with something like this: ``` truncateText = text => { return text.substring(0, 500) + "..."; } ``` and then, inside your map you can call it like this: ``` <p className="post-info-container__text">{this.truncateText(astroPost.postContent)}</p> ```
396,690
There is an increasing interest toward GraphQL and Falcor across the Web. Each time I see an article or discussion about those, I get reminded about SQL, at least its DQL part. Obviously, sending raw SQL queries over the wire gives the client too much power; however, with the most recent versions of DB—Postgres could be an example—we could limit which users could invoke which stored procedures, and even which rows could they see. Sorry if I'm missing something obvious, but it seems to me that with carefully designed query complexity control, with row-based auth and with well-separated per-user privileges, one could just pass a client-formed SQL query straight to the DB engine, and be safe, thus replacing GraphQL with just SQL, and saving one conversion layer in our app. Has there been any such prior experience in the world?
2019/08/29
[ "https://softwareengineering.stackexchange.com/questions/396690", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/243633/" ]
> > one could just pass a client-formed SQL query straight to the DB engine, and be safe > > > Nope. Let's assume that your security is perfect. I can still write a long running query that locks your tables. > > saving one conversion layer in our app. > > > Unlikely. User management, auth tokens, serialising, versioning, fail over etc mean that you are probably going to be unable to completely remove the api layer
The last 20-40+ years of systems development can be seen as largely trying to manage the tension between the fact that users want freedom to do what they want in a system, but the owners of the system are more particular. The owners don't want the database screwed up, they want some things secret and some things not, things that are secret are only secret to some users but OK for others to review (but maybe not to edit), they want some users to do some things but not others, and they want the database resources to remain available (not to crash, degrade, or chew up tons of expensive computational/electrical/storage resources). The thing is, the better the database is at giving some power-users what they want (like developers), the worse they are at serving the needs of other users. It is not a question of whether or not the functionality exists to batten down the hatches and encode security in complex database systems - it is that if you try to do it, you will find it sucks. Just ask a database administrator of a modest-sized system how hard it is to keep databases working and available even when the system is only used by carefully authorized users who are supposed to know what they are doing, and who are not supposed to be expected to have ill intent. Its a full-time job for a reason! Databases which serve the needs of an organization (i.e. management) and the needs of developers are already hard to work with as it is! And developers of the database systems themselves seem to understand this well. They don't particularly try to design the systems to be exposed to end-users directly, largely because they know it won't work out. The system prioritizes the needs of other users, and that means if the system is to be good for some it must be inaccessible to others. Instead, you can try to design a system for users to access directly, but this will involve different trade-offs in what functionality is safe and what isn't. Or, Option B - create a pass-through layer! Layers work precisely because each layer can be designed with a small subset of users and functionality in mind, and thus you can have a world-facing layer, an application-developer only layer, a data-management layer, etc. It exists because it, well, works.
63,467,764
I am not able to call a C function in another JavaScript file, it is giving the error 'called before runtime initialization' [please refer to this link](https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#interacting-with-code-ccall-cwrap.) I compiled the C code in emscripten as described in the given link and used generated asm.js file in my test.js file. command used to generate asm :- ``` emcc test/hello.cpp -o hello.html -s EXPORTED_FUNCTIONS="['_int_sqrt']" -s EXPORTED_RUNTIME_METHODS="["ccall", "cwrap"]" ``` code in test.js file : ``` var Module = require('./asm.js'); var test = Module.cwrap('int_sqrt', 'number', ['number']); console.log(test(25)); ``` and when I run `node test` it gives the error > > > ``` > abort(Assertion failed: native function `int_sqrt` called before runtime initialization) > > ``` > >
2020/08/18
[ "https://Stackoverflow.com/questions/63467764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14124998/" ]
you should wait for runtime init. try this: ``` var Module = require("./lib.js"); var result = Module.onRuntimeInitialized = () => { Module.ccall('myFunction', // name of C function null, // return type null, // argument types null // arguments ); } ```
I had the same issue while using **emscripten** and this has worked for me: ``` <script> Module.onRuntimeInitialized = () => { Module.functionName(param); } </script> ``` Where **functionName** is the name of the function that you want to invoke and **param** is the value that you want to pass to it.
21,902,745
I have a small bit of code that shows thumbnails of images and when you click on them they show a larger version of each. It works perfectly in Google Chrome, but in Firefox the thumbnails become larger so they no longer fit on a single line (I use percentages), I am sure it must be a simple fix, but sadly I don't know what it is. Here is the preview on my site : <http://www.poipleshadow.com/Children-Charity-Blog-2014-02-February#CarnivalForTheChildren> I use styled Radio inputs, for those who don't know, there CAN NOT be spaces between the inputs otherwise extra margins are added for some reason! That took a while to figure out!! Anyway, each one has a width of 11.11% times that by 9 thumbnails should come to 99.99%. I have added the full code, but it's really only the radioboxes which is the issue. **CSS** ``` /* ********************** NEW GALLERY CODE ************************/ /* IMPORTANT - IN THE CODE THERE CAN'T BE SPACE BETWEEN EACH INPUT (Eg New Lines) AS IT MESSES WITH FORMAT OF THE DISPLAY */ .radiogallery {position:relative; width:100%; height:auto; padding:0; border:0; margin:0; overflow:hidden; background:none; text-align:center;} /*Bounding Box */ /* Use this border as the border to the image, the border on the label is for spacing instead of using a margin */ .radiogallery img { max-width: 100%; height:auto; padding:0; margin:0; border: 2px solid #eee; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } /************************ Thumbnails ************************/ /* Use the Border to add spacing between the images */ .radiogallery label {display:inline-block; overflow:hidden; line-height:0; opacity:1; height:auto; margin:0; padding:0; margin-bottom:-4px; border: 2px solid #eee; cursor:pointer; background:none; box-sizing:border-box; } /* Thumbnails */ .radiogallery label.nine { width:11.11%; } /* Thumbnails (9 ACROSS)*/ .radiogallery input {display:none; } /* Check Box Selection Status (NOT SHOWN) */ .radiogallery input:checked + label img{opacity:1; border: 1px solid #09F; } .radiogallery input.pics + label img:hover {opacity:1; border: 1px solid #09F; } .radiogallery input:checked + label:hover {opacity:1; } /************************ MAIN IMAGE (Hiding) ************************/ .radiogallery div.large {position:absolute;display:inline-block; left:0; top:730px; width:100%; height:auto; margin:auto; border:0; background:none; padding:0px; text-align:center; opacity:0; z-index:100; overflow:hidden; -webkit-transition:0.5s; -moz-transition:0.5s; -ms-transition:0.5s; -o-transition:0.5s; transition:0.5s; } /* Make Float:none so that image is centered */ .radiogallery div.large img { margin:auto; background:none; width:720px; width:auto; margin:0; margin-top:10px; padding:2px; background:white; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; border: 1px solid #bbe3ff; float:none;} /**************************************************** MAIN IMAGE (Showing) ****************************************************/ .radiogallery input#pic1:checked ~ div.pic1, .radiogallery input#pic2:checked ~ div.pic2, .radiogallery input#pic3:checked ~ div.pic3, .radiogallery input#pic4:checked ~ div.pic4, .radiogallery input#pic5:checked ~ div.pic5, .radiogallery input#pic6:checked ~ div.pic6, .radiogallery input#pic7:checked ~ div.pic7, .radiogallery input#pic8:checked ~ div.pic8, .radiogallery input#pic9:checked ~ div.pic9, .radiogallery input#pic10:checked ~ div.pic10, .radiogallery input#pic11:checked ~ div.pic11, .radiogallery input#pic12:checked ~ div.pic12, .radiogallery input#pic13:checked ~ div.pic13, .radiogallery input#pic14:checked ~ div.pic14, .radiogallery input#pic15:checked ~ div.pic15, .radiogallery input#pic16:checked ~ div.pic16 {position:relative; opacity:1; z-index:100; top:10%; height:auto; margin:auto; padding:0; background:none; } ``` **HTML** ``` <div class="radiogallery"> <input type="radio" name="pic" id="pic1" class="pics" checked="checked"><label for="pic1" class="nine"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-01.JPG" alt="Carnival and Goa Entertainers 1" width="960" height="720"></label><input type="radio" name="pic" id="pic2" class="pics"><label for="pic2" class="nine"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-02.JPG" alt="Carnival and Goa Entertainers 2" width="960" height="720"></label><input type="radio" name="pic" id="pic3" class="pics"><label for="pic3" class="nine"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-03.JPG" alt="Carnival and Goa Entertainers 3" width="960" height="720"></label><input type="radio" name="pic" id="pic4" class="pics"><label for="pic4" class="nine"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-04.JPG" alt="Carnival and Goa Entertainers 4" width="960" height="720"></label><input type="radio" name="pic" id="pic5" class="pics"><label for="pic5" class="nine"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-05.JPG" alt="Carnival and Goa Entertainers 5" width="960" height="720"></label><input type="radio" name="pic" id="pic6" class="pics"><label for="pic6" class="nine"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-06.JPG" alt="Carnival and Goa Entertainers 6" width="960" height="720"></label><input type="radio" name="pic" id="pic7" class="pics"><label for="pic7" class="nine"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-07.JPG" alt="Carnival and Goa Entertainers 7" width="960" height="720"></label><input type="radio" name="pic" id="pic8" class="pics"><label for="pic8" class="nine"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-08.JPG" alt="Carnival and Goa Entertainers 8" width="960" height="720"></label><input type="radio" name="pic" id="pic9" class="pics"><label for="pic9" class="nine"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-09.JPG" alt="Carnival and Goa Entertainers 8" width="960" height="720"></label> <div class="pic1 large"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-01.JPG" alt="Carnival and Goa Entertainers 1" width="960" height="720"></div> <div class="pic2 large"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-02.JPG" alt="Carnival and Goa Entertainers 2" width="960" height="720"></div> <div class="pic3 large"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-03.JPG" alt="Carnival and Goa Entertainers 3" width="960" height="720"></div> <div class="pic4 large"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-04.JPG" alt="Carnival and Goa Entertainers 4" width="960" height="720"></div> <div class="pic5 large"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-05.JPG" alt="Carnival and Goa Entertainers 5" width="960" height="720"></div> <div class="pic6 large"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-06.JPG" alt="Carnival and Goa Entertainers 6" width="960" height="720"></div> <div class="pic7 large"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-07.JPG" alt="Carnival and Goa Entertainers 7" width="960" height="720"></div> <div class="pic8 large"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-08.JPG" alt="Carnival and Goa Entertainers 8" width="960" height="720"></div> <div class="pic9 large"><img src="Blog/2014-Photo-Sets/02-Feb/Carnival-09.JPG" alt="Carnival and Goa Entertainers 8" width="960" height="720"></div> </div> <!-- end radiogroup --> ```
2014/02/20
[ "https://Stackoverflow.com/questions/21902745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443301/" ]
A bit tricky, and you'll have to check yourself for the different browsers' support, but here is a `[**Fiddle Demo**](http://jsfiddle.net/ronency/ucWAE/1/)` for you :-) **html** ``` <input type="text" placeholder="Name" /> ``` **css** ``` input::-webkit-input-placeholder:after{color:red;content:" *";} ``` Just moved the \* to be a part of the :after element, and styled it separately.
The top-rated solution doesn't work anymore I found the solution from [How to set color for last character in placeholder](https://stackoverflow.com/questions/41614440/how-to-set-color-for-last-character-in-placeholder) And here is the code: ``` input { padding: 1em; } ::-webkit-input-placeholder { background: -webkit-linear-gradient(left, #AAA 0%, #AAA 70%,red 70%, red 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } ```
44,440,844
I use aws ec2 with elastic beanstalk(eb) to deploy application then I try to access application I got empty page and no error on console. I put my template under > > app/assets/templates/simple\_template.html.erb > > > Then I tried to check with server in rails log (production.log) nginx log (access.log , error.log) is no any error in these logs > > > I search on Google then I found some people talk about > > gem sprockets > > > then I put **gem 'sprockets', '~> 3.0'** to gem file is still not working More Detail [Empty page](https://i.stack.imgur.com/ugXrz.png) [Inspect HTML](https://i.stack.imgur.com/Yqwpf.png)
2017/06/08
[ "https://Stackoverflow.com/questions/44440844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1415480/" ]
I know this is old, but this just happened to me and this is what I found. For me, it ended up being the encoding of the file including the byte order mark (BOM), which got interpreted as part of the first line and so instead of setting the "env" variable, it thought it was executing a command (the first error in your output supports this). You can confirm by adding `echo "env = $env"` as the 2nd line and you'll see "env = ", showing that the env variable isn't set. I had created .bashrc using notepad++ and it defaults to utf-8 with BOM. You can change the encoding (the encoding menu) to utf-8 or ANSI, re-save the file, and it should now work as expected. Alternatively, delete the file and re-create it from bash: ``` cd ~/ rm .bashrc umask 077 touch .bashrc ``` then edit the file and paste your script.
Point `ssh-add` to the file, eg `ssh-add ~/.ssh/id_rsa` or `c:/somenondefaultlocation/.ssh/id_rsa` ``` if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then agent_start ssh-add elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then ssh-add ``` Also, make sure you set the same directory for the first line, eg `env=~/.ssh/agent.env` or `env=c:/somenondefaultlocation/.ssh/agent.env`
44,440,844
I use aws ec2 with elastic beanstalk(eb) to deploy application then I try to access application I got empty page and no error on console. I put my template under > > app/assets/templates/simple\_template.html.erb > > > Then I tried to check with server in rails log (production.log) nginx log (access.log , error.log) is no any error in these logs > > > I search on Google then I found some people talk about > > gem sprockets > > > then I put **gem 'sprockets', '~> 3.0'** to gem file is still not working More Detail [Empty page](https://i.stack.imgur.com/ugXrz.png) [Inspect HTML](https://i.stack.imgur.com/Yqwpf.png)
2017/06/08
[ "https://Stackoverflow.com/questions/44440844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1415480/" ]
I know it's an old thread, but maybe i can help some others who run across this problem. In my case, I simply had to create the .ssh folder in the user profile to get this working.
Point `ssh-add` to the file, eg `ssh-add ~/.ssh/id_rsa` or `c:/somenondefaultlocation/.ssh/id_rsa` ``` if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then agent_start ssh-add elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then ssh-add ``` Also, make sure you set the same directory for the first line, eg `env=~/.ssh/agent.env` or `env=c:/somenondefaultlocation/.ssh/agent.env`
44,440,844
I use aws ec2 with elastic beanstalk(eb) to deploy application then I try to access application I got empty page and no error on console. I put my template under > > app/assets/templates/simple\_template.html.erb > > > Then I tried to check with server in rails log (production.log) nginx log (access.log , error.log) is no any error in these logs > > > I search on Google then I found some people talk about > > gem sprockets > > > then I put **gem 'sprockets', '~> 3.0'** to gem file is still not working More Detail [Empty page](https://i.stack.imgur.com/ugXrz.png) [Inspect HTML](https://i.stack.imgur.com/Yqwpf.png)
2017/06/08
[ "https://Stackoverflow.com/questions/44440844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1415480/" ]
For others who end up here trying to figure out why their script isn't executing when they add it to either `~/.profile` or `~/.bashrc`, I found I needed to add it to `~/.bash_profile` for it to get picked up and used by Git Bash on Windows.
Point `ssh-add` to the file, eg `ssh-add ~/.ssh/id_rsa` or `c:/somenondefaultlocation/.ssh/id_rsa` ``` if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then agent_start ssh-add elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then ssh-add ``` Also, make sure you set the same directory for the first line, eg `env=~/.ssh/agent.env` or `env=c:/somenondefaultlocation/.ssh/agent.env`
44,440,844
I use aws ec2 with elastic beanstalk(eb) to deploy application then I try to access application I got empty page and no error on console. I put my template under > > app/assets/templates/simple\_template.html.erb > > > Then I tried to check with server in rails log (production.log) nginx log (access.log , error.log) is no any error in these logs > > > I search on Google then I found some people talk about > > gem sprockets > > > then I put **gem 'sprockets', '~> 3.0'** to gem file is still not working More Detail [Empty page](https://i.stack.imgur.com/ugXrz.png) [Inspect HTML](https://i.stack.imgur.com/Yqwpf.png)
2017/06/08
[ "https://Stackoverflow.com/questions/44440844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1415480/" ]
I know it's an old thread, but maybe i can help some others who run across this problem. In my case, I simply had to create the .ssh folder in the user profile to get this working.
I know this is old, but this just happened to me and this is what I found. For me, it ended up being the encoding of the file including the byte order mark (BOM), which got interpreted as part of the first line and so instead of setting the "env" variable, it thought it was executing a command (the first error in your output supports this). You can confirm by adding `echo "env = $env"` as the 2nd line and you'll see "env = ", showing that the env variable isn't set. I had created .bashrc using notepad++ and it defaults to utf-8 with BOM. You can change the encoding (the encoding menu) to utf-8 or ANSI, re-save the file, and it should now work as expected. Alternatively, delete the file and re-create it from bash: ``` cd ~/ rm .bashrc umask 077 touch .bashrc ``` then edit the file and paste your script.
44,440,844
I use aws ec2 with elastic beanstalk(eb) to deploy application then I try to access application I got empty page and no error on console. I put my template under > > app/assets/templates/simple\_template.html.erb > > > Then I tried to check with server in rails log (production.log) nginx log (access.log , error.log) is no any error in these logs > > > I search on Google then I found some people talk about > > gem sprockets > > > then I put **gem 'sprockets', '~> 3.0'** to gem file is still not working More Detail [Empty page](https://i.stack.imgur.com/ugXrz.png) [Inspect HTML](https://i.stack.imgur.com/Yqwpf.png)
2017/06/08
[ "https://Stackoverflow.com/questions/44440844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1415480/" ]
I know it's an old thread, but maybe i can help some others who run across this problem. In my case, I simply had to create the .ssh folder in the user profile to get this working.
For others who end up here trying to figure out why their script isn't executing when they add it to either `~/.profile` or `~/.bashrc`, I found I needed to add it to `~/.bash_profile` for it to get picked up and used by Git Bash on Windows.
17,440,152
There are several questions about this in the forum, but I couldn't get a good answer for what I need. I am getting into Canvas and Javascript, and I want to preload some images as soon as the game opens. I made an example of the method I wanted to build (and didn't work) I have 3 files: "main.html" where the canvas (there is only one in this example) is declared and I try to load an image, "ImagePreloader.js" where I preload all the images and "Variables.js" where I have my variables. Could anyone please help me with this image preloading metod, or suggest me a viable one? I think the image is not loading because I am not using an onLoad() function, which I couldn't understand in the tutorials I read so far (I know how to apply it to an image, but not to an array of images) main.html: ``` <!DOCTYPE HTML> <html> <body> <canvas id="myCanvas" width="800" height="600"></canvas> <script type="text/javascript" src="Variables.js"></script> <script type="text/javascript" src="ImagePreloader.js"></script> <script> // Basic canvas info var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); // Draw one of the images. Somehow it doesn't work :( context.drawImage(imageArray[3], x, y, width, height); </script> </body> </html> ``` ImagePreloader.js ``` // This should preload the images in imageArray[i] with 0 <= i <= 5 ... right? function preloader() { for(var i=0; i<5; i++) { imageArray[i].src=images[i]; } } ``` Variables.js ``` // array of sources of my images images = new Array(); images[0]="img1.jpg" images[1]="img2.jpg" images[2]="img3.jpg" images[3]="img4.jpg" images[4]="img5.jpg" // Stuff to draw the image var x = 50; var y = 50; var width = 256; var height = 256; // Is this actually an array of images? imageArray = new Image(); ``` Thanks in advance!
2013/07/03
[ "https://Stackoverflow.com/questions/17440152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217820/" ]
You have to make sure these 5 images are loaded (downloaded doesnt alwaysmean its loaded and ready to use, only onload guarantees that image is ready to use) before you use it. So add onload for the images, then count from the onload function and trigger the draw after 5 of them are loaded ``` function prefetchImages(sources){ var images = []; var loadedImages = 0; var numImages = sources.length; for (var i=0; i < numImages; i++) { images[i] = new Image(); images[i].onload = function(){ if (++loadedImages >= numImages) { //ready draw with my images now drawThePainting(); } }; images[i].src = sources[i]; //bind onload before setting src bug in some chrome versions } }; prefetchImages(["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]); function drawThePainting(){ // Basic canvas info var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); // Draw one of the images. Somehow it doesn't work :( context.drawImage(imageArray[3], x, y, width, height); } ```
try this ``` put this script in head section <script type="text/javascript"> function preload(arrayOfImages) { for(i = 0 ; i < arrayOfImages.length ; i++) { var img = new Image(); img.src = arrayOfImages[i]; } } preload(['img1.png','img2.png']); </script> ```
17,440,152
There are several questions about this in the forum, but I couldn't get a good answer for what I need. I am getting into Canvas and Javascript, and I want to preload some images as soon as the game opens. I made an example of the method I wanted to build (and didn't work) I have 3 files: "main.html" where the canvas (there is only one in this example) is declared and I try to load an image, "ImagePreloader.js" where I preload all the images and "Variables.js" where I have my variables. Could anyone please help me with this image preloading metod, or suggest me a viable one? I think the image is not loading because I am not using an onLoad() function, which I couldn't understand in the tutorials I read so far (I know how to apply it to an image, but not to an array of images) main.html: ``` <!DOCTYPE HTML> <html> <body> <canvas id="myCanvas" width="800" height="600"></canvas> <script type="text/javascript" src="Variables.js"></script> <script type="text/javascript" src="ImagePreloader.js"></script> <script> // Basic canvas info var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); // Draw one of the images. Somehow it doesn't work :( context.drawImage(imageArray[3], x, y, width, height); </script> </body> </html> ``` ImagePreloader.js ``` // This should preload the images in imageArray[i] with 0 <= i <= 5 ... right? function preloader() { for(var i=0; i<5; i++) { imageArray[i].src=images[i]; } } ``` Variables.js ``` // array of sources of my images images = new Array(); images[0]="img1.jpg" images[1]="img2.jpg" images[2]="img3.jpg" images[3]="img4.jpg" images[4]="img5.jpg" // Stuff to draw the image var x = 50; var y = 50; var width = 256; var height = 256; // Is this actually an array of images? imageArray = new Image(); ``` Thanks in advance!
2013/07/03
[ "https://Stackoverflow.com/questions/17440152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217820/" ]
Well, you will want to use a function which loads the images at a certain point, so you might as well try to understand onLoad. It's not that hard to grasp. "onload" is a javascript event that occurs immediately after *something* is loaded. In other words: *onLoad* is like a javascript-native function which triggers when *something* is loaded. That *something* can be a window (eg: window.onload) or a document. What you want is the document onLoad event, as it triggers when your document is loaded. Let's provide you with a simple example... ``` <body onload="preloadMyImages();"> ``` This tells the browser "when you've loaded the document, run the *preloadMyImages* function". All you have to do is then use that function to load your images into the client's browser cache. ``` function preloadMyImages() { var imageList = [ "image.gif", "example/image.jpg", "whatever/image.png" ]; for(var i = 0; i < imageList.length; i++ ) { var imageObject = new Image(); imageObject.src = imageList[i]; } } ``` That practically wraps it up and provides you with a fully working example. Enjoy! **EDIT** Since - according to your comment - you are looking for some more help, I would like to point you to <https://stackoverflow.com/a/1038381/2432317> which (as one of many examples) shows how that you can (and probably should - depending on what you're planning do draw on your canvas) use img.onload too. Yet, as I stated in my comment: it will all depend on where you want to take it. The more you dive into Javascript coding, the more you will understand what's going on. There are several good (partly free) books out there explaining how to code Javascript, use the HTML5 canvas, create preloaders, animations, talk about scopes etc. A quick check at the big G of search engines turns up ample examples and tutorials too which will be helpfull for you. One of many examples: "[How To Draw Images Onto Your HTML5 Canvas](http://www.gaminglogy.com/tutorial/draw-image/)" which shows you preloading and looping an animation in a short and crisp tutorial. But please, don't expect us to code it all for you - it's not going to happen. This is one of the not-so-rare cases where *"learning by doing"* will actually make you smarter. And if you hit another problem on your way to your final goal, you can always post a new question related to that new problem.
try this ``` put this script in head section <script type="text/javascript"> function preload(arrayOfImages) { for(i = 0 ; i < arrayOfImages.length ; i++) { var img = new Image(); img.src = arrayOfImages[i]; } } preload(['img1.png','img2.png']); </script> ```
17,440,152
There are several questions about this in the forum, but I couldn't get a good answer for what I need. I am getting into Canvas and Javascript, and I want to preload some images as soon as the game opens. I made an example of the method I wanted to build (and didn't work) I have 3 files: "main.html" where the canvas (there is only one in this example) is declared and I try to load an image, "ImagePreloader.js" where I preload all the images and "Variables.js" where I have my variables. Could anyone please help me with this image preloading metod, or suggest me a viable one? I think the image is not loading because I am not using an onLoad() function, which I couldn't understand in the tutorials I read so far (I know how to apply it to an image, but not to an array of images) main.html: ``` <!DOCTYPE HTML> <html> <body> <canvas id="myCanvas" width="800" height="600"></canvas> <script type="text/javascript" src="Variables.js"></script> <script type="text/javascript" src="ImagePreloader.js"></script> <script> // Basic canvas info var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); // Draw one of the images. Somehow it doesn't work :( context.drawImage(imageArray[3], x, y, width, height); </script> </body> </html> ``` ImagePreloader.js ``` // This should preload the images in imageArray[i] with 0 <= i <= 5 ... right? function preloader() { for(var i=0; i<5; i++) { imageArray[i].src=images[i]; } } ``` Variables.js ``` // array of sources of my images images = new Array(); images[0]="img1.jpg" images[1]="img2.jpg" images[2]="img3.jpg" images[3]="img4.jpg" images[4]="img5.jpg" // Stuff to draw the image var x = 50; var y = 50; var width = 256; var height = 256; // Is this actually an array of images? imageArray = new Image(); ``` Thanks in advance!
2013/07/03
[ "https://Stackoverflow.com/questions/17440152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217820/" ]
Well, you will want to use a function which loads the images at a certain point, so you might as well try to understand onLoad. It's not that hard to grasp. "onload" is a javascript event that occurs immediately after *something* is loaded. In other words: *onLoad* is like a javascript-native function which triggers when *something* is loaded. That *something* can be a window (eg: window.onload) or a document. What you want is the document onLoad event, as it triggers when your document is loaded. Let's provide you with a simple example... ``` <body onload="preloadMyImages();"> ``` This tells the browser "when you've loaded the document, run the *preloadMyImages* function". All you have to do is then use that function to load your images into the client's browser cache. ``` function preloadMyImages() { var imageList = [ "image.gif", "example/image.jpg", "whatever/image.png" ]; for(var i = 0; i < imageList.length; i++ ) { var imageObject = new Image(); imageObject.src = imageList[i]; } } ``` That practically wraps it up and provides you with a fully working example. Enjoy! **EDIT** Since - according to your comment - you are looking for some more help, I would like to point you to <https://stackoverflow.com/a/1038381/2432317> which (as one of many examples) shows how that you can (and probably should - depending on what you're planning do draw on your canvas) use img.onload too. Yet, as I stated in my comment: it will all depend on where you want to take it. The more you dive into Javascript coding, the more you will understand what's going on. There are several good (partly free) books out there explaining how to code Javascript, use the HTML5 canvas, create preloaders, animations, talk about scopes etc. A quick check at the big G of search engines turns up ample examples and tutorials too which will be helpfull for you. One of many examples: "[How To Draw Images Onto Your HTML5 Canvas](http://www.gaminglogy.com/tutorial/draw-image/)" which shows you preloading and looping an animation in a short and crisp tutorial. But please, don't expect us to code it all for you - it's not going to happen. This is one of the not-so-rare cases where *"learning by doing"* will actually make you smarter. And if you hit another problem on your way to your final goal, you can always post a new question related to that new problem.
You have to make sure these 5 images are loaded (downloaded doesnt alwaysmean its loaded and ready to use, only onload guarantees that image is ready to use) before you use it. So add onload for the images, then count from the onload function and trigger the draw after 5 of them are loaded ``` function prefetchImages(sources){ var images = []; var loadedImages = 0; var numImages = sources.length; for (var i=0; i < numImages; i++) { images[i] = new Image(); images[i].onload = function(){ if (++loadedImages >= numImages) { //ready draw with my images now drawThePainting(); } }; images[i].src = sources[i]; //bind onload before setting src bug in some chrome versions } }; prefetchImages(["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]); function drawThePainting(){ // Basic canvas info var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); // Draw one of the images. Somehow it doesn't work :( context.drawImage(imageArray[3], x, y, width, height); } ```
68,127
Firefox 3.5 adds support for OGG and WAV playback using the HTML5 `<audio>` element. Great! However, it also defaults to opening a media player in the browser whenever I follow a link to OGG or WAV. It's not a plugin, it seems to be implemented as a simple HTML wrapper containing `<audio>`, but I still don't like it. I want to get a prompt to open/download/whatever like with any other media file. I've set the action for OGG and WAV to ‘Always ask’ in the ‘Applications’ tab on Preferences, but this is ignored. I can't see anything obvious in `about:config`. Except for `media.ogg.enabled`, but that just disables format support so I still get an HTML player for OGG, just one that doesn't work. Gah! Google's not helping today; do any superusers have a solution, before I go bugging the zilla?
2009/11/09
[ "https://superuser.com/questions/68127", "https://superuser.com", "https://superuser.com/users/10551/" ]
Go to Options>Applications in firefox to change you preferences on this.
OK, it doesn't seem to be possible currently. Discussion in [bug 498523](https://bugzilla.mozilla.org/show_bug.cgi?id=498523).
2,420,135
Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript: ``` <div class="nav" style="float: right;"> <ul> <li style="margin-right: 0px;" > <a id="nav-ask" href="/questions/ask">Ask Question</a> </li> </ul> </div> ``` I can't hide the `nav` class because other page elements use it. Can I hide the link element via the `nav-ask` id?
2010/03/10
[ "https://Stackoverflow.com/questions/2420135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
I found that the following code, when inserted into the site's footer, worked well enough: ``` <script type="text/javascript"> $("#nav-ask").remove(); </script> ``` This may or may not require jquery. The site I'm editing has jquery, but unfortunately I'm no javascripter, so I only have a limited knowledge of what's going on here, and the requirements of this code snippet...
you can use CSS selectors ``` a[href="/questions/ask"] { display:none; } ```
2,420,135
Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript: ``` <div class="nav" style="float: right;"> <ul> <li style="margin-right: 0px;" > <a id="nav-ask" href="/questions/ask">Ask Question</a> </li> </ul> </div> ``` I can't hide the `nav` class because other page elements use it. Can I hide the link element via the `nav-ask` id?
2010/03/10
[ "https://Stackoverflow.com/questions/2420135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
If you want to do it via javascript rather than CSS you can use: ``` var link = document.getElementById('nav-ask'); link.style.display = 'none'; //or link.style.visibility = 'hidden'; ``` depending on what you want to do.
``` <style type="text/css"> #nav-ask{ display:none; } </style> ```
2,420,135
Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript: ``` <div class="nav" style="float: right;"> <ul> <li style="margin-right: 0px;" > <a id="nav-ask" href="/questions/ask">Ask Question</a> </li> </ul> </div> ``` I can't hide the `nav` class because other page elements use it. Can I hide the link element via the `nav-ask` id?
2010/03/10
[ "https://Stackoverflow.com/questions/2420135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
If you want to do it via javascript rather than CSS you can use: ``` var link = document.getElementById('nav-ask'); link.style.display = 'none'; //or link.style.visibility = 'hidden'; ``` depending on what you want to do.
I found that the following code, when inserted into the site's footer, worked well enough: ``` <script type="text/javascript"> $("#nav-ask").remove(); </script> ``` This may or may not require jquery. The site I'm editing has jquery, but unfortunately I'm no javascripter, so I only have a limited knowledge of what's going on here, and the requirements of this code snippet...
2,420,135
Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript: ``` <div class="nav" style="float: right;"> <ul> <li style="margin-right: 0px;" > <a id="nav-ask" href="/questions/ask">Ask Question</a> </li> </ul> </div> ``` I can't hide the `nav` class because other page elements use it. Can I hide the link element via the `nav-ask` id?
2010/03/10
[ "https://Stackoverflow.com/questions/2420135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
``` <style type="text/css"> #nav-ask{ display:none; } </style> ```
I found that the following code, when inserted into the site's footer, worked well enough: ``` <script type="text/javascript"> $("#nav-ask").remove(); </script> ``` This may or may not require jquery. The site I'm editing has jquery, but unfortunately I'm no javascripter, so I only have a limited knowledge of what's going on here, and the requirements of this code snippet...
2,420,135
Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript: ``` <div class="nav" style="float: right;"> <ul> <li style="margin-right: 0px;" > <a id="nav-ask" href="/questions/ask">Ask Question</a> </li> </ul> </div> ``` I can't hide the `nav` class because other page elements use it. Can I hide the link element via the `nav-ask` id?
2010/03/10
[ "https://Stackoverflow.com/questions/2420135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
If you want to do it via javascript rather than CSS you can use: ``` var link = document.getElementById('nav-ask'); link.style.display = 'none'; //or link.style.visibility = 'hidden'; ``` depending on what you want to do.
@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS ``` <style type="text/css"> #nav-ask{ display:none; } </style> ``` or if you already have a "hideMe" CSS Class: ``` <script type="text/javascript"> if(document.getElementById && document.createTextNode) { if(document.getElementById('nav-ask')) { document.getElementById('nav-ask').className='hideMe'; } } </script> ```
2,420,135
Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript: ``` <div class="nav" style="float: right;"> <ul> <li style="margin-right: 0px;" > <a id="nav-ask" href="/questions/ask">Ask Question</a> </li> </ul> </div> ``` I can't hide the `nav` class because other page elements use it. Can I hide the link element via the `nav-ask` id?
2010/03/10
[ "https://Stackoverflow.com/questions/2420135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS ``` <style type="text/css"> #nav-ask{ display:none; } </style> ``` or if you already have a "hideMe" CSS Class: ``` <script type="text/javascript"> if(document.getElementById && document.createTextNode) { if(document.getElementById('nav-ask')) { document.getElementById('nav-ask').className='hideMe'; } } </script> ```
you can use CSS selectors ``` a[href="/questions/ask"] { display:none; } ```
2,420,135
Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript: ``` <div class="nav" style="float: right;"> <ul> <li style="margin-right: 0px;" > <a id="nav-ask" href="/questions/ask">Ask Question</a> </li> </ul> </div> ``` I can't hide the `nav` class because other page elements use it. Can I hide the link element via the `nav-ask` id?
2010/03/10
[ "https://Stackoverflow.com/questions/2420135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
``` <style type="text/css"> #nav-ask{ display:none; } </style> ```
``` .nav ul li a#nav-ask{ display:none; } ```
2,420,135
Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript: ``` <div class="nav" style="float: right;"> <ul> <li style="margin-right: 0px;" > <a id="nav-ask" href="/questions/ask">Ask Question</a> </li> </ul> </div> ``` I can't hide the `nav` class because other page elements use it. Can I hide the link element via the `nav-ask` id?
2010/03/10
[ "https://Stackoverflow.com/questions/2420135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
``` .nav ul li a#nav-ask{ display:none; } ```
you can use CSS selectors ``` a[href="/questions/ask"] { display:none; } ```
2,420,135
Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript: ``` <div class="nav" style="float: right;"> <ul> <li style="margin-right: 0px;" > <a id="nav-ask" href="/questions/ask">Ask Question</a> </li> </ul> </div> ``` I can't hide the `nav` class because other page elements use it. Can I hide the link element via the `nav-ask` id?
2010/03/10
[ "https://Stackoverflow.com/questions/2420135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
``` .nav ul li a#nav-ask{ display:none; } ```
I found that the following code, when inserted into the site's footer, worked well enough: ``` <script type="text/javascript"> $("#nav-ask").remove(); </script> ``` This may or may not require jquery. The site I'm editing has jquery, but unfortunately I'm no javascripter, so I only have a limited knowledge of what's going on here, and the requirements of this code snippet...
2,420,135
Hopefully there's a quick and dirty way to remove the "Ask Question" (or hide it) from a page where I can only add CSS and Javascript: ``` <div class="nav" style="float: right;"> <ul> <li style="margin-right: 0px;" > <a id="nav-ask" href="/questions/ask">Ask Question</a> </li> </ul> </div> ``` I can't hide the `nav` class because other page elements use it. Can I hide the link element via the `nav-ask` id?
2010/03/10
[ "https://Stackoverflow.com/questions/2420135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
``` <style type="text/css"> #nav-ask{ display:none; } </style> ```
you can use CSS selectors ``` a[href="/questions/ask"] { display:none; } ```
27,635,255
Upon running the WebView in ICS, I'm encountering such problem, a white screen always flickering before the WebView runs. I don't know if it is normal or not. If yes, are there any other way to remove it? Thanks. Here are my codes. WebViewSet.java ``` public class WebViewSet { public static void settings(WebView view) { WebSettings s = view.getSettings(); s.setJavaScriptEnabled(true); s.setPluginState(PluginState.ON); s.setTextZoom(100); } } ``` Home.java - Where in my I call my WebView ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Layout View rootView = inflater.inflate(R.layout.fragment_home, container, false); // webview mWebView = (WebView)rootView.findViewById(R.id.home_webview); WebViewSet.settings(mWebView); mWebView.loadUrl("file:///android_asset/blover.swf"); return rootView; } } ```
2014/12/24
[ "https://Stackoverflow.com/questions/27635255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4371785/" ]
Your #header is 0px x 0px big. Give it a size (width and height) and you should be good.
Its because of Height and Width. Specify height and width. **height: auto; width: 100%;** and also indicate **no-repeat**.
27,635,255
Upon running the WebView in ICS, I'm encountering such problem, a white screen always flickering before the WebView runs. I don't know if it is normal or not. If yes, are there any other way to remove it? Thanks. Here are my codes. WebViewSet.java ``` public class WebViewSet { public static void settings(WebView view) { WebSettings s = view.getSettings(); s.setJavaScriptEnabled(true); s.setPluginState(PluginState.ON); s.setTextZoom(100); } } ``` Home.java - Where in my I call my WebView ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Layout View rootView = inflater.inflate(R.layout.fragment_home, container, false); // webview mWebView = (WebView)rootView.findViewById(R.id.home_webview); WebViewSet.settings(mWebView); mWebView.loadUrl("file:///android_asset/blover.swf"); return rootView; } } ```
2014/12/24
[ "https://Stackoverflow.com/questions/27635255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4371785/" ]
Your #header is 0px x 0px big. Give it a size (width and height) and you should be good.
please give the height like ``` #header{height: 100px;} ```
27,635,255
Upon running the WebView in ICS, I'm encountering such problem, a white screen always flickering before the WebView runs. I don't know if it is normal or not. If yes, are there any other way to remove it? Thanks. Here are my codes. WebViewSet.java ``` public class WebViewSet { public static void settings(WebView view) { WebSettings s = view.getSettings(); s.setJavaScriptEnabled(true); s.setPluginState(PluginState.ON); s.setTextZoom(100); } } ``` Home.java - Where in my I call my WebView ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Layout View rootView = inflater.inflate(R.layout.fragment_home, container, false); // webview mWebView = (WebView)rootView.findViewById(R.id.home_webview); WebViewSet.settings(mWebView); mWebView.loadUrl("file:///android_asset/blover.swf"); return rootView; } } ```
2014/12/24
[ "https://Stackoverflow.com/questions/27635255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4371785/" ]
you forget to set height and width., ``` #header{ background-image: url('bg.jpg'); background-size: cover; padding: 0px; margin: 0px; border: 0px; width:100%;/* what size you need to add here */ heigth:50%; } ```
Its because of Height and Width. Specify height and width. **height: auto; width: 100%;** and also indicate **no-repeat**.
27,635,255
Upon running the WebView in ICS, I'm encountering such problem, a white screen always flickering before the WebView runs. I don't know if it is normal or not. If yes, are there any other way to remove it? Thanks. Here are my codes. WebViewSet.java ``` public class WebViewSet { public static void settings(WebView view) { WebSettings s = view.getSettings(); s.setJavaScriptEnabled(true); s.setPluginState(PluginState.ON); s.setTextZoom(100); } } ``` Home.java - Where in my I call my WebView ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Layout View rootView = inflater.inflate(R.layout.fragment_home, container, false); // webview mWebView = (WebView)rootView.findViewById(R.id.home_webview); WebViewSet.settings(mWebView); mWebView.loadUrl("file:///android_asset/blover.swf"); return rootView; } } ```
2014/12/24
[ "https://Stackoverflow.com/questions/27635255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4371785/" ]
you forget to set height and width., ``` #header{ background-image: url('bg.jpg'); background-size: cover; padding: 0px; margin: 0px; border: 0px; width:100%;/* what size you need to add here */ heigth:50%; } ```
please give the height like ``` #header{height: 100px;} ```
27,635,255
Upon running the WebView in ICS, I'm encountering such problem, a white screen always flickering before the WebView runs. I don't know if it is normal or not. If yes, are there any other way to remove it? Thanks. Here are my codes. WebViewSet.java ``` public class WebViewSet { public static void settings(WebView view) { WebSettings s = view.getSettings(); s.setJavaScriptEnabled(true); s.setPluginState(PluginState.ON); s.setTextZoom(100); } } ``` Home.java - Where in my I call my WebView ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Layout View rootView = inflater.inflate(R.layout.fragment_home, container, false); // webview mWebView = (WebView)rootView.findViewById(R.id.home_webview); WebViewSet.settings(mWebView); mWebView.loadUrl("file:///android_asset/blover.swf"); return rootView; } } ```
2014/12/24
[ "https://Stackoverflow.com/questions/27635255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4371785/" ]
Give your #header some height. It will work. Try this - ``` #header { background:url(image.jpg) no-repeat; height:50px; width:50px; } ```
Its because of Height and Width. Specify height and width. **height: auto; width: 100%;** and also indicate **no-repeat**.
27,635,255
Upon running the WebView in ICS, I'm encountering such problem, a white screen always flickering before the WebView runs. I don't know if it is normal or not. If yes, are there any other way to remove it? Thanks. Here are my codes. WebViewSet.java ``` public class WebViewSet { public static void settings(WebView view) { WebSettings s = view.getSettings(); s.setJavaScriptEnabled(true); s.setPluginState(PluginState.ON); s.setTextZoom(100); } } ``` Home.java - Where in my I call my WebView ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Layout View rootView = inflater.inflate(R.layout.fragment_home, container, false); // webview mWebView = (WebView)rootView.findViewById(R.id.home_webview); WebViewSet.settings(mWebView); mWebView.loadUrl("file:///android_asset/blover.swf"); return rootView; } } ```
2014/12/24
[ "https://Stackoverflow.com/questions/27635255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4371785/" ]
Give your #header some height. It will work. Try this - ``` #header { background:url(image.jpg) no-repeat; height:50px; width:50px; } ```
please give the height like ``` #header{height: 100px;} ```
202,120
I have server side log files written to various directories throughout the course of a week. I have the need to optionally compress, and archive these files to AWS. The script I have come up with takes a config file defining the include glob to look for matches, and offers optional removal of the source files once the process has completed. ``` python aws_bkup.py path/to/config.cfg ``` A sample config file can be found in the project directory: <https://github.com/twanas/aws-bkup> I would be most appreciative of feedback on the code style and areas it can be improved. ``` from __future__ import print_function import re import errno import os from glob import glob from os.path import join, basename, splitext from os import environ, remove from shutil import copy, rmtree from uuid import uuid4 import gzip from configparser import ConfigParser from datetime import date, timedelta import subprocess def gz(src, dest): """ Compresses a file to *.gz Parameters ---------- src: filepath of file to be compressesd dest: destination filepath """ filename = splitext(basename(src))[0] destpath = join(dest, '{}.gz'.format(filename)) blocksize = 1 << 16 #64kB with open(src) as f_in: f_out = gzip.open(destpath, 'wb') while True: block = f_in.read(blocksize) if block == '': break f_out.write(block) f_out.close() def aws_sync(src, dest): """ Synchronise a local directory to aws Parameters ---------- src: local path dest: aws bucket """ cmd = 'aws s3 sync {} {}'.format(src, dest) push = subprocess.call(cmd, shell=True) def today(): """ Returns a string format of today's date """ return date.today().strftime('%Y%m%d') def fwe(): """ Returns a string format of the next friday's date """ d = date.today() while d.weekday() != 4: d += timedelta(1) return d def regex_match(string, pattern): """ Returns if there is a match between parameter and regex pattern """ pattern = re.compile(pattern) return pattern.match(string) def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def aws_bkup(section, include, exclude, s3root, categorize_weekly=True, compress=True, remove_source=True): """ Transfers a backup of any local files matching the user's criteria to AWS. Parameters ---------- include: regex pattern to use for the file inclusion(s) exclude: regex pattern to use for the file exclusion(s) s3root: AWS root in which to send the backup categorize_weekly: switch between daily and weekly folder groupings compress: switch to compress outbound files to AWS """ folder = '{}'.format(fwe() if categorize_weekly else today()) tmp_root = join('/tmp', str(uuid4())) tmp_dir = join(tmp_root, folder) mkdir_p(tmp_dir) for file in glob(include): if regex_match(file, exclude): continue print('Processing: {}'.format(file)) if compress: gz(file, tmp_dir) else: copy(file, tmp_dir) if remove_source: remove(file) aws_dest = join(s3root, section) print('Syncronizing {} to s3'.format(tmp_dir)) aws_sync(tmp_root, aws_dest) if os.path.exists(tmp_root): rmtree(tmp_root) print('Done') if __name__ == "__main__": import sys args = sys.argv if len(args) < 2: print("Usage: python -m aws-bkup /path/to/config.cfg") sys.exit() config = ConfigParser() config.read(args[1]) environ['AWS_ACCESS_KEY_ID'] = config.get('aws', 'access_id') environ['AWS_SECRET_ACCESS_KEY'] = config.get('aws', 'secret_key') environ['AWS_DEFAULT_REGION'] = config.get('aws', 'region') for section in config.sections(): if section != 'aws': print('Starting {}'.format(section)) aws_bkup( section, config.get(section, 'include'), config.get(section, 'exclude'), config.get('aws', 's3root'), config.getboolean(section, 'categorize_weekly'), config.getboolean(section, 'compress'), config.getboolean(section, 'remove_source') ) ```
2018/08/21
[ "https://codereview.stackexchange.com/questions/202120", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/177775/" ]
After a quick read-through, I’ve spotted two items: --- `with` not used for `f_out` --------------------------- The code: ``` with open(src) as f_in: f_out = gzip.open(destpath, 'wb') #... f_out.close() ``` should be replaced with: ``` with open(arc) as f_in, gzip.open(destpath, 'wb') as f_out: #... ``` --- Reg-ex pattern repeatedly compiled ---------------------------------- The function `regex_match()` takes a string and compiles it to a pattern, and then matches a string to that pattern. The same pattern string is repeatedly passed to `regex_match`. This string should be compiled to a pattern by the caller, and the resulting pattern reused for each match. This means the calls to `regex_match` could be replaced by `exclude_pattern.match(file)` --- Argument quoting ---------------- If `src` or `dest` contain spaces, this command may become confused. ``` cmd = 'aws s3 sync {} {}'.format(src, dest) push = subprocess.call(cmd, shell=True) ``` Since you are using the `shell=True` argument, it may also be a vector for arbitrary command injection! Instead of formatting the command into a string, with proper quoting, and requiring the `.call()` command to parse it, you can simply pass in an array of arguments to the call. No need to worry about spaces or proper escaping/quoting -- and arbitrary command injection becomes much harder: ``` cmd = ['aws', 's3', 'sync', src, dest] push = subprocess.call(cmd, shell=True) ``` Additional notes: `push` is neither returned or used. Also, while `subprocess.call(...)` is still acceptable, as of Python 3.5 `subprocess.run(...)` is the preferred interface.
Convert `while` to `for` ------------------------ Any time you see a function being called in a `while` loop with some sort of predicate for `break`, you can probably turn it into a `for` loop: ```py def gz(src, dest): """ Compresses a file to *.gz Parameters ---------- src: filepath of file to be compressesd dest: destination filepath """ filename = splitext(basename(src))[0] destpath = join(dest, '{}.gz'.format(filename)) blocksize = 1 << 16 #64kB # this can be altered to a for loop with open(src) as f_in: f_out = gzip.open(destpath, 'wb') while True: block = f_in.read(blocksize) if block == '': break f_out.write(block) f_out.close() ``` This function can be turned into: ```py from functools import partial def gz(src, dest): """ Compresses a file to *.gz Parameters ---------- src: filepath of file to be compressesd dest: destination filepath """ filename = splitext(basename(src))[0] destpath = join(dest, '{}.gz'.format(filename)) blocksize = 1 << 16 #64kB with open(src) as f_in, gzip.open(destpath, 'wb') as f_out: reader = partial(f_in.read, blocksize) for block in iter(reader, ''): f_out.write(block) ``` `iter` can take two arguments, a callable that takes no arguments and a sentinel value that signals that the loop should end. In order for `f_in.read` to take no args, you can bind `blocksize` to the `size` argument using `functools.partial`, returning a new function that takes no arguments. Continuing on with this function, you should be opening `src` in bytes mode so that you are writing bytes back: ```py def gz(src, dest): """ Compresses a file to *.gz Parameters ---------- src: filepath of file to be compressesd dest: destination filepath """ filename = splitext(basename(src))[0] # let's use an f-string here destpath = join(dest, f'{filename}.gz') blocksize = 1 << 16 #64kB # open src in rb mode with open(src, 'rb') as f_in, gzip.open(destpath, 'wb') as f_out: reader = partial(f_in.read, blocksize) # change your sentinel value to an empty byte string for block in iter(reader, b''): f_out.write(block) ``` `mkdir_p` --------- This could be covered by using the `os.makedirs` function with `exist_ok=True`. Any other `OSError` would then be raised accordingly: ```py def aws_bkup(section, include, exclude, s3root, categorize_weekly=True, compress=True, remove_source=True): """ Transfers a backup of any local files matching the user's criteria to AWS. Parameters ---------- include: regex pattern to use for the file inclusion(s) exclude: regex pattern to use for the file exclusion(s) s3root: AWS root in which to send the backup categorize_weekly: switch between daily and weekly folder groupings compress: switch to compress outbound files to AWS """ folder = '{}'.format(fwe() if categorize_weekly else today()) tmp_root = join('/tmp', str(uuid4())) tmp_dir = join(tmp_root, folder) os.makedirs(tmp_dir, exist_ok=True) ``` Date formatting --------------- You use two different date formats, one for `fwe` and one for `today`: ```py # Returns %Y%m%d def today(): """ Returns a string format of today's date """ return date.today().strftime('%Y%m%d') # Returns %Y-%m-%d def fwe(): """ Returns a string format of the next friday's date """ d = date.today() while d.weekday() != 4: d += timedelta(1) return d ``` Keep it consistent. I would prefer the less cluttered format of `date`, so just collapse it into one function: ```py def get_date(weekly=False): d = date.today() if not weekly: return d while d.weekday() != 4: d += timedelta(days=1) return d def aws_bkup(section, include, exclude, s3root, categorize_weekly=True, compress=True, remove_source=True): # pass in your categorize_weekly variable as a param on the # get_date function folder = str(get_date(weekly=categorize_weekly)) ```
68,471,021
Is there a better way to convert a ListArray into a byte array in C#? The ListArray is coming from a dictionary object and contains a ListArray of objects where the underlying type is int. The only way I could get it to work was by looping thru the ListArray and individually inserting into the byte array. I was trying to get it to work with ToArray but I kept getting a cast error. ``` static void Main(string[] args) { int intLoop; byte[] arrByte; string strJson = "{\"Data\":[104,101,108,108,111,32,119,111,114,108,100]}"; Dictionary<string, object> dic = new Dictionary<string, object>(); JavaScriptSerializer js = new JavaScriptSerializer(); //deserialize json into dictionary object dic = js.Deserialize<Dictionary<string, object>>(strJson); //convert arraylist into byte array intLoop = 0; arrByte = new byte[((System.Collections.ArrayList)dic["Data"]).Count]; foreach (var s in (System.Collections.ArrayList)dic["Data"]) { arrByte[intLoop] = Convert.ToByte(s); intLoop++; } } ```
2021/07/21
[ "https://Stackoverflow.com/questions/68471021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11968149/" ]
There's nothing wrong with your approach, but, if you prefer, you could use a LINQ one-liner instead: ``` ArrayList data = ...; var arrByte = data.Cast<int>().Select(i => (byte)i).ToArray(); ``` Note: `Cast<int>()` is required because your code uses the legacy `ArrayList` type. If your source type already implements `IEnumerable<int>` (for example, a `List<int>` or an `int[]`), you can skip this step.
The problem is that int[] and byte[] are the same when all numbers are less 255. If one of the numbers is large than 255 it will throw exeption during conversion. If you need byte[] ``` string strJson = "{\"Data\":[104,101,108,108,111,32,119,111,114,108,100]}"; var byteArray = JsonConvert.DeserializeObject<RootData>(strJson); ``` class ``` public class RootData { public byte[] Data {get; set;} } ```
68,471,021
Is there a better way to convert a ListArray into a byte array in C#? The ListArray is coming from a dictionary object and contains a ListArray of objects where the underlying type is int. The only way I could get it to work was by looping thru the ListArray and individually inserting into the byte array. I was trying to get it to work with ToArray but I kept getting a cast error. ``` static void Main(string[] args) { int intLoop; byte[] arrByte; string strJson = "{\"Data\":[104,101,108,108,111,32,119,111,114,108,100]}"; Dictionary<string, object> dic = new Dictionary<string, object>(); JavaScriptSerializer js = new JavaScriptSerializer(); //deserialize json into dictionary object dic = js.Deserialize<Dictionary<string, object>>(strJson); //convert arraylist into byte array intLoop = 0; arrByte = new byte[((System.Collections.ArrayList)dic["Data"]).Count]; foreach (var s in (System.Collections.ArrayList)dic["Data"]) { arrByte[intLoop] = Convert.ToByte(s); intLoop++; } } ```
2021/07/21
[ "https://Stackoverflow.com/questions/68471021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11968149/" ]
There's nothing wrong with your approach, but, if you prefer, you could use a LINQ one-liner instead: ``` ArrayList data = ...; var arrByte = data.Cast<int>().Select(i => (byte)i).ToArray(); ``` Note: `Cast<int>()` is required because your code uses the legacy `ArrayList` type. If your source type already implements `IEnumerable<int>` (for example, a `List<int>` or an `int[]`), you can skip this step.
That's how I would write it (using c# 9 language features) ``` public record MyDto(IEnumerable<int> Data); var json = "{\"Data\":[104,101,108,108,111,32,119,111,114,108,100]}"; var document = JsonSerializer.Deserialize<MyDto>(json); var bytes = document?.Data .Select(i => (byte) i) .ToArray(); ``` 1. Create data structure to represent the input data 2. Parse it with `System.Text.Json` JsonSerializer (the new standard json serializer) 3. Convert it with LINQ
68,471,021
Is there a better way to convert a ListArray into a byte array in C#? The ListArray is coming from a dictionary object and contains a ListArray of objects where the underlying type is int. The only way I could get it to work was by looping thru the ListArray and individually inserting into the byte array. I was trying to get it to work with ToArray but I kept getting a cast error. ``` static void Main(string[] args) { int intLoop; byte[] arrByte; string strJson = "{\"Data\":[104,101,108,108,111,32,119,111,114,108,100]}"; Dictionary<string, object> dic = new Dictionary<string, object>(); JavaScriptSerializer js = new JavaScriptSerializer(); //deserialize json into dictionary object dic = js.Deserialize<Dictionary<string, object>>(strJson); //convert arraylist into byte array intLoop = 0; arrByte = new byte[((System.Collections.ArrayList)dic["Data"]).Count]; foreach (var s in (System.Collections.ArrayList)dic["Data"]) { arrByte[intLoop] = Convert.ToByte(s); intLoop++; } } ```
2021/07/21
[ "https://Stackoverflow.com/questions/68471021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11968149/" ]
The problem is that int[] and byte[] are the same when all numbers are less 255. If one of the numbers is large than 255 it will throw exeption during conversion. If you need byte[] ``` string strJson = "{\"Data\":[104,101,108,108,111,32,119,111,114,108,100]}"; var byteArray = JsonConvert.DeserializeObject<RootData>(strJson); ``` class ``` public class RootData { public byte[] Data {get; set;} } ```
That's how I would write it (using c# 9 language features) ``` public record MyDto(IEnumerable<int> Data); var json = "{\"Data\":[104,101,108,108,111,32,119,111,114,108,100]}"; var document = JsonSerializer.Deserialize<MyDto>(json); var bytes = document?.Data .Select(i => (byte) i) .ToArray(); ``` 1. Create data structure to represent the input data 2. Parse it with `System.Text.Json` JsonSerializer (the new standard json serializer) 3. Convert it with LINQ
18,066,204
I am setting up tests that use Jasmine and Karma to test my JavaScript. Karma runs in Node.js and starts a Chrome browser. I keep getting and error "Chrome 28.0 (Windows) ERROR Script error. at :0" Upon tracing through things I realized that some of the objects I create in my code make AJAX cross-domain AJAX calls and when they do that my Karma tests crash. I do not need these AJAX calls to succeed for my tests to succeed, however I would like them to not crash my Karma tests. I am open to solve this issue in a wide variety of ways. Can I change my Karma/Chrome settings so the AJAX will not fail catastrophically? Can I override XMLHttpRequest so either the offending requests aren't made or no requests are made? Notes: The test does not fail in the debug window even though that it is also making cross domain AJAX requests. I have am using a testing library that overrides jQuery's AJAX. However, I have another library that is still making AJAX requests.
2013/08/05
[ "https://Stackoverflow.com/questions/18066204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/953068/" ]
I was having a similar issue with CORS and AJAX, then I followed jhamm suggestion. Then, I got "ERROR [launcher]: Cannot start chrome\_without\_security Can not find the binary chrome\_without\_security". Since my issue was with CORS, I found out [here](https://github.com/karma-runner/karma-chrome-launcher/issues/154) that I should add the new browser type to the browsers list on karma.conf.js. I added it like this: ``` browsers: ['Chrome_without_security'], customLaunchers:{ Chrome_without_security:{ base: 'Chrome', flags: ['--disable-web-security'] } } ``` After that, and since I only have this one browser, I don't have to use ``` karma start --browsers Chrome_without_security ``` I can just type ``` karma start ``` And it will call for the HeadlessChrome without security, meaning it won't find any problems with CORS.
If it really is a CORS issue, you can disable the cross-domain by starting karma like this: ``` karma start --browsers chrome_without_security ``` Chrome has the ability to be started with the security disabled ``` open -a Google\ Chrome --args --disable-web-security ``` And the Karma team just takes advantage of it.
31,152,566
I need to create a menu of regions hat display two lists: a `<select>` for the region and another `<select>` for the available municipalities of that region. For this, I have a `<form>` and I update the municipalities through JavaScript. I have problems assigning the municipalities as `<option>`s of the second `<select>`. The option matrix of the menu doesn't accept the assignment of the values. Here's the code. HTML. ``` <html> <head> <title> P&aacute;gina men&uacute; principal. </title> <?!= incluirArchivo('ArchivoJS'); ?> </head> <body onLoad = "preparar();"> <form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on"> <select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();"> <option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option> <option value="0">Antioquia</option> <option value="1">Atl&aacute;ntico</option> </select> <select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled> <option value=0>TODOS LOS MUNICIPIOS</option> </select> </form> </body> </html> ``` Javascript code: ``` <script lenguage="javascript"> function preparar() { document.forms[0].elements.numeroLicencia.focus(); document.forms[0].elements.nombreConductor.disabled = true; document.forms[0].elements.botonEnviar.disabled = true; document.forms[0].elements.botonActualizar.disabled = true; } function municipiosDepartamento() { var arregloMunicipiosDepartamento = new Array(); var posicionMunicipio = document.forms[0].elements.menuDepartamento.value; arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio); if(document.forms[0].elements.menuMunicipios.options.length > 1){ var totalMunicipios = document.forms[0].elements.menuMunicipios.length; for (var i = 1; i < totalMunicipios; i ++){ document.forms[0].elements.menuMunicipios.options[1] = null; } } if(document.forms[0].elements.menuDepartamento.value === "x"){ document.forms[0].elements.menuMunicipios.selectedItem = 0; document.forms[0].elements.menuMunicipios.disabled = true; } else { document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length; for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) { var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1)); ***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text; document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;*** } document.forms[0].elements.menuMunicipios.disabled = false; } } function municipiosColombia(posicion) { var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array(); antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"]; atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"]; arregloTodos = [antioquia, atlantico]; arregloMunicipiosDepartamento=arregloTodos[posicion]; return arregloMunicipiosDepartamento; } </script> ``` I have highlighted the work that doesn't work.
2015/07/01
[ "https://Stackoverflow.com/questions/31152566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4724488/" ]
Try this: ``` var results = taskDataList .Where(td => td.TaskParams != null) .Where(td => td.TaskParams.Any(kvp => kvp.Key != null && kvp.Key.ToString().Equals("LOCATION", StringComparison.OrdinalIgnoreCase) && kvp.Value != null && kvp.Value.Equals("Stockroom")) && td.TaskParams.Any(kvp => kvp.Key != null && kvp.Key.ToString().Equals("ITERATION", StringComparison.OrdinalIgnoreCase) && kvp.Value != null && kvp.Value.Equals(1))) .ToList(); ``` I have tested this code against this data: ``` IList<ITaskData> taskDataList = new List<ITaskData>(); var taskData = new TaskData(); taskData.TaskParams.Add(new KeyValuePair<object, object>("Location", "Stockroom")); taskData.TaskParams.Add(new KeyValuePair<object, object>("Location", "Salesfloor")); taskData.TaskParams.Add(new KeyValuePair<object, object>("Iteration", 1)); taskData.TaskParams.Add(new KeyValuePair<object, object>("Iteration", 2)); taskDataList.Add(taskData); ```
It should be something like this: ``` var tasks = taskDataList.Where( i => i.TaskParams.Any(x => x.Key == "Location" && x.Value.Contains("Stockroom")) && i.TaskParams.Any(x => x.Key == "Iteration" && x.Values.Contains(2))); ``` The above code is just to explain the logic. You need to cast the object to the right type (if you know them) or user another comparison method.
31,152,566
I need to create a menu of regions hat display two lists: a `<select>` for the region and another `<select>` for the available municipalities of that region. For this, I have a `<form>` and I update the municipalities through JavaScript. I have problems assigning the municipalities as `<option>`s of the second `<select>`. The option matrix of the menu doesn't accept the assignment of the values. Here's the code. HTML. ``` <html> <head> <title> P&aacute;gina men&uacute; principal. </title> <?!= incluirArchivo('ArchivoJS'); ?> </head> <body onLoad = "preparar();"> <form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on"> <select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();"> <option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option> <option value="0">Antioquia</option> <option value="1">Atl&aacute;ntico</option> </select> <select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled> <option value=0>TODOS LOS MUNICIPIOS</option> </select> </form> </body> </html> ``` Javascript code: ``` <script lenguage="javascript"> function preparar() { document.forms[0].elements.numeroLicencia.focus(); document.forms[0].elements.nombreConductor.disabled = true; document.forms[0].elements.botonEnviar.disabled = true; document.forms[0].elements.botonActualizar.disabled = true; } function municipiosDepartamento() { var arregloMunicipiosDepartamento = new Array(); var posicionMunicipio = document.forms[0].elements.menuDepartamento.value; arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio); if(document.forms[0].elements.menuMunicipios.options.length > 1){ var totalMunicipios = document.forms[0].elements.menuMunicipios.length; for (var i = 1; i < totalMunicipios; i ++){ document.forms[0].elements.menuMunicipios.options[1] = null; } } if(document.forms[0].elements.menuDepartamento.value === "x"){ document.forms[0].elements.menuMunicipios.selectedItem = 0; document.forms[0].elements.menuMunicipios.disabled = true; } else { document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length; for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) { var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1)); ***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text; document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;*** } document.forms[0].elements.menuMunicipios.disabled = false; } } function municipiosColombia(posicion) { var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array(); antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"]; atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"]; arregloTodos = [antioquia, atlantico]; arregloMunicipiosDepartamento=arregloTodos[posicion]; return arregloMunicipiosDepartamento; } </script> ``` I have highlighted the work that doesn't work.
2015/07/01
[ "https://Stackoverflow.com/questions/31152566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4724488/" ]
If you insist on using `object` in `KeyValuePair`, then your example would look like this: ``` IList<ITaskData> taskDataList = new List<ITaskData> { new ITaskData { TaskParams = new List<KeyValuePair<object,object>> { new KeyValuePair<object, object>("Location", "Stockroom"), new KeyValuePair<object, object>("Location", "Salesfloor"), new KeyValuePair<object, object>("Iteration", 1), new KeyValuePair<object, object>("Iteration", 2) } }, new ITaskData { TaskParams = new List<KeyValuePair<object,object>> { new KeyValuePair<object, object>("Location", "Stockroom"), new KeyValuePair<object, object>("Location", "Salesfloor"), new KeyValuePair<object, object>("Iteration", 101), new KeyValuePair<object, object>("Iteration", 2) } } }; var result = taskDataList.Where(td => td.TaskParams.Any(tp => ((string)tp.Key == "Location") && ((string)tp.Value == "Stockroom")) && td.TaskParams.Any(tp => (string)tp.Key == "Iteration" && (int)tp.Value == 1) ); ``` As you can see, you need to cast `object` to an exact type, so this approach is very error-prone, and can easily cause run-time exceptions if you key,value collection will have items with type different from what you expect. If you need to filter by location or iteration, define them as properties inside your TaskParams class, then your query will become more clear, strongly typed and less error-prone. See the example below: ``` public class TaskParamsType { public IList<string> Locations; public IList<int> Iterations; } public class ITaskDataNew { public TaskParamsType TaskParams { get; set; } } var result = taskDataList.Where(td => td.TaskParams.Locations.Contains("Stockroom") && td.TaskParams.Iterations.Contains(1) ); ```
It should be something like this: ``` var tasks = taskDataList.Where( i => i.TaskParams.Any(x => x.Key == "Location" && x.Value.Contains("Stockroom")) && i.TaskParams.Any(x => x.Key == "Iteration" && x.Values.Contains(2))); ``` The above code is just to explain the logic. You need to cast the object to the right type (if you know them) or user another comparison method.
31,152,566
I need to create a menu of regions hat display two lists: a `<select>` for the region and another `<select>` for the available municipalities of that region. For this, I have a `<form>` and I update the municipalities through JavaScript. I have problems assigning the municipalities as `<option>`s of the second `<select>`. The option matrix of the menu doesn't accept the assignment of the values. Here's the code. HTML. ``` <html> <head> <title> P&aacute;gina men&uacute; principal. </title> <?!= incluirArchivo('ArchivoJS'); ?> </head> <body onLoad = "preparar();"> <form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on"> <select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();"> <option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option> <option value="0">Antioquia</option> <option value="1">Atl&aacute;ntico</option> </select> <select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled> <option value=0>TODOS LOS MUNICIPIOS</option> </select> </form> </body> </html> ``` Javascript code: ``` <script lenguage="javascript"> function preparar() { document.forms[0].elements.numeroLicencia.focus(); document.forms[0].elements.nombreConductor.disabled = true; document.forms[0].elements.botonEnviar.disabled = true; document.forms[0].elements.botonActualizar.disabled = true; } function municipiosDepartamento() { var arregloMunicipiosDepartamento = new Array(); var posicionMunicipio = document.forms[0].elements.menuDepartamento.value; arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio); if(document.forms[0].elements.menuMunicipios.options.length > 1){ var totalMunicipios = document.forms[0].elements.menuMunicipios.length; for (var i = 1; i < totalMunicipios; i ++){ document.forms[0].elements.menuMunicipios.options[1] = null; } } if(document.forms[0].elements.menuDepartamento.value === "x"){ document.forms[0].elements.menuMunicipios.selectedItem = 0; document.forms[0].elements.menuMunicipios.disabled = true; } else { document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length; for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) { var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1)); ***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text; document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;*** } document.forms[0].elements.menuMunicipios.disabled = false; } } function municipiosColombia(posicion) { var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array(); antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"]; atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"]; arregloTodos = [antioquia, atlantico]; arregloMunicipiosDepartamento=arregloTodos[posicion]; return arregloMunicipiosDepartamento; } </script> ``` I have highlighted the work that doesn't work.
2015/07/01
[ "https://Stackoverflow.com/questions/31152566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4724488/" ]
Try this: ``` var results = taskDataList .Where(td => td.TaskParams != null) .Where(td => td.TaskParams.Any(kvp => kvp.Key != null && kvp.Key.ToString().Equals("LOCATION", StringComparison.OrdinalIgnoreCase) && kvp.Value != null && kvp.Value.Equals("Stockroom")) && td.TaskParams.Any(kvp => kvp.Key != null && kvp.Key.ToString().Equals("ITERATION", StringComparison.OrdinalIgnoreCase) && kvp.Value != null && kvp.Value.Equals(1))) .ToList(); ``` I have tested this code against this data: ``` IList<ITaskData> taskDataList = new List<ITaskData>(); var taskData = new TaskData(); taskData.TaskParams.Add(new KeyValuePair<object, object>("Location", "Stockroom")); taskData.TaskParams.Add(new KeyValuePair<object, object>("Location", "Salesfloor")); taskData.TaskParams.Add(new KeyValuePair<object, object>("Iteration", 1)); taskData.TaskParams.Add(new KeyValuePair<object, object>("Iteration", 2)); taskDataList.Add(taskData); ```
Let's suppose you have the following code which returns a `List<KeyValuePair<object, object>>` matching the logical condition: ``` public class ITaskData { public List<KeyValuePair<object, object>> keyValuePairs { get; set; } } class Program { private static List<ITaskData> list = new List<ITaskData>(); private static void Main() { List<KeyValuePair<object, object>> result = new List<KeyValuePair<object, object>>(); foreach (var a in list) foreach (var b in a.keyValuePairs) if (b.Value.ToString().Contains("Stockroom")) result.Add(b); // Here I make .ToString().Contains("Stockroom") // You can add any required logics here } } ``` You can make it in LINQ: ``` List<KeyValuePair<object, object>> result = (from a in list from b in a.keyValuePairs where b.Value.ToString().Contains("Stockroom") select b) .ToList(); ``` Or in LINQ method chain: ``` List<KeyValuePair<object, object>> result = (list .SelectMany(a => a.keyValuePairs, (a, b) => new {a, b}) .Where(t => t.b.Value.ToString().Contains("Stockroom")) .Select(t => t.b) ).ToList(); ``` However, *in my private opinion*, in your case the solution with `foreach`s looks more elegant and readable. Of course, this code will throw a `NullReferenceException` as `keyValuePairs` are not initialized. I don't initialize it as it is an example and you have your own `ITaskData` class with proper initialization.
31,152,566
I need to create a menu of regions hat display two lists: a `<select>` for the region and another `<select>` for the available municipalities of that region. For this, I have a `<form>` and I update the municipalities through JavaScript. I have problems assigning the municipalities as `<option>`s of the second `<select>`. The option matrix of the menu doesn't accept the assignment of the values. Here's the code. HTML. ``` <html> <head> <title> P&aacute;gina men&uacute; principal. </title> <?!= incluirArchivo('ArchivoJS'); ?> </head> <body onLoad = "preparar();"> <form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on"> <select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();"> <option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option> <option value="0">Antioquia</option> <option value="1">Atl&aacute;ntico</option> </select> <select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled> <option value=0>TODOS LOS MUNICIPIOS</option> </select> </form> </body> </html> ``` Javascript code: ``` <script lenguage="javascript"> function preparar() { document.forms[0].elements.numeroLicencia.focus(); document.forms[0].elements.nombreConductor.disabled = true; document.forms[0].elements.botonEnviar.disabled = true; document.forms[0].elements.botonActualizar.disabled = true; } function municipiosDepartamento() { var arregloMunicipiosDepartamento = new Array(); var posicionMunicipio = document.forms[0].elements.menuDepartamento.value; arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio); if(document.forms[0].elements.menuMunicipios.options.length > 1){ var totalMunicipios = document.forms[0].elements.menuMunicipios.length; for (var i = 1; i < totalMunicipios; i ++){ document.forms[0].elements.menuMunicipios.options[1] = null; } } if(document.forms[0].elements.menuDepartamento.value === "x"){ document.forms[0].elements.menuMunicipios.selectedItem = 0; document.forms[0].elements.menuMunicipios.disabled = true; } else { document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length; for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) { var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1)); ***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text; document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;*** } document.forms[0].elements.menuMunicipios.disabled = false; } } function municipiosColombia(posicion) { var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array(); antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"]; atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"]; arregloTodos = [antioquia, atlantico]; arregloMunicipiosDepartamento=arregloTodos[posicion]; return arregloMunicipiosDepartamento; } </script> ``` I have highlighted the work that doesn't work.
2015/07/01
[ "https://Stackoverflow.com/questions/31152566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4724488/" ]
If you insist on using `object` in `KeyValuePair`, then your example would look like this: ``` IList<ITaskData> taskDataList = new List<ITaskData> { new ITaskData { TaskParams = new List<KeyValuePair<object,object>> { new KeyValuePair<object, object>("Location", "Stockroom"), new KeyValuePair<object, object>("Location", "Salesfloor"), new KeyValuePair<object, object>("Iteration", 1), new KeyValuePair<object, object>("Iteration", 2) } }, new ITaskData { TaskParams = new List<KeyValuePair<object,object>> { new KeyValuePair<object, object>("Location", "Stockroom"), new KeyValuePair<object, object>("Location", "Salesfloor"), new KeyValuePair<object, object>("Iteration", 101), new KeyValuePair<object, object>("Iteration", 2) } } }; var result = taskDataList.Where(td => td.TaskParams.Any(tp => ((string)tp.Key == "Location") && ((string)tp.Value == "Stockroom")) && td.TaskParams.Any(tp => (string)tp.Key == "Iteration" && (int)tp.Value == 1) ); ``` As you can see, you need to cast `object` to an exact type, so this approach is very error-prone, and can easily cause run-time exceptions if you key,value collection will have items with type different from what you expect. If you need to filter by location or iteration, define them as properties inside your TaskParams class, then your query will become more clear, strongly typed and less error-prone. See the example below: ``` public class TaskParamsType { public IList<string> Locations; public IList<int> Iterations; } public class ITaskDataNew { public TaskParamsType TaskParams { get; set; } } var result = taskDataList.Where(td => td.TaskParams.Locations.Contains("Stockroom") && td.TaskParams.Iterations.Contains(1) ); ```
Try this: ``` var results = taskDataList .Where(td => td.TaskParams != null) .Where(td => td.TaskParams.Any(kvp => kvp.Key != null && kvp.Key.ToString().Equals("LOCATION", StringComparison.OrdinalIgnoreCase) && kvp.Value != null && kvp.Value.Equals("Stockroom")) && td.TaskParams.Any(kvp => kvp.Key != null && kvp.Key.ToString().Equals("ITERATION", StringComparison.OrdinalIgnoreCase) && kvp.Value != null && kvp.Value.Equals(1))) .ToList(); ``` I have tested this code against this data: ``` IList<ITaskData> taskDataList = new List<ITaskData>(); var taskData = new TaskData(); taskData.TaskParams.Add(new KeyValuePair<object, object>("Location", "Stockroom")); taskData.TaskParams.Add(new KeyValuePair<object, object>("Location", "Salesfloor")); taskData.TaskParams.Add(new KeyValuePair<object, object>("Iteration", 1)); taskData.TaskParams.Add(new KeyValuePair<object, object>("Iteration", 2)); taskDataList.Add(taskData); ```
31,152,566
I need to create a menu of regions hat display two lists: a `<select>` for the region and another `<select>` for the available municipalities of that region. For this, I have a `<form>` and I update the municipalities through JavaScript. I have problems assigning the municipalities as `<option>`s of the second `<select>`. The option matrix of the menu doesn't accept the assignment of the values. Here's the code. HTML. ``` <html> <head> <title> P&aacute;gina men&uacute; principal. </title> <?!= incluirArchivo('ArchivoJS'); ?> </head> <body onLoad = "preparar();"> <form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on"> <select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();"> <option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option> <option value="0">Antioquia</option> <option value="1">Atl&aacute;ntico</option> </select> <select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled> <option value=0>TODOS LOS MUNICIPIOS</option> </select> </form> </body> </html> ``` Javascript code: ``` <script lenguage="javascript"> function preparar() { document.forms[0].elements.numeroLicencia.focus(); document.forms[0].elements.nombreConductor.disabled = true; document.forms[0].elements.botonEnviar.disabled = true; document.forms[0].elements.botonActualizar.disabled = true; } function municipiosDepartamento() { var arregloMunicipiosDepartamento = new Array(); var posicionMunicipio = document.forms[0].elements.menuDepartamento.value; arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio); if(document.forms[0].elements.menuMunicipios.options.length > 1){ var totalMunicipios = document.forms[0].elements.menuMunicipios.length; for (var i = 1; i < totalMunicipios; i ++){ document.forms[0].elements.menuMunicipios.options[1] = null; } } if(document.forms[0].elements.menuDepartamento.value === "x"){ document.forms[0].elements.menuMunicipios.selectedItem = 0; document.forms[0].elements.menuMunicipios.disabled = true; } else { document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length; for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) { var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1)); ***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text; document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;*** } document.forms[0].elements.menuMunicipios.disabled = false; } } function municipiosColombia(posicion) { var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array(); antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"]; atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"]; arregloTodos = [antioquia, atlantico]; arregloMunicipiosDepartamento=arregloTodos[posicion]; return arregloMunicipiosDepartamento; } </script> ``` I have highlighted the work that doesn't work.
2015/07/01
[ "https://Stackoverflow.com/questions/31152566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4724488/" ]
If you insist on using `object` in `KeyValuePair`, then your example would look like this: ``` IList<ITaskData> taskDataList = new List<ITaskData> { new ITaskData { TaskParams = new List<KeyValuePair<object,object>> { new KeyValuePair<object, object>("Location", "Stockroom"), new KeyValuePair<object, object>("Location", "Salesfloor"), new KeyValuePair<object, object>("Iteration", 1), new KeyValuePair<object, object>("Iteration", 2) } }, new ITaskData { TaskParams = new List<KeyValuePair<object,object>> { new KeyValuePair<object, object>("Location", "Stockroom"), new KeyValuePair<object, object>("Location", "Salesfloor"), new KeyValuePair<object, object>("Iteration", 101), new KeyValuePair<object, object>("Iteration", 2) } } }; var result = taskDataList.Where(td => td.TaskParams.Any(tp => ((string)tp.Key == "Location") && ((string)tp.Value == "Stockroom")) && td.TaskParams.Any(tp => (string)tp.Key == "Iteration" && (int)tp.Value == 1) ); ``` As you can see, you need to cast `object` to an exact type, so this approach is very error-prone, and can easily cause run-time exceptions if you key,value collection will have items with type different from what you expect. If you need to filter by location or iteration, define them as properties inside your TaskParams class, then your query will become more clear, strongly typed and less error-prone. See the example below: ``` public class TaskParamsType { public IList<string> Locations; public IList<int> Iterations; } public class ITaskDataNew { public TaskParamsType TaskParams { get; set; } } var result = taskDataList.Where(td => td.TaskParams.Locations.Contains("Stockroom") && td.TaskParams.Iterations.Contains(1) ); ```
Let's suppose you have the following code which returns a `List<KeyValuePair<object, object>>` matching the logical condition: ``` public class ITaskData { public List<KeyValuePair<object, object>> keyValuePairs { get; set; } } class Program { private static List<ITaskData> list = new List<ITaskData>(); private static void Main() { List<KeyValuePair<object, object>> result = new List<KeyValuePair<object, object>>(); foreach (var a in list) foreach (var b in a.keyValuePairs) if (b.Value.ToString().Contains("Stockroom")) result.Add(b); // Here I make .ToString().Contains("Stockroom") // You can add any required logics here } } ``` You can make it in LINQ: ``` List<KeyValuePair<object, object>> result = (from a in list from b in a.keyValuePairs where b.Value.ToString().Contains("Stockroom") select b) .ToList(); ``` Or in LINQ method chain: ``` List<KeyValuePair<object, object>> result = (list .SelectMany(a => a.keyValuePairs, (a, b) => new {a, b}) .Where(t => t.b.Value.ToString().Contains("Stockroom")) .Select(t => t.b) ).ToList(); ``` However, *in my private opinion*, in your case the solution with `foreach`s looks more elegant and readable. Of course, this code will throw a `NullReferenceException` as `keyValuePairs` are not initialized. I don't initialize it as it is an example and you have your own `ITaskData` class with proper initialization.
51,426,785
I am creating a drop-down menu for birth year with a JavaScript loop. ```js var year_list_start = 1938; var year_list_end = 2008; var year_options = ""; for (var y = year_list_start; y <= year_list_end; y++) { year_options += "<option name'" + y + "'>" + y + "</option>" } document.getElementById("year").innerHTML = year_options; ``` ```html <select id="year" name="year" required></select> ``` It works like a charm, except I would like the to be completely different (text/title) and not selectable. Something like "Select your birth year". I tried this and that, but couldn't achieve success.
2018/07/19
[ "https://Stackoverflow.com/questions/51426785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6692902/" ]
Just set it as the initial value of `year_options` with `selected` and `disabled` attributes present: ```js var year_list_start = 1938, year_list_end = 2008, year_options = '<option selected disabled>Select birth year:</option>'; for( var y = year_list_start; y <= year_list_end; y++ ) { year_options += "<option name'" + y + "'>" + y + "</option>" } document.getElementById("year").innerHTML = year_options; ``` ```html <select id="year" name="year" required></select> ```
```js var year_list_start = 1938; var year_list_end = 2008; var year_options = ""; for (var y = year_list_start; y <= year_list_end; y++) { year_options += "<option name'" + y + "'>" + y + "</option>" } document.getElementById("year").innerHTML += year_options; ``` ```html <select id="year" name="year" required> <option id="start" selected disabled>Please select birth year...</option> </select> ``` The `selected` option makes it so that it starts out selected, and the `disabled` option makes it so that you can't choose it as your answer.
51,426,785
I am creating a drop-down menu for birth year with a JavaScript loop. ```js var year_list_start = 1938; var year_list_end = 2008; var year_options = ""; for (var y = year_list_start; y <= year_list_end; y++) { year_options += "<option name'" + y + "'>" + y + "</option>" } document.getElementById("year").innerHTML = year_options; ``` ```html <select id="year" name="year" required></select> ``` It works like a charm, except I would like the to be completely different (text/title) and not selectable. Something like "Select your birth year". I tried this and that, but couldn't achieve success.
2018/07/19
[ "https://Stackoverflow.com/questions/51426785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6692902/" ]
Just set it as the initial value of `year_options` with `selected` and `disabled` attributes present: ```js var year_list_start = 1938, year_list_end = 2008, year_options = '<option selected disabled>Select birth year:</option>'; for( var y = year_list_start; y <= year_list_end; y++ ) { year_options += "<option name'" + y + "'>" + y + "</option>" } document.getElementById("year").innerHTML = year_options; ``` ```html <select id="year" name="year" required></select> ```
``` <select id="year" name="year" required> <option id="start" selected disabled>Select your birth year:</option> </select> ``` JSFiddle Link : <https://jsfiddle.net/Memorynotfound/13r1qfjb/>
51,426,785
I am creating a drop-down menu for birth year with a JavaScript loop. ```js var year_list_start = 1938; var year_list_end = 2008; var year_options = ""; for (var y = year_list_start; y <= year_list_end; y++) { year_options += "<option name'" + y + "'>" + y + "</option>" } document.getElementById("year").innerHTML = year_options; ``` ```html <select id="year" name="year" required></select> ``` It works like a charm, except I would like the to be completely different (text/title) and not selectable. Something like "Select your birth year". I tried this and that, but couldn't achieve success.
2018/07/19
[ "https://Stackoverflow.com/questions/51426785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6692902/" ]
``` <select id="year" name="year" required> <option id="start" selected disabled>Select your birth year:</option> </select> ``` JSFiddle Link : <https://jsfiddle.net/Memorynotfound/13r1qfjb/>
```js var year_list_start = 1938; var year_list_end = 2008; var year_options = ""; for (var y = year_list_start; y <= year_list_end; y++) { year_options += "<option name'" + y + "'>" + y + "</option>" } document.getElementById("year").innerHTML += year_options; ``` ```html <select id="year" name="year" required> <option id="start" selected disabled>Please select birth year...</option> </select> ``` The `selected` option makes it so that it starts out selected, and the `disabled` option makes it so that you can't choose it as your answer.
60,298,353
I´ve set the attribute "disable" to my save-button and my goal is it to enable it, when the user fill out all input fields from the form. For now it works, cause i set the `onkeyup="checkForm(this)"` in the last input field, but thats not a smart way to fix my problem. Heres my html code from my form: ``` div class="page" id="create__book__formular"> <div class="page__formular"> <h3 id="formualer__name">Formular</h3> <label>Name: <input type="text" placeholder="Name" id="title" > </label> <label>Autor: <input type="text" placeholder="Autor" id="autor"> </label> <label>ISBN: <input type="text" placeholder="ISBN" id="isbn"> </label> <label>Anazhl: <input type="text" placeholder="Anazhl" id="number"> </label> <label>Verlag: <input type="text" onkeyup="checkForm(this)" placeholder="Verlag" id="publishing"> </label> <button type="button" class="btn btn-success create__book__formular" id="save--button" disabled="disabled"> save </button> <button type=" button " class="btn btn-light create__book__formular" id="back--button"> back </button> </div> </div> ``` Heres my JavaScript code: ``` function checkForm(create__book__formular) { var bt = document.getElementById('save--button'); if (create__book__formular.value != '') { bt.disabled = false; } else { bt.disabled = true; } ``` } Thanks for your help!
2020/02/19
[ "https://Stackoverflow.com/questions/60298353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10391024/" ]
You need to define your loss like that in order to pass new parameters to it : ``` def custom_loss(sample_weights_): def example_loss(y_true, y_pred): return K.mean(K.sqrt(K.sum(K.pow(y_pred - y_true, 2), axis=-1)), axis=0) * sample_weights_ return example_loss ``` and call it like that : ``` model.compile("Adam", custom_loss(weights_tensor)) ```
You can rewrite your loss like this: ``` # Designing loss function that uses my pre-computed weights def example_loss(sample_weights_): def loss(y_true, y_pred): return K.mean(K.sqrt(K.sum(K.pow(y_pred - y_true, 2), axis=-1)), axis=0) * sample_weights_ ``` As you see, here we have a function that takes the sample weights, and returns another function (the actual loss) that has the sample weights embedded into it. You can use it as: ``` model.compile(optimizer="adam", loss=example_loss(weights_tensor)) ```
10,776
In Kubernetes, if I run a Service *Foo* on every Node, and also Service *Bar* on every Node, i.e. with `DaemonSets`. If a Pod from Service *Foo* needs to make a request to Service *Bar*, does Kubernetes networking magic optimise things so communication will be done within the same Node, i.e. without a external network call? Or will a random Pod *Bar* be picked meaning usually *Bar* will be on a different Node, so there will be a network hop? *Context to question*: I'm thinking to run `CoreDNS` as a `Daemonset`, because with the *cache* plugin, I'm hoping most DNS queries will not need to use the network as there will always be a CoreDNS Pod co-located within the same Node and most requests will be cached. Currently we only run 3 CoreDNS pods and we have 12 Nodes and we see some DNS failures at times of network traffic surges - particularly during a deployment when lot of logging is done, which have to be shipped across the network to ElasticSearch. --- In case specifics matter: * The CoreDNS service runs as `clusterIP: 172.20.0.10` * The services that use CoreDNS run as `type: NodePort` * The Kubernetes cluster is AWS EKS, v1.14.9. Networking is done with the AWS VPC CNI.
2020/02/12
[ "https://devops.stackexchange.com/questions/10776", "https://devops.stackexchange.com", "https://devops.stackexchange.com/users/19638/" ]
OK, there seems to be two problems here. --- ### SSH hanging after connection It's probably a problem on the client tty due to limitations of MinGW. In the past I've encountered that `ssh` was unable to `ioctl` the local `tty` because the lack of a control device (`pty`). I've used <https://github.com/rprichard/winpty> at the time, but I think that newer versions of MinGW/MinGW64 (the Posix layer installed to run bash by Git) have that covered because I didn't see that problem anymore. Summary: * Try upgrading git in your Windows client to the latest version (best option). * Try using `GIT CMD` instead of `GIT BASH`. * If you're not using the GIT components on Windows, try invoking `ssh` from a Command window. --- ### SSH not using your key I suspect that this is your problem: ``` debug1: identity file C:\\Users\\alexa\\.ssh\\id_rsa type -1 ``` In my PC, I get the following: ``` debug1: Reading configuration data /c/Users/xxxx/.ssh/config debug1: Reading configuration data /etc/ssh/ssh_config debug1: Connecting to xxx [192.168.0.1] port 22. debug1: Connection established. debug1: identity file /c/Users/xxxx/.ssh/id_rsa type 0 ``` As to why you're getting type `-1`, it *might* be a permissions problem. Make sure that all `C:\Users\alexa`, `C:\Users\alexa\.ssh` *and* `C:\Users\alexa\.ssh\id_rsa` have only permissions for `SYSTEM`, `alexa` and `Administrators`. Also, please notice that you're getting double backslashes in your log (e.g. `C:\\Users\\alexa\\.ssh\\id_rsa` instead of `C:\Users\alexa\.ssh\id_rsa`). I don't get double backslashes in mine.
Looks like you needs to install it another way. The errors message does give you a hint > > and setup Gitea under another user > > > The docs say > > Gitea should be run with a dedicated non-root system account on > UNIX-type systems. Note: Gitea manages the ~/.ssh/authorized\_keys > file. Running Gitea as a regular user could break that user’s ability > to log in. > > > Check here under the system requirements <https://docs.gitea.io/en-us/>
48,507,047
Is there any way to disable any incoming phone calls while running a web app in mobile devices such as tablet or smartphone(iOS, Android)? I have tried `<meta name="format-detection" content="telephone=no">` in the html5 but it does not work at all. And I don't know how to do this in JavaScript The reason is our projects is to run a web app on the mobile devices to play multiple audio clips to children. We don't want incoming phone calls to interrupt the audio clips. I appreciate any help!
2018/01/29
[ "https://Stackoverflow.com/questions/48507047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8662535/" ]
This is completely impossible on any non modified mobile phone, the operating systems for ios, android, blackberry, and windows phone all have zero apis for interacting with low level phone settings. You may be able to read if the phone is in airplane mode and not allow the application to continue until it is. If it's important to the operation. But it is up to the user not the application to decide if you should allow phone calls.
Before the parent hands over the phone to the child, remind the parent to put his phone on airplane mode so the child can work with the app in full concentration uninterrupted. This way you give the choice to to the parent instead of forcing unexpected behaviour.
20,087,256
I'm very new at PHP/CSS and programming in general for that matter. I want to change the formatting of a text in a textarea like one would do here, for example when adding the tags "Code Sample" for a highlighted text it will indent it or when setting it as bold it will bold it. The purpose of this would be preformatting an e-mail before sending it. I'm pretty sure this is a vast subject so I'm not looking for an explanation as much as a few links to some tutorials. I'm having trouble find some with Google since I don't even know what to search for exactly. Thank you.
2013/11/20
[ "https://Stackoverflow.com/questions/20087256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3011538/" ]
In Objective-C, `nil` is roughly analogous to `0`, `NULL` or `false`, but for object pointers. In an `if` statement, it will behave the same as one of the aforementioned scalar values. For example, the following two `if` statements should produce the same results: ``` NSNumber *balance = nil; if (!balance) { // do something if balance is nil } if (balance == nil) { // do something if balance is nil } ```
NSLog should return (null) (which probably is description for nil), not NULL in console. Your check should look like this: ``` if (!controller) { // do some stuff here } ```
20,087,256
I'm very new at PHP/CSS and programming in general for that matter. I want to change the formatting of a text in a textarea like one would do here, for example when adding the tags "Code Sample" for a highlighted text it will indent it or when setting it as bold it will bold it. The purpose of this would be preformatting an e-mail before sending it. I'm pretty sure this is a vast subject so I'm not looking for an explanation as much as a few links to some tutorials. I'm having trouble find some with Google since I don't even know what to search for exactly. Thank you.
2013/11/20
[ "https://Stackoverflow.com/questions/20087256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3011538/" ]
In Objective-C, `nil` is roughly analogous to `0`, `NULL` or `false`, but for object pointers. In an `if` statement, it will behave the same as one of the aforementioned scalar values. For example, the following two `if` statements should produce the same results: ``` NSNumber *balance = nil; if (!balance) { // do something if balance is nil } if (balance == nil) { // do something if balance is nil } ```
If `balance` is `nil` then it will be a pointer to `0x0`. That address is never used for a valid object. In C anything within an `if` that evaluates to zero is considered a negative response, anything that evaluates to non-zero is a positive response. Pointers evaluate to their address — exactly as if you cast them to an integral type. The `!` means "NOT". So the test is `if(address of balance is not zero)`.
20,087,256
I'm very new at PHP/CSS and programming in general for that matter. I want to change the formatting of a text in a textarea like one would do here, for example when adding the tags "Code Sample" for a highlighted text it will indent it or when setting it as bold it will bold it. The purpose of this would be preformatting an e-mail before sending it. I'm pretty sure this is a vast subject so I'm not looking for an explanation as much as a few links to some tutorials. I'm having trouble find some with Google since I don't even know what to search for exactly. Thank you.
2013/11/20
[ "https://Stackoverflow.com/questions/20087256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3011538/" ]
In Objective-C, `nil` is roughly analogous to `0`, `NULL` or `false`, but for object pointers. In an `if` statement, it will behave the same as one of the aforementioned scalar values. For example, the following two `if` statements should produce the same results: ``` NSNumber *balance = nil; if (!balance) { // do something if balance is nil } if (balance == nil) { // do something if balance is nil } ```
First you need to understand how `if` works. Basically, any non-zero value is treated as true and a zero value is treated as false. Something as simple as `if (10)` will be treated as true while `if (0)` is treated as false. Any expression evaluates to either a value of zero or a non-zero value. An object pointer is just a number - a memory address. A `nil` pointer is simply an address of 0. Any non-nil pointer will have a non-zero address. The `!` operator negates that state. A non-zero value will be treated as a zero value and visa-versa. So now combine all of this. ``` Foo *bar = nil; if (bar) // false since bar is nil (or zero) Foo *bar = [[Foo alloc] init]; // some non-nil value if (bar) // true since bar is non-zero Foo *bar = nil; if (!bar) // true since !bar mean "not bar" which is "not zero" which is "non-zero" Foo *bar = [[Foo alloc] init]; // some non-nil value if (!bar) // false since !bar mean "not bar" which is "not non-zero" which is "zero" ```
60,551,726
I wrote a web application in `ASP.NET` that exchange data with a `C#` program via `SignalR`. Here the relevant parts of my code. Of course if I forgot something important to address my issue, please ask in the comments. ASP.NET ------- **HubClientManager.cs** ``` using Microsoft.AspNet.SignalR.Client; using System; using System.Threading.Tasks; using System.Diagnostics; namespace MyProject { public class HubClientManager { public String GetServerURI() { return String.Concat("http://192.168.1.103", ":8080", "/signalr"); } public IHubProxy GetHub() { var hubConnection = new HubConnection(GetServerURI()); var hub = hubConnection.CreateHubProxy("liveHub"); try { var task = hubConnection.Start(); Task.WhenAll(task).Wait(); } catch (Exception e) { Debug.WriteLine(e); } return hub; } } } ``` **Index.cshtml** ``` <script src="@ViewBag.serverURI/hubs"></script> <script> $(function () { $.connection.hub.url = "@ViewBag.serverURI"; var hub = $.connection.liveHub; hub.client.orderStatus = function (opened, suspended, running, closed, cancelled) { $("#cntOpened").text(opened); $("#cntSuspended").text(suspended); $("#cntRunning").text(running); $("#cntClosed").text(closed); $("#cntCancelled").text(cancelled); }; $.connection.hub.logging = true; $.connection.hub.start().done(function () { }); $.connection.hub.error(function (error) { console.log('SignalR error: ' + error) }); }); </script> ``` **MachinesController.cs** ``` public class MachinesController : Controller { private HubClientManager _manager = new HubClientManager(); private IHubProxy _hub; public MachinesController() { _hub = _manager.GetHub(); } // GET: Machines public ActionResult Index() { ViewBag.serverURI = _manager.GetServerURI(); return View(...); } ... } ``` C# -- **Hub.cs** ``` namespace MyProject.Hubs { public class LiveHub : Hub { private readonly Erp _erp; public LiveHub(Erp erp) { _erp = erp; _erp.HubSendOrderStatus += Erp_HubSendOrderStatus; } private void Erp_HubSendOrderStatus(int arg1, int arg2, int arg3, int arg4, int arg5) { Clients.All.orderStatus(arg1, arg2, arg3, arg4, arg5); } ... public override Task OnConnected() { _erp.SendOrderStatus(); return base.OnConnected(); } } } ``` All works fine: I can show data int the web page coming from the `C#` application (from the `Erp` class, and send commands from the web page back to the engine application. Here I reported only a small set of functions, but they should be enough to understand what happens. Perhaps I'm blind and I cannot see my mistake looking at the examples. Anyway, every time I refresh a page in the browser or even I load another page of the same application (that of course shares the same `JavaScript` code above) I receive more and more `SignalR` messages! I mean, if the first time I receive the `orderStatus` message every 10 seconds, after a reload (or a page change) I receive 2 messages every 10 seconds. Another refresh and they become 3, and so on... after some time the whole system become unusable because it receives thousands of messages at once. I'm aware there's the `OnDisconnected()` callback but it seems it's called by the framework to *notify* a client has disconnected (and I'm not interested to know it). UPDATE ------ I cannot post the whole `Erp` class because it 3k+ lines long... anyway, most of the code does all other kind of stuff (database, field communications, etc...). Here the only functions involved with the hub: ``` public event Action<int, int, int, int, int> HubSendOrderStatus; public void SendOrderStatus() { using (MyDBContext context = new MyDBContext()) { var openedOrders = context.Orders.AsNoTracking().Count(x => x.State == OrderStates.Opened); var suspendedOrders = context.Orders.AsNoTracking().Count(x => x.State == OrderStates.Suspended); var runningOrders = context.Orders.AsNoTracking().Count(x => x.State == OrderStates.Running || x.State == OrderStates.Queued); var closedOrders = context.Orders.AsNoTracking().Count(x => x.State == OrderStates.Completed); var cancelledOrders = context.Orders.AsNoTracking().Count(x => x.State == OrderStates.Cancelled); HubSendOrderStatus?.Invoke(openedOrders, suspendedOrders, runningOrders, closedOrders, cancelledOrders); } } public async Task ImportOrdersAsync() { // doing something with I/O file SendOrderStatus(); } public void JobImportOrders() { Timer t = null; t = new Timer( async delegate (object state) { t.Dispose(); await ImportOrdersAsync(); JobImportOrders(); }, null, 10 * 1000, -1); } public Erp() { // initialize other stuff JobImportOrders(); } ``` EDIT ---- **AutofacContainer.cs** ``` public class AutofacContainer { public IContainer Container { get; set; } public AutofacContainer() { var builder = new ContainerBuilder(); var config = new HubConfiguration(); builder.RegisterHubs(Assembly.GetExecutingAssembly()).PropertiesAutowired(); builder.RegisterType<Erp>().PropertiesAutowired().InstancePerLifetimeScope(); Container = builder.Build(); config.Resolver = new AutofacDependencyResolver(Container); } } ```
2020/03/05
[ "https://Stackoverflow.com/questions/60551726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/881712/" ]
Following the suggestions of "Alex - Tin Le" I discovered the handlers weren't removed with: ``` _erp.HubSendOrderStatus -= Erp_HubSendOrderStatus; ``` I fixed this weird behavior checking if the handler is already registered: ``` if (!_erp.HubSendOrderStatus_isRegistered()) _erp.HubSendOrderStatus += Erp_HubSendOrderStatus; ``` The `HubSendOrderStatus_isRegistered` function is this: ``` public bool HubSendOrderStatus_isRegistered() { return HubSendOrderStatus != null; } ``` **I solved the initial problem**: no more flood of messages when making new connections. The last bit I don't understand is why it sends out 2 messages at time *no matter the number of active connections*. Debugging both the Javascript and the server code I noticed that a new connection is made on `$.connection.hub.start().done(function () { });` as expected. But another was *already* created when refreshing a page, even before any available breakpoint. But removing the "explicit" one leads to receive no messages.
Can you try this? ``` _erp.HubSendOrderStatus -= Erp_HubSendOrderStatus; _erp.HubSendOrderStatus += Erp_HubSendOrderStatus; ``` Normally, I always do this to avoid registering same handler many times.
28,437,434
i am running Ubuntu Machine and i installed awscli using pip. after this i configure the service with a user with full access to read monitor data. My goal is to get a list of all my ELB at this Aws Account and go over all their instances. this is the CLI command that i am trying to run : ``` aws elb describe-load-balancers --load-balancer-name "cpv" --region us-east-1b ``` i am trying a lot of diffrent combinations with the name , with - "" without "" i also configure the Region. this is the reply i always get : ``` HTTPSConnectionPool(host='elasticloadbalancing.us-east-1b.amazonaws.com', port=443): Max retries exceeded with url: / (Caused by <class 'socket.gaierror'>: [Errno -2] Name or service not known) ``` it seems the AWSCLI is trying to call to a default host and not to my ELB. i also tried the following for the name : 1. use the ELB - DNS\_name and with http:// , and https:// 2. Use DNS record that call to the ELB CNAME 3. Use with "" and without "" 4. Use the name with <> , [] around it It seems that my awscli is set on using this default host elasticloadbalancing.us-east-1b.amazonaws.com Is there any way to configure this ? The results of all those tries where all the same .. Fail does anyone know how to make this work? After Running this format : ``` aws elb describe-load-balancers --load-balancer-names "my-VIP" --endpoint-url http://my-VIP.us-east-1.elb.amazonaws.com --debug ``` I got this debug out put : ``` 015-02-10 17:50:54,581 - MainThread - awscli.clidriver - DEBUG - CLI version: aws-cli/1.7.5 Python/2.7.3 Linux/3.2.0-23-generic, botocore version: 0.86.0 2015-02-10 17:50:54,587 - MainThread - botocore.hooks - DEBUG - Event session-initialized: calling handler 2015-02-10 17:50:54,588 - MainThread - botocore.hooks - DEBUG - Event session-initialized: calling handler 2015-02-10 17:50:54,589 - MainThread - botocore.service - DEBUG - Creating service object for: elb 2015-02-10 17:50:54,832 - MainThread - botocore.hooks - DEBUG - Event service-data-loaded.elb: calling handler 2015-02-10 17:50:54,859 - MainThread - botocore.handlers - DEBUG - Registering retry handlers for service: elb 2015-02-10 17:50:54,861 - MainThread - botocore.hooks - DEBUG - Event service-data-loaded.elb: calling handler 2015-02-10 17:50:54,862 - MainThread - botocore.handlers - DEBUG - Registering retry handlers for service: elb 2015-02-10 17:50:54,863 - MainThread - botocore.service - DEBUG - Creating operation objects for: Service(elasticloadbalancing) 2015-02-10 17:50:54,920 - MainThread - botocore.hooks - DEBUG - Event building-command-table.elb: calling handler 2015-02-10 17:50:54,929 - MainThread - awscli.clidriver - DEBUG - OrderedDict([(u'load-balancer-names', ), (u'marker', ), (u'page-size', )]) 2015-02-10 17:50:54,930 - MainThread - botocore.hooks - DEBUG - Event building-argument-table.elb.describe-load-balancers: calling handler 2015-02-10 17:50:54,932 - MainThread - botocore.hooks - DEBUG - Event building-argument-table.elb.describe-load-balancers: calling handler 2015-02-10 17:50:54,933 - MainThread - botocore.hooks - DEBUG - Event building-argument-table.elb.describe-load-balancers: calling handler 2015-02-10 17:50:54,935 - MainThread - awscli.customizations.paginate - DEBUG - Modifying paging parameters for operation: Operation:DescribeLoadBalancers 2015-02-10 17:50:54,936 - MainThread - botocore.hooks - DEBUG - Event building-argument-table.elb.describe-load-balancers: calling handler 2015-02-10 17:50:54,938 - MainThread - botocore.hooks - DEBUG - Event before-building-argument-table-parser.elb.describe-load-balancers: calling handler > 2015-02-10 17:50:54,939 - MainThread - botocore.hooks - DEBUG - Event before-building-argument-table-parser.elb.describe-load-balancers: calling handler > 2015-02-10 17:50:54,946 - MainThread - botocore.hooks - DEBUG - Event operation-args-parsed.elb.describe-load-balancers: calling handler 2015-02-10 17:50:54,951 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.elasticloadbalancing.describe-load-balancers.load-balancer-names: calling handler 2015-02-10 17:50:54,952 - MainThread - botocore.hooks - DEBUG - Event process-cli-arg.elasticloadbalancing.describe-load-balancers: calling handler 2015-02-10 17:50:54,953 - MainThread - awscli.argprocess - DEBUG - Detected structure: list-scalar 2015-02-10 17:50:54,953 - MainThread - awscli.arguments - DEBUG - Unpacked value of [u'inj-VIP'] for parameter "load_balancer_names": [u'inj-VIP'] 2015-02-10 17:50:54,954 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.elasticloadbalancing.describe-load-balancers.marker: calling handler 2015-02-10 17:50:54,955 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.elasticloadbalancing.describe-load-balancers.page-size: calling handler 2015-02-10 17:50:54,956 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.elasticloadbalancing.describe-load-balancers.cli-input-json: calling handler 2015-02-10 17:50:54,957 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.elasticloadbalancing.describe-load-balancers.starting-token: calling handler 2015-02-10 17:50:54,958 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.elasticloadbalancing.describe-load-balancers.max-items: calling handler 2015-02-10 17:50:54,959 - MainThread - botocore.hooks - DEBUG - Event load-cli-arg.elasticloadbalancing.describe-load-balancers.generate-cli-skeleton: calling handler 2015-02-10 17:50:54,960 - MainThread - botocore.hooks - DEBUG - Event calling-command.elb.describe-load-balancers: calling handler > 2015-02-10 17:50:54,961 - MainThread - botocore.hooks - DEBUG - Event calling-command.elb.describe-load-balancers: calling handler > 2015-02-10 17:50:54,961 - MainThread - botocore.credentials - DEBUG - Looking for credentials via: env 2015-02-10 17:50:54,962 - MainThread - botocore.credentials - DEBUG - Looking for credentials via: assume-role 2015-02-10 17:50:54,962 - MainThread - botocore.credentials - DEBUG - Looking for credentials via: shared-credentials-file 2015-02-10 17:50:54,964 - MainThread - botocore.credentials - INFO - Found credentials in shared credentials file: ~/.aws/credentials 2015-02-10 17:50:55,003 - MainThread - botocore.operation - DEBUG - Operation:DescribeLoadBalancers called with kwargs: {u'LoadBalancerNames': [u'inj-VIP']} 2015-02-10 17:50:55,008 - MainThread - botocore.hooks - DEBUG - Event service-data-loaded.elb: calling handler 2015-02-10 17:50:55,009 - MainThread - botocore.handlers - DEBUG - Registering retry handlers for service: elb 2015-02-10 17:50:55,011 - MainThread - botocore.endpoint - DEBUG - Making request for (verify_ssl=False) with params: {'query_string': '', 'headers': {}, 'url_path': '/', 'body': {'Action': u'DescribeLoadBalancers', u'LoadBalancerNames.member.1': u'inj-VIP', 'Version': u'2012-06-01'}, 'method': u'POST'} 2015-02-10 17:50:55,013 - MainThread - botocore.hooks - DEBUG - Event request-created.elasticloadbalancing.DescribeLoadBalancers: calling handler 2015-02-10 17:50:55,018 - MainThread - botocore.auth - DEBUG - Calculating signature using v4 auth. 2015-02-10 17:50:55,018 - MainThread - botocore.auth - DEBUG - CanonicalRequest: POST / host:my-VIP.us-east-1.elb.amazonaws.com user-agent:aws-cli/1.7.5 Python/2.7.3 Linux/3.2.0-23-generic x-amz-date:20150210T175055Z host;user-agent;x-amz-date c9392bdd24453ba27fb57ad4362df35f56eee79cf57d429cde9df313d2a5b18a 2015-02-10 17:50:55,019 - MainThread - botocore.auth - DEBUG - StringToSign: AWS4-HMAC-SHA256 20150210T175055Z 20150210/us-east-1b/elasticloadbalancing/aws4_request 856ff8a91801b14db9fbfdecb5ed94d0715a880ff56dca3d634ff22ac995ceaf 2015-02-10 17:50:55,025 - MainThread - botocore.auth - DEBUG - Signature: 5cdecf0ba02219076779d47dfa713c23eb1126f9975bf347f2205c0e5f223eca 2015-02-10 17:50:55,056 - MainThread - botocore.endpoint - DEBUG - Sending http request: 2015-02-10 17:50:55,061 - MainThread - botocore.vendored.requests.packages.urllib3.connectionpool - INFO - Starting new HTTP connection (1): my-VIP.us-east-1.elb.amazonaws.com 2015-02-10 17:50:55,139 - MainThread - botocore.vendored.requests.packages.urllib3.connectionpool - DEBUG - "POST / HTTP/1.1" 200 20 2015-02-10 17:50:55,146 - MainThread - botocore.parsers - DEBUG - Response headers: {'connection': 'keep-alive', 'content-length': '20', 'content-type': 'text/html', 'date': 'Tue, 10 Feb 2015 17:50:06 GMT', 'server': 'nginx/1.1.19'} 2015-02-10 17:50:55,147 - MainThread - botocore.parsers - DEBUG - Response body: Web Analytics Server 2015-02-10 17:50:55,148 - MainThread - awscli.clidriver - DEBUG - Exception caught in main() Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/awscli/clidriver.py", line 197, in main return command_table[parsed_args.command](remaining, parsed_args) File "/usr/local/lib/python2.7/dist-packages/awscli/clidriver.py", line 357, in __call__ return command_table[parsed_args.operation](remaining, parsed_globals) File "/usr/local/lib/python2.7/dist-packages/awscli/clidriver.py", line 492, in __call__ self._operation_object, call_parameters, parsed_globals) File "/usr/local/lib/python2.7/dist-packages/awscli/clidriver.py", line 594, in invoke parsed_globals) File "/usr/local/lib/python2.7/dist-packages/awscli/clidriver.py", line 607, in _display_response formatter(operation, response) File "/usr/local/lib/python2.7/dist-packages/awscli/formatter.py", line 229, in __call__ for _, page in response: File "/usr/local/lib/python2.7/dist-packages/botocore/paginate.py", line 70, in __iter__ response = self._make_request(current_kwargs) File "/usr/local/lib/python2.7/dist-packages/botocore/paginate.py", line 390, in _make_request return self._operation.call(self._endpoint, **current_kwargs) File "/usr/local/lib/python2.7/dist-packages/botocore/operation.py", line 164, in call response = endpoint.make_request(self.model, request_dict) File "/usr/local/lib/python2.7/dist-packages/botocore/endpoint.py", line 105, in make_request return self._send_request(request_dict, operation_model) File "/usr/local/lib/python2.7/dist-packages/botocore/endpoint.py", line 143, in _send_request request, operation_model, attempts) File "/usr/local/lib/python2.7/dist-packages/botocore/endpoint.py", line 176, in _get_response operation_model.output_shape)), File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 210, in parse parsed = self._do_parse(response, shape) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 399, in _do_parse root = self._parse_xml_string_to_dom(xml_contents) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 337, in _parse_xml_string_to_dom parser.feed(xml_string) ParseError: syntax error: line 1, column 0 2015-02-10 17:50:55,159 - MainThread - awscli.clidriver - DEBUG - Exiting with rc 255 syntax error: line 1, column 0 ```
2015/02/10
[ "https://Stackoverflow.com/questions/28437434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1805551/" ]
The log level for a Play application already is `INFO` by default. The reason for no logging output probably has to do with your multiple SLF4J bindings. Play uses logback by default. Apparently you have included a (different?) SLF4J binding in your `suredbits-core-assembly` project. Play configures the logback logger, but probably not the logger of the binding you're using. And even if you have included logback twice it might not configure the logger which SLF4J eventually uses because of different class loaders. You should not define any SLF4J binding as a dependency of your core project: <http://www.slf4j.org/manual.html#libraries> > > Embedded components such as libraries or frameworks should not declare a dependency on any SLF4J binding but only depend on slf4j-api. When a library declares a transitive dependency on a specific binding, that binding is imposed on the end-user negating the purpose of SLF4J. Note that declaring a non-transitive dependency on a binding, for example for testing, does not affect the end-user. > > > So, remove the dependency to the SLF4J binding in your core project or at least exclude the org.slf4j.impl package when assembling your jar.
I think you have to set the level for the root logger: ``` logger.root=INFO ```
63,946,096
So I'm a Ruby dev messing with C# and trying to figure out how to use Flurl with my endpoint. Here's the JSON I can pass successfully with Ruby. ``` { type: "workorder.generated", data: [{ id: order.id, type: "orders" },{ id: second_order.id, type: "orders" },{ id: bad_order.id, type: "orders" } ] } ``` So using C# with Flurl I'm not 100% on how to structure that. ``` var response = await GetAPIPath() .AppendPathSegment("yardlink_webhook") .WithOAuthBearerToken(GetAPIToken()) .PostJsonAsync(new { type = "workorder.generated", data = new { } }) .ReceiveJson(); ``` Any help on getting that data nested similar to the Ruby example?
2020/09/17
[ "https://Stackoverflow.com/questions/63946096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1257350/" ]
While you could indeed plot subsets of the data as layers, you could also make the colour aesthetic a nested `ifelse()` statement. You'll get the correct legend too. Example below: ```r library(ggplot2) set.seed(0) df <- data.frame( logFC = rt(10000, 10), pvalue = runif(10000) ) ggplot(df, aes(logFC, log10(pvalue))) + geom_point( aes(colour = ifelse(is.na(pvalue) | pvalue > 0.05 | abs(logFC) < 2, "n.s.", ifelse(logFC >= 2, "Up", "Down"))) ) + scale_colour_manual(values = c("limegreen", "grey50", "dodgerblue"), name = "Category") + scale_y_continuous(trans = "reverse") ``` ![](https://i.imgur.com/DCtMPfY.png) Created on 2020-09-17 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)
Seems you used a `geom_point`-plot for your whole dataset. One way to solve your question is to add additional point-layers with subsets. You didn't provide an example dataset yet, so I used the iris dataset. I recolored smaller and higher values of Sepal.Length by subseting the dataset and added points in blue. Futhermore small values in Sepal.Width got the color green. To transfer this code to your case. Filter your dataset for your desired `LogFC` and/or `P.Value` and add these datasets and a color argument to additional `geom_point`layers. ``` ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(color = "red") + geom_point(data = iris[iris$Sepal.Length < 5 | iris$Sepal.Length > 7, ], color = "blue") + geom_point(data = iris[iris$Sepal.Width < 3, ], color = "green") ``` [![enter image description here](https://i.stack.imgur.com/taczN.png)](https://i.stack.imgur.com/taczN.png)
45,900,515
I'd like to crawl a set of random websites received from a URL generator, using Selenium's [ChromeDriver](http://www.seleniumhq.org/projects/webdriver/) with [Crawljax](http://crawljax.com/) to do static code analysis on the captured DOM states. Is this potentially unsafe for the machine doing the crawling? My concern is that one of the randomly generated sites is malicious and that execution of JavaScript from ChromeDriver (which is used to capture the new DOM states) infects the machine running the test somehow. Should I be running this in some kind of sandboxed environment? --edit-- If it matters, the crawler is implemented entirely in Java.
2017/08/26
[ "https://Stackoverflow.com/questions/45900515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6911032/" ]
Simple answer, no. Only if your afraid of cookies, and even if you are, your machine isn't.
It's hard to say it's very secure,you should aware of that there is no absolute secure in network.Recently,a chrome RCE has been put out,details: [SSD Advisory – Chrome Turbofan Remote Code Execution – SecuriTeam Blogs](https://blogs.securiteam.com/index.php/archives/3379 "SSD Advisory – Chrome Turbofan Remote Code Execution – SecuriTeam Blogs") Maybe this can effect on Selenium's ChromeDriver But you can do some enforce on your system,such as change your firewall mode to white list,only allow your python script and selenium to access internet on port 80,443. Even if your system pwned by RCE,the malicious code still can't access internet,unless it inject to you python process(I think it's very hard to do with js script in Browser RCE). Another option:Install HIPS,if your python script want to do anything else but crawl web page(such as start an other process) or read/write some other files,you will know it and decide what to do. In my oppion,do your crawl thing in a VM and do some enforce on firewall(Windows firewall or Linux iptables),shutdown useless services in windows.That's enough. In a word,it's diffcult to find the balance between security and convenience and do not believe your system is unbreakable
60,681,521
I am trying to do auto-deployment of a Python Flask application using Jenkins and then run it by using shell command on a Raspberry Pi server. Here are some **background info**, Before using Jenkins, my deployment and execution process was manual described below: 1. FTP to the directory where my Python scripts and Python venv are located 2. Replace Flask application scripts using FTP 3. Activate virtual environment to of Python(3.5) through the terminal on Raspberry Pi ("./venv/bin/activate") 4. Run myFlaskApp.py by executing "python myFlaskApp.py" in terminal Now I have integrated Jenkins with the deployment/execution process described below: 1. Code change pushed to github 2. Jenkins automatically pulls from github 3. Jenkins deploy files to specified directories by executing shell commands 4. Jenkins then activates virtual environment and run myFlaskApp.py by bashing a .sh script in the shell terminal. Now **the problem** that I am having is on step 4, because a Flask app has to always be alive, my Jenkins will never "finish building successfully", it will always be in a loading state as the Flask app is running on the shell terminal Jenkins is using. Now my **question**: What is the correct approach that I should be taking in order to activate myFlaskApp.py with Jenkins after deploying the files while not causing it to be "locked down" by the build process? I have read up about Docker, SubShell and the Linux utility "Screen". Will any of these tools be useful to assist me in my situation right now and which approach should I be taking?
2020/03/14
[ "https://Stackoverflow.com/questions/60681521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11537143/" ]
The simple and robust solution (in my opinion) is to use [Supervisor](http://supervisord.org/) which is available in Debian as `supervisor` package. It allows you do make a daemon from script like your app, it can spawn multiple processes, watch if app doesn't crash and if it does it can start it again. Note about `virtualenv` - you don't need to activate venv to use it. You just need to point appropriate Python executable (`your_venv/bin/python`) instead of default one. For example: ``` $ ./venv/bin/python myFlaskApp.py ```
You need to create these files for deployment over jenkins. **Code can be found:** <https://github.com/ishwar6/django_ci_cd> 1. This will work for both flask as well as django. 2. initial-setup.sh - This file is the first file to look at when setting up this project. It installs the required packages to make this project work such as Nginx, Jenkins, Python etc. Refer to the youtube video to see how and when it is used. 3. Jenkinsfile - This file contains the definition of the stages in the pipeline. The stages in this project's pipeline are Setup Python Virtual Environment, Setup gunicorn service and Setup Nginx. The stages in this pipeline just does two things. First it makes a file executable and then runs the file. The file carries out the commands that is described by the stage description. 4. envsetup.sh - This file sets up the python virtual environment, installs the python packages and then creates log files that will be used by Nginx. 5. gunicorn.sh - This file runs some Django management commands like migration commands and static files collection commands. It also sets up the gunicorn service that will be running the gunicorn server in the background. 6. nginx.sh - This file sets up Nginx with a configuration file that points Nginx to the gunicorn service that is running our application. This allows Nginx serve our application. I have followed a digital ocean article to setup this file. You can go through the video once to replicate sites-available and sites-enabled scanerio. 7. app.conf - This is an Nginx server configuration file. This file is used to setup Nginx as proxy server to gunicorn. For this configuration to work, change the value of server\_name to the IP address or domain name of your server.
68,042,680
I have been reading the book \*\*JavaScript: The Definitive Guide, 7th Edition", in this book is included forEach example that I am not able to get it: ``` let data = [1,2,3,4,5] data.forEach(function(v, i, a) { a[i] = v + 1; }); console.log(data); //[2,3,4,5,6] ``` I do not know how the parameters `v, i, a` are getting its value from the data array. If I change the order instead of (v, i ,a), then I get different result. Why it has to be in this order (value, index, array)? I have not been able to find why this strict order. For example, this other snippet is very straighforward: ``` let sum=0; data.forEach((value) => {sum+= value;}); ``` each element of data is passed to the body of the arrow function and it is adding the value and storing in sum which adds them up. Can you please provide insight about the first example? Thanks
2021/06/19
[ "https://Stackoverflow.com/questions/68042680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4538768/" ]
Have a look at the syntx of the `Array.prototype.forEach()` <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach> There is not much to say about the order, it's just the intended way of using the interface. You could use red, green and yellow for all intends and purposes, but the order would stay the same. First param will be the element value, second one the index and third the array itself. ```js let data = [1,2,3,4,5] data.forEach(function(red, green, yellow) { yellow[green] = red + 1; }); console.log(data); //[2,3,4,5,6] data.forEach(function(value, index, array) { array[index] = value + 1; }); console.log(data); //[3,4,5,6,7] ``` In newer versions of JS you could do something like ``` const array = [ 1, 2, 3, 4] for (const number of array) { console.log(number) } for (const [number, index] of array.entries()) { console.log(`${number} has ${index}`) } ``` And since the naming of the objects do only matter inside the `forEach()` scope, you could simply set them to something that makes sense in the context you are in, so your iteration gets easier to read and understand. E.g.: `for (const car of cars) {//car go honk}` See for `.entries()`: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries>
data.forEach funciton need a function as a parameter. and that function defined as function(value,index,array).you can pass a function with less parameters Eg:function(value),function(value,index).but you can't pass wrong order. becuase inside the forEach() function.you can image it did like this ```js //Just for Example.real code not like this Array.forEach = function(callback){ for(var i in this){ callback(this[i],i,this); } } ```
34,967,530
Node.js seems to use different rules to attach variables to the `global` object whether this is done in the REPL or in a script. ``` $ node > var a = 1; undefined > a 1 > global.a 1 > a === global.a true ``` As shown above when working in the REPL, declaring a variable with `var` creates a new property with the name of that variable on the `global` object. However, this doesn't seem to be the case in a script: ``` // test.js var a = 1; console.log(a); console.log(global.a); console.log(a === global.a); ``` Let's run the script: ``` $ node test.js 1 undefined false ``` Why is this happening?
2016/01/23
[ "https://Stackoverflow.com/questions/34967530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1335076/" ]
When a script is run, it is wrapped in a module. The top level variables in a script are inside a module function and are not global. This is how node.js loads and runs scripts whether specified on the initial command line or loaded with `require()`. Code run in the REPL is not wrapped in a module function. If you want variables to be global, you assign them specifically to the `global` object and this will work in either a script or REPL. ``` global.a = 1; ``` Global variables are generally frowned upon in node.js. Instead variables are shared between specific modules as needed by passing references to them via module exports, module constructors or other module methods. --- When you load a module in node.js, the code for the module is inserted into a function wrapper like this: ``` (function (exports, require, module, __filename, __dirname) { // Your module code injected here }); ``` So, if you declare a variable `a` at the top level of the module file, the code will end up being executed by node.js like this: ``` (function (exports, require, module, __filename, __dirname) { var a = 1; }); ``` From that, you can see that the `a` variable is actually a local variable in the module function wrapper, not in the global scope so if you want it in the global scope, then you must assign it to the global object.
There is no `window` in Node.js but there is another highest object called `global`. Whatever you assign to `global.something` in one module is accessible from another module. Example: **app.js** ``` global.name = "myName" ``` now you can get the `global.name` from any module **myController.js** ``` console.log(global.name); // output: myName ``` **anotherModule.js** ``` console.log(global.name); // output: myName ``` now when you declare a variable at one module `var i=0;` is it available from all module? NO ! Because all your project code is wrapped under a module, On REPL it doesn't. it's the highest level. That's why REPL variable becomes global. so if you want to work with global, you have to use with the `global` prefix ``` global.a = 1; console.log(global.a); ```
18,253,581
I recently updated my Java to the most up to date version and this caused an applet that I work with to not run correctly. I have changed the security parameters for Java through the Control Panel to the lowest possible settings but my applet still does not run. Here is what my applet looked like: ``` <HTML> <BODY BGCOLOR="#003333"> <p> <APPLET name=IpixViewer code=IpixViewer.class archive="IpixViewer.jar" width=450 height=450> <PARAM NAME="url" VALUE="209_a_CHEM.ipx"> </APPLET> </p> </BODY> </HTML> ``` I tried to use the HTML tag as a work around but this also is failing. Here is that code: ``` <HTML> <body> <p> <object type="application/x-java-applet;version=1.6" name="IpixViewer" id="ipixviewer" style="width:450px;height:450px" > <param name="code" value="IpixViewer.class" > <param name="archive" value="IpixViewer.jar" > <param name="codebase" value="Z:\filepath\"> <param name="url" value="205_a_CHEM.ipx" > </object> </p> </body> </HTML> ``` I think the issue is when I try to pass the url parameter into the applet but I am not sure. Any help would be appreciated.
2013/08/15
[ "https://Stackoverflow.com/questions/18253581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2660737/" ]
Because your overriding of `hello(int arg)` hides other functions with the same name. What you can do is to explicitly introduce those base class functions to subclass: ``` struct B : A { using A::hello; // Make other overloaded version of hello() to show up in subclass. virtual void hello(int arg) {} }; ```
The `hello(int)` member function in `B` takes an int argument and hides the `hello()` member of `A`. If you want the `hello` member function of `B` not to hide the one in `A`, add `using A::hello` to `B`.