qid
int64
1
74.7M
question
stringlengths
16
65.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
117k
response_k
stringlengths
3
61.5k
6,150,196
After 2 Days of search i still didnt find an answer. **Situation:** **Server:** SQL Server 2008 Express installed on RemoteServer TCP/IP: *Enabled on port 1433* Named Pipes: *Enabled* Database: *ConDB.mdf (attached to server)* **Workstation:** Microsoft Management Studio: ***Connection to database works*** > > Servertype: Databasemodul > > Servername: MTTC5020\SQLEXPRESS,1433 > > Authentifcation: SQL > Server-Authentification > Username: > testuser > Password: 1234 > > > > > **Visual Studio 2010 Express:** > > Error on Database Explorer: *SQL > Network Interfaces, error: 26 - Error > Locating Server/Instance > Specified* > > > > Same Error Through Connection via Appconfig and connectionstring: ``` <connectionStrings> <add name="ContainerDB.My.MySettings.ConDBConnectionString" connectionString="Data Source=MTTC5020\SQLEXPRESS,1433;Initial Catalog=ConDB.mdf;User ID=testuser;Password=1234;Integrated Security=false" providerName="System.Data.SqlClient.SqlConnection" /> </connectionStrings> ``` I also tried many other connectionstrings (Via IP / AttachedDBFileName / etc.) I also tried everything here: [MSDN](http://blogs.msdn.com/b/sql_protocols/archive/2007/05/13/sql-network-interfaces-error-26-error-locating-server-instance-specified.aspx) portcheck through SQLCMD -U testuser -P 1234 -S MTTC5020\SQLEXPRESS,1433 works aswell Any suggestions?
2011/05/27
[ "https://Stackoverflow.com/questions/6150196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/609671/" ]
I now found the issue. The connectionstring for the dbml is not only stored in the .config file. checkout the workaround for this at: [LINQ to SQL Connection Strings](http://www.toplinestrategies.com/dotneters/uncategorized/linq-to-sql-connection-strings/?lang=en)
Because by default express editions are installed as named instances, SQL Server on the remote machine needs to be allowed in firewall, not only the port, but the service, because named instances probably will change the port from time to time. Check this post, hope this helps blogs.msdn.com/b/sqlexpress/
7,072,438
I'm quite new to JSP/Liferay portlet development and I'm trying to add a progress bar using jQuery, I found [this question](https://stackoverflow.com/questions/5883101/jsp-progress-bar) but wasn't very specific to how it will be done using AJAX. I was wondering if anyone can point me in the right direction to help me get started. thanks. EDIT: I used [JSON simple](http://code.google.com/p/json-simple), and manage to make some changes but I am getting a bad request(error code 400 when using fire bug) and a 404 not found on my JS below is my code: ``` public void processAction( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { //some code here this.generateJSON(actionRequest, actionResponse);//manual call the method? public void generateJSON(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { try{ //just want to see a progress bar so do static for now... JSONObject obj=new JSONObject(); obj.put("percent",new Integer(30)); StringWriter out = new StringWriter(); obj.writeJSONString(out); String jsonText = out.toString(); }catch(Exception ex){ System.out.print(ex); } } }//end of class ``` JS here ``` function checkStatus(){ $.ajax({ type: 'POST', //url: '<%=request.getContextPath()%>/checkStatusServlet', url: '<%=request.getContextPath()%>/generateJSON', dataType: 'json', success: function( data ) { alert(data.statusPercent); var statusPercent = data.percent; //Update your jQuery progress bar $( "#progressbar" ).progressbar({value: statusPercent}); } }); //below works and alert is being called... /*for (i=0;i<=5;i++) { $( "#progressbar" ).progressbar({value: i+10}); } alert('got here'); */ } ``` HTML/JSP ``` <%@ page import="javax.portlet.PortletPreferences" %> <portlet:defineObjects/> <portlet:renderURL var="resourceUrl"></portlet:renderURL> <!-- Javascript files --> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="js/main.js"></script> <!-- end of Java script files --> <script type="text/javascript"> setTimeout('checkStatus()',1000); </script> <div id="progressbar"></div> ```
2011/08/16
[ "https://Stackoverflow.com/questions/7072438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/652670/" ]
You can't generate JSON in processAction. This method is meant to change the portlet state, but not generate output. The portal-way to accomplish what you need it to use the serveResource method/lifecycle-phase: you get the URL for this from the portal ( < portlet:resourceURL / >). Specifically you shouldn't create them yourself. An alternative (but not the portal way) is to use a servlet - but in this you don't have the portlet state that you might need. And you might want to use < portlet:namespace / > to disambiguate your global names - or use proper namespacing - because you can never say how many times your portlet will be placed on a page. (added spaces to jsp-tags so that they don't get eaten by markup) Short: Read about resource-serving for portlets, this will most likely solve your underlying problem: With the code you give above you won't be able to access your JSON at all - no matter what you do on the JS side.
The answer really depends on your specific needs. Are you trying to display how much time is actually left for some task, or how much time till a page loads or what? You could poll from the client and update the progress bar in the browser depending on how much is left to process. A simple jQuery ajax example: ``` function checkStatus { $.ajax({ type: 'POST', url: '<%=request.getContextPath()%>/checkStatusServlet', dataType: 'json', success: function( data ) { var statusPercent = data.statusPercent; //Update your jQuery progress bar $( "#progressbar" ).progressbar({value: statusPercent }); } }); } ``` Then you can simply poll this function till its done ``` setTimeout('checkStatus()' 1000); ``` Of course you will also need to construct a servlet or struts action or portlet to handle the processing on the server, and return the appropriate status for the task. EDIT: Use the [JSON library](https://github.com/douglascrockford/JSON-java) From your servlet or action. (code below is from struts2 action) ``` public String checkStatus() { try { Integer percentDone = 50; //Calculate how much time is left JSONObject statusResult = new JSONObject(); statusResult.put("statusPercent", percentDone); //Obtain HttpServletResponse.. //implementation depends on your framework. //PortletResponse should work too. PrintWriter out = this.response.getWriter(); out.write( statusResult.toString(4) ); out.flush(); out.close(); } catch (IOException e) {} catch (JSONException e) {} return null; } ```
50,693,799
I'm a new for Javascript. I wanted to add a method to the external library named jsPDF. so I tried to add a function named 'addHangle' to jsPDF.prototype But the object of jsPDF didn't find my method. I've tried debugging and I found out jsPDF.prototype is pointer for Object.prototype Why does it happend? I thought doc.construct is pointer for jsPDF and doc.\_\_proto\_\_ is pointer for jsPDF.prototype Is there anyone know the reason? please tell me. my code is below. ``` jsPDF.prototype.addHangle = function(x, y, text) { // some logic for supporting Korean }; var doc = new jsPDF(); doc.addHangle(); ```
2018/06/05
[ "https://Stackoverflow.com/questions/50693799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8101806/" ]
Because jsPDF constructor returns API object. Following example might help you to understand why `doc`'s prototype is not a `jsPDF` ``` var P = function() { var API = {}; // This is constructor of P function P() { // Do something... API.a = function(val){return val}; return API; } return P; }; var p = new P(); var result = p instanceof P; // false ``` You can see what really happens when `new jsPDF()` called at [jsPDF GitHub](https://github.com/MrRio/jsPDF/blob/master/jspdf.js) If you want to insert your own method, you have to make it as jsPDF plugin. You can refer other plugins of jsPDF at <https://github.com/MrRio/jsPDF/tree/master/plugins>
hi follow the link <https://github.com/happymishra/JavaScriptTutorials/blob/master/Part2/Prototypes.md> you will get idea of prototypes
19,941,009
I'm trying to set the focus to a TextBox control (which is inside an UpdatePanel) in an ASP.Net application (C#). I've tried the following in the code behind: ``` tbxName.Focus(); Page.SetFocus(tbxName); tsmManageTables.SetFocus(tbxName); ``` None of those worked, so then I went to Javascript. Here's my Javascript function: ``` function SetControlFocus(ctrlID) { var ctrl = document.getElementById(ctrlID); ctrl.focus(); } ``` Here's the method in code behind that's calling it: ``` private void SetControlFocus(Control ctrl) { StringBuilder focus = new StringBuilder(); focus.AppendLine("<script type='text/javascript'>"); focus.AppendFormat(" SetControlFocus('{0}');" + System.Environment.NewLine, ctrl.ClientID); focus.AppendLine("</script>"); ClientScript.RegisterStartupScript(this.GetType(), "setControlFocus", focus.ToString(), false); } ``` And the call: ``` SetControlFocus(tbxName); ``` I've also tried the Javascript: ``` (function($) { SetControlFocus = function(ctrlID) { var ctrl = $('<%= ' + ctrlID + ' %>'); ctrl.focus(); }; })(jQuery); ``` With either version of the Javascript function, I get the error > > "Object ctl00\_MainContent\_tbxName has no method 'focus'" > > > What am I doing wrong? **UPDATE**: I tried Karl's suggestion of using a class selector instead of the ID selector with the ugly `<%= =>`, but it didn't work. Now I'm getting a different error: > > Uncaught ReferenceError: className is not defined > > > with the Javascript: ``` (function($) { SetControlFocus = function(ctrlClass) { var ctrl = $('.' + ctrlClass); ctrl.focus(); }; })(jQuery); ``` the markup: ``` <asp:TextBox ID="tbxName" runat="server" CssClass="className"></asp:TextBox> ``` the calling method: ``` private void SetControlFocus(Control ctrl) { StringBuilder focus = new StringBuilder(); focus.AppendLine("<script type='text/javascript'>"); focus.AppendFormat(" SetControlFocus({0});" + System.Environment.NewLine, ctrl.CssClass); focus.AppendLine("</script>"); ClientScript.RegisterStartupScript(this.GetType(), "setControlFocus", focus.ToString(), false); } ``` the call (C#): ``` SetControlFocus(tbxName); ``` and the generated HTML for the TextBox: ``` <input name="ctl00$MainContent$tbxName" type="text" id="ctl00_MainContent_tbxName" class="className" /> ``` **UPDATE 2**: I played around some more with this and made progress (I think). Now I'm not getting any error messages, but the focus still isn't going to the TextBox. Here's my current jQuery function: ``` (function($) { SetControlFocus = function(ctrl) { //give the control focus alert(ctrl); ctrl.focus(); }; })(jQuery); ``` And here's the C# method where I call it: ``` private void SetControlFocus(TextBox ctrl) { StringBuilder focus = new StringBuilder(); focus.AppendLine("<script type='text/javascript'>"); focus.AppendFormat(" SetControlFocus({0});" + System.Environment.NewLine, ctrl.ClientID); focus.AppendLine("</script>"); ClientScript.RegisterStartupScript(this.GetType(), "setControlFocus", focus.ToString(), false); } //end method SetControlFocus ``` Notice that I'm passing the control's ClientID to the Javascript function. The weird thing is that the Javascript is taking the ClientID and actually "capturing" the control object, rather than a string containing the ClientID. The alert is working, it gives me `[object HTMLInputElement]` in the alert. Any tips? **UPDATE 3**: I've modified the Javascript function: ``` (function($) { SetControlFocus = function(ctrlSelector) { alert(ctrlSelector); $(ctrlSelector).focus(); }; })(jQuery); ``` and the calling method: ``` private void SetControlFocus(TextBox ctrl) { StringBuilder focus = new StringBuilder(); focus.AppendLine("<script type='text/javascript'>"); focus.AppendFormat(" SetControlFocus('{0}');" + System.Environment.NewLine, "#" + ctrl.ClientID); focus.AppendLine("</script>"); ClientScript.RegisterStartupScript(this.GetType(), "setControlFocus", focus.ToString(), false); } ``` (notice the addition of single quotes around the argument - `'{0}'`). Now I'm getting the correct selector (the alert responds with `#ctl00_MainContent_txtName`), no errors, but the TextBox *still* isn't getting focus.
2013/11/12
[ "https://Stackoverflow.com/questions/19941009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1299152/" ]
You're [shadowing](http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.4.1) the variable `b1`. Replace ``` JButton b1 = new JButton("Blue"); ``` with ``` b1 = new JButton("Blue"); ```
I see your problem, you are redeclaring b1,b2, and b2 in method main, leaving static variables b1,b2,b3 as null. To fix remove the word "JButton" when initializing your buttons.
33,547,735
Hi I have a Form which needs a unique form number. Basically what I need is before the form is submitted, the user is able to see what form number will that form submission will have. The form number should be unique. What I'm thinking is I'll have another table which has a single row: ``` table:numbers ->id ->number ``` Then when the form loads I'll make an ajax request to show the current number and use it as form number then when the user submit, the number will be updated (increamented) since it is already used. But problem is I want the form number to formatted like `1, 2, 3 ..` so I added zerofill on database but when I fetch it it only show the number in my form without zeroes. Is there a better approach on this? I'm using MySQL Thanks
2015/11/05
[ "https://Stackoverflow.com/questions/33547735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3639125/" ]
Try something like ``` bool compareNumbers(const void* a, const void* b) { object* A = (object*) a; object* B = (object*) b; if (A->number <= B->number) { return true; } else { return false; } } ``` Then change bubbleSort params in order to look like ``` void bubbleSort(object tab[], int size_tab, bool(comparator*)(const void*, const void*)) ``` Now you can pass the pointer to `compareNumbers` function as third argument of `bubbleSort` function: ``` bubbleSort(a, n, &compareNumbers); ``` and use it in `bubbleSort`'s implemetntation: ``` void bubbleSort(object tab[], int size_tab, bool(comparator*)(const void*, const void*)) { object temp; for (int i = 1; i < size_tab; i++) { for (int j = 0; j < size_tab - i; j++) { if (comparator(tab + j, tab + j + 1)) { temp = tab[j]; tab[j] = tab[j+1]; tab[j+1] = temp; } } } } ```
Based on the `compareNumbers` that you have, the line ``` if(tab[j].number > tab[j+1].number) ``` should become ``` if(compareNumbers(&tab[j],&tab[j+1]) == 1) ``` I would also recommend changing `compareNumbers` to: ``` int compareNumbers(const object *a, const object *b) { if(a->number > b->number) return 1; else if(a->number < b->number) return -1; else return 0; } ``` or even better yet, using [references](http://www.cprogramming.com/tutorial/references.html). --- To give you an idea of a C++11 way to do this: ``` template <class T> void bubble_sort( T tab[], size_t tab_size, std::function<bool(const T&,const T&)> Comp ) { if ( !tab || tab_size < 2 ) return; for ( size_t i=1; i<tab_size; ++i ) for ( size_t j=0; j<tab_size-i; ++j ) if (Comp(tab[j],tab[j+1])) std::swap(tab[j],tab[j+1]); } ``` and then call with ``` bubble_sort( tab, 42, []( const object& a, const object& b )->bool {return a.number < b.number;} ); bubble_sort( tab, 42, []( const object& a, const object& b )->bool {return a.letter < b.letter;} ); ```
20,564,587
I have a need of display two diff. tables's data in one selectbox. so i use following query: ``` <select name="account[]" id="account" class="input" multiple size="3"> <option value="">Select</option> <?php global $mysqli; $query = "SELECT `number` as num, `id` from `table1` where `account_id`='".$_SESSION['account_id']."' UNION ALL SELECT `number` as num, `id` from `table2` where `account_id`='".$_SESSION['account_id']."'"; $result = $mysqli->query($query) or die($mysqli->error); while($row5 = $result->fetch_array(MYSQLI_ASSOC)){ ?> <option value="<?php echo $row5['id'];?>"><?php echo $row5['num'];?></option> <?php }?> </select> ``` so all data are fetch according to my need. But now i have a problem. > > When i inserted user selected data, how to indentify that user selected data is from table1 or table2 ? > > > I have a some ideas: (1) Create two diff. queries in selectbox and bind predifined value. exa.: ``` <option value="table1.9999"><?php echo $row5['num'];?></option> <option value="table2.2222"><?php echo $row5['num'];?></option> ``` (2) insert table2's id(here id is automatic inserted id primary key) maually. > > like: id=10000 > so i check that if id>10000 then it is from table2. > > > But the upper things is like petch. so what is the alternavites for do upper things. Any ideas are welcome.Thanks in advance. **SIDE NOTE:** table structure is good according to my need. so i cannot change whole table structure. But i can add fields in tables.
2013/12/13
[ "https://Stackoverflow.com/questions/20564587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1773177/" ]
Just add a column to your SELECT statement, that specifies whether the data comes from table1 or table2: ``` SELECT `number` as num, `id`, "Table1" as source from `table1` where ... UNION ALL SELECT `number` as num, `id`, "Table2" as source from `table2` where ... ``` Then you can use this `source` column to determine if the record is from Table1 or Table2. If you need a unique identifier across both tables, just concatenate the id with the table number. Something like this should work: ``` SELECT `number` as num, `id` & "-Table1" as uniqueid ... ```
Let's say you separated this functionalities, so now you have a php backend with delivers the query result as a json string optionlist.php ``` global $mysqli; $optionlist=array(); $query = "SELECT `number` as num, `id`, 'Table1' as source from `table1` where `account_id`='".$_SESSION['account_id']."' UNION ALL SELECT `number` as num, `id`, 'Table2' as source from `table2` where `account_id`='".$_SESSION['account_id']."'"; $result = $mysqli->query($query) or die($mysqli->error); while($row5 = $result->fetch_array(MYSQLI_ASSOC)){ $optionlist[] = $row5; } echo json_encode($optionlist); ``` now in your mainfile you have an empty select box and a js to fill it up main.html ``` <script src="//code.jquery.com/jquery-1.10.2.min.js"></script> <script> jQuery(document).ready(function() { jQuery.ajax({ url: 'optionlist.php' dataType: 'json'; }).done(function(jsonlist) { for(var i=0;i<jsonlist.length;i++) { theoption=jsonlist[i]; jQuery('#account').append('<option rel="'+ theoption.source +" value="'+theoption.id+'">'+ theoption.num '</option>'; } }); </script> <select name="account[]" id="account" class="input" multiple size="3"> <option value="">Select</option> </select> ```
58,276,460
I've got an animated section [at the very bottom of this page](https://cv.devops.unlimitedgrowth.io/start-ups/#bottom) that works as expected when you click on the "Next Category" DIV container, except that the text's `font-weight` does not change... I understand that the style of child element always override the parent style even with the use of `!important`, but my JQuery directly gives this text a class that has `font-weight: 400 !important`, and other elements in the same site with 400 font weight display this lighter Google font just fine -it is a font that by default has different weights after all- so I do not understand... This is the jQuery ``` $('.clickable').on('click', function() { $('.clickable').attr('id', 'ScaleDown'); $('.dot').css('opacity', '0'); $('#next').addClass('lighter') $('.category').addClass('ScaleUp'); }); ``` This is the CSS ``` .clickable { transform: scale(1); transition: all 1s; } #ScaleDown { transform: scale(0.33); transition: all 1s; } .lighter { font-weight: 400 !important; } .category { opacity: 0; transform: scale(0); transition: all 1s; } .ScaleUp { transform: scale(1); opacity: 1 !important; } ```
2019/10/07
[ "https://Stackoverflow.com/questions/58276460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12124593/" ]
You need to override the `<h3>` font-weight, since it is declared specifically for this tag in the stylesheet. If you change this ```css .lighter { font-weight: 400 !important; } ``` to this ```css .lighter h3.elementor-heading-title { font-weight: 400 !important; } ```
There's a font-weight attribute set on the h3 tags. If you target the h3 tag in the .lighter class, you can override the applied font-weight. Try this: ``` .lighter h3 { font-weight: 400 !important; } ```
58,276,460
I've got an animated section [at the very bottom of this page](https://cv.devops.unlimitedgrowth.io/start-ups/#bottom) that works as expected when you click on the "Next Category" DIV container, except that the text's `font-weight` does not change... I understand that the style of child element always override the parent style even with the use of `!important`, but my JQuery directly gives this text a class that has `font-weight: 400 !important`, and other elements in the same site with 400 font weight display this lighter Google font just fine -it is a font that by default has different weights after all- so I do not understand... This is the jQuery ``` $('.clickable').on('click', function() { $('.clickable').attr('id', 'ScaleDown'); $('.dot').css('opacity', '0'); $('#next').addClass('lighter') $('.category').addClass('ScaleUp'); }); ``` This is the CSS ``` .clickable { transform: scale(1); transition: all 1s; } #ScaleDown { transform: scale(0.33); transition: all 1s; } .lighter { font-weight: 400 !important; } .category { opacity: 0; transform: scale(0); transition: all 1s; } .ScaleUp { transform: scale(1); opacity: 1 !important; } ```
2019/10/07
[ "https://Stackoverflow.com/questions/58276460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12124593/" ]
Your rule has to select the `h3` tag ``` .lighter h3 { font-weight: 400 !important; } ``` because of this existing rule ``` body.elementor-page-300 h3, body.elementor-page-300 .elementor-widget-heading h3.elementor-heading-title, body.elementor-page-300 h3 a, body.elementor-page-300 .elementor-widget-heading h3.elementor-heading-title a { font-family: "PT Serif", Sans-serif; font-size: 3.5em; font-weight: 600; text-transform: none; line-height: 1em; } ``` which styles the `h3` tag already.
You need to override the `<h3>` font-weight, since it is declared specifically for this tag in the stylesheet. If you change this ```css .lighter { font-weight: 400 !important; } ``` to this ```css .lighter h3.elementor-heading-title { font-weight: 400 !important; } ```
58,276,460
I've got an animated section [at the very bottom of this page](https://cv.devops.unlimitedgrowth.io/start-ups/#bottom) that works as expected when you click on the "Next Category" DIV container, except that the text's `font-weight` does not change... I understand that the style of child element always override the parent style even with the use of `!important`, but my JQuery directly gives this text a class that has `font-weight: 400 !important`, and other elements in the same site with 400 font weight display this lighter Google font just fine -it is a font that by default has different weights after all- so I do not understand... This is the jQuery ``` $('.clickable').on('click', function() { $('.clickable').attr('id', 'ScaleDown'); $('.dot').css('opacity', '0'); $('#next').addClass('lighter') $('.category').addClass('ScaleUp'); }); ``` This is the CSS ``` .clickable { transform: scale(1); transition: all 1s; } #ScaleDown { transform: scale(0.33); transition: all 1s; } .lighter { font-weight: 400 !important; } .category { opacity: 0; transform: scale(0); transition: all 1s; } .ScaleUp { transform: scale(1); opacity: 1 !important; } ```
2019/10/07
[ "https://Stackoverflow.com/questions/58276460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12124593/" ]
Your rule has to select the `h3` tag ``` .lighter h3 { font-weight: 400 !important; } ``` because of this existing rule ``` body.elementor-page-300 h3, body.elementor-page-300 .elementor-widget-heading h3.elementor-heading-title, body.elementor-page-300 h3 a, body.elementor-page-300 .elementor-widget-heading h3.elementor-heading-title a { font-family: "PT Serif", Sans-serif; font-size: 3.5em; font-weight: 600; text-transform: none; line-height: 1em; } ``` which styles the `h3` tag already.
There's a font-weight attribute set on the h3 tags. If you target the h3 tag in the .lighter class, you can override the applied font-weight. Try this: ``` .lighter h3 { font-weight: 400 !important; } ```
24,757,486
Lets take a word ``` qwerty ``` What I want is I need to insert periods (dots .) between the string. It can be any other character also. For example, ``` q.werty qw.erty qwe.rty qwer.ty qwert.y ``` The above is for 1 period or dot. So 1 period combination for a 5 letter string will generate 5 outputs. (N-1) Now for 2 periods (2 dots) (2 examples only): ``` q.w.erty q.we.rty q.wer.ty q.wert.y qw.e.rty qw.er.ty qw.ert.y qwe.r.ty qwe.rt.y qwer.t.y ``` and so on.. NOTE: There must not be 2 consecutive dots between 2 letters in the string. Also, there must not be a period before starting character and/or after ending character. Can anyone provide a Shell Script (sh, bash) for the above to list all the possible combinations and permutations. I have tried Googling and didn't find any worthwhile content to refer. EDIT: Any help on how to start this on bash shell script would be great...
2014/07/15
[ "https://Stackoverflow.com/questions/24757486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2732674/" ]
Your puzzle is fun so here's a code: ``` #!/bin/bash t=qwerty echo '---- one dot ----' for (( i = 1; i < ${#t}; ++i )); do echo "${t:0:i}.${t:i}" done echo '---- two dots ----' for (( i = 1; i < (${#t} - 1); ++i )); do for (( j = i + 1; j < ${#t}; ++j )); do echo "${t:0:i}.${t:i:j - i}.${t:j}" done done ``` Output: ``` ---- one dot ---- q.werty qw.erty qwe.rty qwer.ty qwert.y ---- two dots ---- q.w.erty q.we.rty q.wer.ty q.wert.y qw.e.rty qw.er.ty qw.ert.y qwe.r.ty qwe.rt.y qwer.t.y ``` See the [Bash Manual](http://www.gnu.org/software/bash/manual/bashref.html) for everything.
I won't write the code, but I can guide you to the answer. I assume you want to consider all possible number of dots, not just 1 or 2, but 3, 4, ... , up to the length of the string - 1. For each character in the string up until the last, there are two possibilities: there is a dot or there is not a dot. So for an `n` character string, there are O(2^(n-1)) possibilities. You could write a for loop that goes through all 2^(n-1) possibilities. Each one of these corresponds to a single output with dots after letters. Let `i` be an iteration of the for loop. Then have an internal `j` loop that goes 1 to n-1. If the `j`th bit is 1, then put a dot after the `j`th letter.
36,994,177
Sorry to ask this question but I'm really newbie with Ruby and I need help to update several records on my database. I'm using ActiveRecord to query the database. Let say I have a table Product that contains SubProduct that also contains SubSubProduct. Now I would like to write a simple query to get all SubSubProduct of Product. To get a list of SubSubProduct I usually do this ``` ssp = SubSubProduct.where(sub_sub_type: "example") ``` Now to use a where clause on relational element how can I do ``` ssp = SubSubProduct.where(sub_sub_type: "example", SubProduct.Product.type: "sample") ```
2016/05/03
[ "https://Stackoverflow.com/questions/36994177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196526/" ]
Use `String.toUpperCase()` along with `equals()`: ``` String line1 = "THIS LINE IS ALL CAPS"; String line2 = "THIS line is MIXED"; if (line1.equals(line1.toUpperCase())) { System.out.println("Line 1 is all uppercase."); } if (line2.equals(line2.toUpperCase())) { System.out.println("Line 2 is all uppercase."); } ``` **Output:** ``` Line 1 is all uppercase. ```
You can convert input string to all upperCase and store it on New variable(say `inputUppercase`) And then simply check if `inputUppercase` and input are equal.
36,994,177
Sorry to ask this question but I'm really newbie with Ruby and I need help to update several records on my database. I'm using ActiveRecord to query the database. Let say I have a table Product that contains SubProduct that also contains SubSubProduct. Now I would like to write a simple query to get all SubSubProduct of Product. To get a list of SubSubProduct I usually do this ``` ssp = SubSubProduct.where(sub_sub_type: "example") ``` Now to use a where clause on relational element how can I do ``` ssp = SubSubProduct.where(sub_sub_type: "example", SubProduct.Product.type: "sample") ```
2016/05/03
[ "https://Stackoverflow.com/questions/36994177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196526/" ]
Use `String.toUpperCase()` along with `equals()`: ``` String line1 = "THIS LINE IS ALL CAPS"; String line2 = "THIS line is MIXED"; if (line1.equals(line1.toUpperCase())) { System.out.println("Line 1 is all uppercase."); } if (line2.equals(line2.toUpperCase())) { System.out.println("Line 2 is all uppercase."); } ``` **Output:** ``` Line 1 is all uppercase. ```
Or you can use regex: ``` Pattern p = Pattern.compile("^[A-Z. ]+$"); //regex that matches uppercase and space and period only for(String line : lines){ Matcher m = p.matcher(line); if(m.matches()){ // all upper case ... } } ``` [Regex](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)
27,683,567
I got error when i clicked button inside webview page. Suppposedly, when I click button, it will change to google site. Below are code and error:- MainActivity.java ``` package com.mt.nad.testwebapp; import android.content.Context; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { private WebView webC; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webC = (WebView)findViewById(R.id.webView1); webC.addJavascriptInterface(new JavaScriptInterface(), "CallJavaAdapter"); webC.setWebViewClient(new WebViewClient()); WebSettings webS = webC.getSettings(); webS.setJavaScriptEnabled(true); webC.loadUrl("http://10.0.2.2/test-java-adapter/"); } private class JavaScriptInterface{ JavaScriptInterface() { } @JavascriptInterface public void gotoSite() { //Toast.makeText(mContext, url, Toast.LENGTH_SHORT).show(); webC.clearCache(true); webC.loadUrl("http://google.com"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ``` activity\_main.xml ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" /> <WebView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/webView1" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> </RelativeLayout> ``` AndroidManifest.xml ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.mt.nad.testwebapp" > <uses-permission android:name="android.permission.INTERNET"></uses-permission> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> ``` index.html ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Test Only</title> <link rel="stylesheet" href=""> </head> <body> <div> <input type="button" value="Go To Site" onClick="window.CallJavaAdapter.gotoSite()"> </div> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> </body> </html> ``` LogCat ``` 12-29 03:54:04.099 2793-2838/com.mt.nad.testwebapp W/WebView﹕ java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {2e799371} called on Looper (JavaBridge, tid 210) {72d6c48}, FYI main Looper is Looper (main, tid 1) {2e799371}) at android.webkit.WebView.checkThread(WebView.java:2194) at android.webkit.WebView.clearCache(WebView.java:1451) at com.mt.nad.testwebapp.MainActivity$JavaScriptInterface.gotoSite(MainActivity.java:56) at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method) at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:28) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.os.HandlerThread.run(HandlerThread.java:61) 12-29 03:54:04.100 2793-2838/com.mt.nad.testwebapp W/System.err﹕ java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {2e799371} called on Looper (JavaBridge, tid 210) {72d6c48}, FYI main Looper is Looper (main, tid 1) {2e799371}) 12-29 03:54:04.100 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.webkit.WebView.checkThread(WebView.java:2204) 12-29 03:54:04.100 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.webkit.WebView.clearCache(WebView.java:1451) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at com.mt.nad.testwebapp.MainActivity$JavaScriptInterface.gotoSit (MainActivity.java:56) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:28) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.os.Looper.loop(Looper.java:135) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.os.HandlerThread.run(HandlerThread.java:61) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ Caused by: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {2e799371} called on Looper (JavaBridge, tid 210) {72d6c48}, FYI main Looper is Looper (main, tid 1) {2e799371}) 12-29 03:54:04.102 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.webkit.WebView.checkThread(WebView.java:2194) 12-29 03:54:04.102 2793-2838/com.mt.nad.testwebapp W/System.err﹕ ... 7 more 12-29 03:54:04.127 2793-2793/com.mt.nad.testwebapp I/chromium﹕ [INFO:CONSOLE(19)] "Uncaught Error: Java exception was raised during method invocation", source: http://10.0.2.2/test-java-adapter/ (19) 12-29 03:54:04.159 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.175 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.274 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) 12-29 03:54:04.299 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.323 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.448 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) 12-29 03:54:04.468 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.499 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.527 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) 12-29 03:54:04.537 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.549 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.580 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) ``` source: ``` http://10.0.2.2/test-java-adapter/ (19) ``` is refer to ``` <input type="button" value="Go To Site" onClick="window.CallJavaAdapter.gotoSite()"> ``` If using Toast or TextView, in can change when click the button but for WebView loadurl(), it won't load... I refer to: [Android App: How to loadUrl in WebView from another class?](https://stackoverflow.com/questions/7915309/android-app-how-to-loadurl-in-webview-from-another-class) but still no luck...
2014/12/29
[ "https://Stackoverflow.com/questions/27683567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2983037/" ]
Technically this doesn't answer the question of how to learn the number of lines of rendered text but I did find a solution to my problem so I thought I'd post it anyway. What I ended up doing was removing the width autolayout constraint on the label (actually the leading and trailing constraints to the superview) and added a center horizontally in container constraint to it. Then in `-[UIViewController viewDidLayoutSubviews]` I set `label.preferredMaxLayoutWidth=self.view.frame.size.width-margin`. The label's `textAlignment=NSTextAlignmentLeft`. This achieves the same effect of having the label centered if it is only one line and left justified if it is two or more.
You can set your `UILabel` with `NSMutableAttributedString` like this: ``` UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)]; [contentLabel setLineBreakMode:NSLineBreakByWordWrapping]; [contentLabel setNumberOfLines:0]; [contentLabel setFont:[UIFont systemFontOfSize:13]; NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello I am a long sentence that should break over multiple lines"]; [string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(0, [string length])]; contentLabel.attributedText = string; ``` Hope this helps...
27,683,567
I got error when i clicked button inside webview page. Suppposedly, when I click button, it will change to google site. Below are code and error:- MainActivity.java ``` package com.mt.nad.testwebapp; import android.content.Context; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { private WebView webC; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webC = (WebView)findViewById(R.id.webView1); webC.addJavascriptInterface(new JavaScriptInterface(), "CallJavaAdapter"); webC.setWebViewClient(new WebViewClient()); WebSettings webS = webC.getSettings(); webS.setJavaScriptEnabled(true); webC.loadUrl("http://10.0.2.2/test-java-adapter/"); } private class JavaScriptInterface{ JavaScriptInterface() { } @JavascriptInterface public void gotoSite() { //Toast.makeText(mContext, url, Toast.LENGTH_SHORT).show(); webC.clearCache(true); webC.loadUrl("http://google.com"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ``` activity\_main.xml ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" /> <WebView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/webView1" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> </RelativeLayout> ``` AndroidManifest.xml ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.mt.nad.testwebapp" > <uses-permission android:name="android.permission.INTERNET"></uses-permission> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> ``` index.html ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Test Only</title> <link rel="stylesheet" href=""> </head> <body> <div> <input type="button" value="Go To Site" onClick="window.CallJavaAdapter.gotoSite()"> </div> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> </body> </html> ``` LogCat ``` 12-29 03:54:04.099 2793-2838/com.mt.nad.testwebapp W/WebView﹕ java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {2e799371} called on Looper (JavaBridge, tid 210) {72d6c48}, FYI main Looper is Looper (main, tid 1) {2e799371}) at android.webkit.WebView.checkThread(WebView.java:2194) at android.webkit.WebView.clearCache(WebView.java:1451) at com.mt.nad.testwebapp.MainActivity$JavaScriptInterface.gotoSite(MainActivity.java:56) at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method) at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:28) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.os.HandlerThread.run(HandlerThread.java:61) 12-29 03:54:04.100 2793-2838/com.mt.nad.testwebapp W/System.err﹕ java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {2e799371} called on Looper (JavaBridge, tid 210) {72d6c48}, FYI main Looper is Looper (main, tid 1) {2e799371}) 12-29 03:54:04.100 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.webkit.WebView.checkThread(WebView.java:2204) 12-29 03:54:04.100 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.webkit.WebView.clearCache(WebView.java:1451) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at com.mt.nad.testwebapp.MainActivity$JavaScriptInterface.gotoSit (MainActivity.java:56) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:28) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.os.Looper.loop(Looper.java:135) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.os.HandlerThread.run(HandlerThread.java:61) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ Caused by: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {2e799371} called on Looper (JavaBridge, tid 210) {72d6c48}, FYI main Looper is Looper (main, tid 1) {2e799371}) 12-29 03:54:04.102 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.webkit.WebView.checkThread(WebView.java:2194) 12-29 03:54:04.102 2793-2838/com.mt.nad.testwebapp W/System.err﹕ ... 7 more 12-29 03:54:04.127 2793-2793/com.mt.nad.testwebapp I/chromium﹕ [INFO:CONSOLE(19)] "Uncaught Error: Java exception was raised during method invocation", source: http://10.0.2.2/test-java-adapter/ (19) 12-29 03:54:04.159 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.175 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.274 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) 12-29 03:54:04.299 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.323 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.448 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) 12-29 03:54:04.468 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.499 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.527 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) 12-29 03:54:04.537 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.549 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.580 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) ``` source: ``` http://10.0.2.2/test-java-adapter/ (19) ``` is refer to ``` <input type="button" value="Go To Site" onClick="window.CallJavaAdapter.gotoSite()"> ``` If using Toast or TextView, in can change when click the button but for WebView loadurl(), it won't load... I refer to: [Android App: How to loadUrl in WebView from another class?](https://stackoverflow.com/questions/7915309/android-app-how-to-loadurl-in-webview-from-another-class) but still no luck...
2014/12/29
[ "https://Stackoverflow.com/questions/27683567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2983037/" ]
Here is Swift 3 version ``` extension NSAttributedString { func numberOfLines(with width: CGFloat) -> Int { let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))) let frameSetterRef : CTFramesetter = CTFramesetterCreateWithAttributedString(self as CFAttributedString) let frameRef: CTFrame = CTFramesetterCreateFrame(frameSetterRef, CFRangeMake(0, 0), path.cgPath, nil) let linesNS: NSArray = CTFrameGetLines(frameRef) guard let lines = linesNS as? [CTLine] else { return 0 } return lines.count } } ``` Hope this helps
Technically this doesn't answer the question of how to learn the number of lines of rendered text but I did find a solution to my problem so I thought I'd post it anyway. What I ended up doing was removing the width autolayout constraint on the label (actually the leading and trailing constraints to the superview) and added a center horizontally in container constraint to it. Then in `-[UIViewController viewDidLayoutSubviews]` I set `label.preferredMaxLayoutWidth=self.view.frame.size.width-margin`. The label's `textAlignment=NSTextAlignmentLeft`. This achieves the same effect of having the label centered if it is only one line and left justified if it is two or more.
27,683,567
I got error when i clicked button inside webview page. Suppposedly, when I click button, it will change to google site. Below are code and error:- MainActivity.java ``` package com.mt.nad.testwebapp; import android.content.Context; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { private WebView webC; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webC = (WebView)findViewById(R.id.webView1); webC.addJavascriptInterface(new JavaScriptInterface(), "CallJavaAdapter"); webC.setWebViewClient(new WebViewClient()); WebSettings webS = webC.getSettings(); webS.setJavaScriptEnabled(true); webC.loadUrl("http://10.0.2.2/test-java-adapter/"); } private class JavaScriptInterface{ JavaScriptInterface() { } @JavascriptInterface public void gotoSite() { //Toast.makeText(mContext, url, Toast.LENGTH_SHORT).show(); webC.clearCache(true); webC.loadUrl("http://google.com"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ``` activity\_main.xml ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" /> <WebView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/webView1" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> </RelativeLayout> ``` AndroidManifest.xml ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.mt.nad.testwebapp" > <uses-permission android:name="android.permission.INTERNET"></uses-permission> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> ``` index.html ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Test Only</title> <link rel="stylesheet" href=""> </head> <body> <div> <input type="button" value="Go To Site" onClick="window.CallJavaAdapter.gotoSite()"> </div> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> </body> </html> ``` LogCat ``` 12-29 03:54:04.099 2793-2838/com.mt.nad.testwebapp W/WebView﹕ java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {2e799371} called on Looper (JavaBridge, tid 210) {72d6c48}, FYI main Looper is Looper (main, tid 1) {2e799371}) at android.webkit.WebView.checkThread(WebView.java:2194) at android.webkit.WebView.clearCache(WebView.java:1451) at com.mt.nad.testwebapp.MainActivity$JavaScriptInterface.gotoSite(MainActivity.java:56) at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method) at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:28) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.os.HandlerThread.run(HandlerThread.java:61) 12-29 03:54:04.100 2793-2838/com.mt.nad.testwebapp W/System.err﹕ java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {2e799371} called on Looper (JavaBridge, tid 210) {72d6c48}, FYI main Looper is Looper (main, tid 1) {2e799371}) 12-29 03:54:04.100 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.webkit.WebView.checkThread(WebView.java:2204) 12-29 03:54:04.100 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.webkit.WebView.clearCache(WebView.java:1451) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at com.mt.nad.testwebapp.MainActivity$JavaScriptInterface.gotoSit (MainActivity.java:56) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:28) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.os.Looper.loop(Looper.java:135) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.os.HandlerThread.run(HandlerThread.java:61) 12-29 03:54:04.101 2793-2838/com.mt.nad.testwebapp W/System.err﹕ Caused by: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 1) {2e799371} called on Looper (JavaBridge, tid 210) {72d6c48}, FYI main Looper is Looper (main, tid 1) {2e799371}) 12-29 03:54:04.102 2793-2838/com.mt.nad.testwebapp W/System.err﹕ at android.webkit.WebView.checkThread(WebView.java:2194) 12-29 03:54:04.102 2793-2838/com.mt.nad.testwebapp W/System.err﹕ ... 7 more 12-29 03:54:04.127 2793-2793/com.mt.nad.testwebapp I/chromium﹕ [INFO:CONSOLE(19)] "Uncaught Error: Java exception was raised during method invocation", source: http://10.0.2.2/test-java-adapter/ (19) 12-29 03:54:04.159 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.175 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.274 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) 12-29 03:54:04.299 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.323 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.448 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) 12-29 03:54:04.468 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.499 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.527 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) 12-29 03:54:04.537 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000b44 12-29 03:54:04.549 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ glUtilsParamSize: unknow param 0x00000bd0 12-29 03:54:04.580 2793-2832/com.mt.nad.testwebapp E/eglCodecCommon﹕ **** ERROR unknown type 0x0 (glSizeof,72) ``` source: ``` http://10.0.2.2/test-java-adapter/ (19) ``` is refer to ``` <input type="button" value="Go To Site" onClick="window.CallJavaAdapter.gotoSite()"> ``` If using Toast or TextView, in can change when click the button but for WebView loadurl(), it won't load... I refer to: [Android App: How to loadUrl in WebView from another class?](https://stackoverflow.com/questions/7915309/android-app-how-to-loadurl-in-webview-from-another-class) but still no luck...
2014/12/29
[ "https://Stackoverflow.com/questions/27683567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2983037/" ]
Here is Swift 3 version ``` extension NSAttributedString { func numberOfLines(with width: CGFloat) -> Int { let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))) let frameSetterRef : CTFramesetter = CTFramesetterCreateWithAttributedString(self as CFAttributedString) let frameRef: CTFrame = CTFramesetterCreateFrame(frameSetterRef, CFRangeMake(0, 0), path.cgPath, nil) let linesNS: NSArray = CTFrameGetLines(frameRef) guard let lines = linesNS as? [CTLine] else { return 0 } return lines.count } } ``` Hope this helps
You can set your `UILabel` with `NSMutableAttributedString` like this: ``` UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)]; [contentLabel setLineBreakMode:NSLineBreakByWordWrapping]; [contentLabel setNumberOfLines:0]; [contentLabel setFont:[UIFont systemFontOfSize:13]; NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello I am a long sentence that should break over multiple lines"]; [string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(0, [string length])]; contentLabel.attributedText = string; ``` Hope this helps...
10,444,301
Does Google Search Appliance support wildcard characters in the query string. If no, is there any way I can fetch all the result set through my query?
2012/05/04
[ "https://Stackoverflow.com/questions/10444301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322171/" ]
Try this: ``` private void setIcon(String iconName) { Resources res = getResources(); int imageResource = res.getIdentifier("drawable/" + iconName, null, getPackageName()); Drawable image = res.getDrawable(imageResource); countryIcon.setBackgroundResource(image); } ```
If you've a pattern, is not difficult at all. Here's an example. I did this for loading flag-images in a ListView depending the flag IDs of each row-object. Once i've the language\_id i get the language\_KEY (String) which is the same as my icon's name: ``` int ico_id, int visible=View.visible(); String flag; Bitmap icona; flag= (MyWharehouse.getLangKey(language_id.get(position))).toLowerCase(); //get the image.png name ico_id = a.getResources().getIdentifier(flag, "drawable", a.getString(R.string.package_str)); icona = BitmapFactory.decodeResource(a.getResources(), ico_id); ((ImageView)a.findViewById(R.id.im_lang_01)).setImageBitmap(icona); //changing the image ```
27,769,608
I am using ui-calendar and I am trying to pass events without a time. Right now I get my date and time like this. ``` var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var WOD = new Date(y,m,d); ``` now I also have a function that changes WOD to the day that is selected in the month view of the calendar like this. ``` $scope.alertOnDayClick = function(d){ WOD = d; }; ``` If I click on a day (Jan 22 2015 for this example) `WOD = "2015-01-22T00:00:00.000Z"` <--This is what I want and works well. But if I don't select a day by default `WOD = "2015-01-04T05:00:00.000Z"` I want to make it so that my default date contains the time T00:00:00.000Z. I have tried ``` var WOD = new Date(y,m,d,0,0,0,0) var WOD = date.UTF(y,m,d) var WOD = date.UTF(y,m,d,0,0,0,0) ``` I also tried setting the default time to null I read this question [Dealing with DateTime format for international application](https://stackoverflow.com/questions/17509142/dealing-with-datetime-format-for-international-application) But I don't know if this is applicable and honestly I didn't fully understand how I would implement it All help is appreciated. UPDATE: After reading [What is the best way to initialize a JavaScript Date to midnight?](https://stackoverflow.com/questions/3894048/what-is-the-best-way-to-initialize-a-javascript-date-to-midnight) I tried ``` var WOD = new Date(); WOD.setHours(0,0,0,0); ``` But it still returns `"2015-01-04T05:00:00.000Z"` Which then makes the event stored on Jan 4 at 12am UPDATE: I tried: ``` $scope.WOD = new Date(); $scope.WOD.setHours(0, 0, 0, 0); $scope.dangerMessage = ($scope.WOD); {{dangerMessage}} = "2015-01-04T05:00:00.000Z" ``` UPDATE W/ Full controller ``` var myAppModule = angular.module('MyApp', ['ui.calendar']); myAppModule.controller('MyController', function($scope,$compile,uiCalendarConfig) { var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); $scope.WOD = new Date(); $scope.WOD.setHours(0, 0, 0, 0); $scope.events = [ {title: 'All Day Event', start: new Date(y, m, 1)}, {title: 'Long Event', start: new Date(y, m, d), end: new Date(y, m, d)}, {id: 999, title: 'Repeating Event', start: new Date(y, m, d - 3, 16, 0), allDay: false}, {id: 999, title: 'Repeating Event', start: new Date(y, m, d + 4, 16, 0), allDay: false}, { title: 'Birthday Party', start: new Date(y, m, d + 1, 19, 0), end: new Date(y, m, d + 1, 22, 30), allDay: false }, {title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29), url: 'http://google.com/'} ]; $scope.addEvent = function() { if($scope.WOD === ''){ $scope.dangerMessage = ('Please Choose a Date'); }else{ $scope.events.push({ title: 'Open Sesame', start: $scope.WOD, end: $scope.WOD, className: ['openSesame'] }); } $scope.dangerMessage = ($scope.WOD); }; $scope.alertOnEventClick = function( date ){ $scope.alertMessage = (date.title + ' was clicked '); }; $scope.alertOnDayClick = function(d){ uiCalendarConfig.calendars['CalDayView'].fullCalendar('gotoDate', d); WOD = d; $scope.dangerMessage = (WOD); }; /* remove event */ $scope.remove = function(index) { $scope.events.splice(index,1); }; /* config object */ $scope.uiDayConfig = { calendar:{ height: 450, editable: true, header:{ left: 'today', center: 'title', right: 'prev,next' }, timeFormat: '', defaultView: 'basicDay', defaultDate: new Date(), eventDrop: $scope.alertOnDrop, eventResize: $scope.alertOnResize, eventClick: $scope.alertOnEventClick, eventRender: $scope.eventRender } }; $scope.uiMonthConfig = { calendar:{ height: 450, editable: true, header:{ left: 'prev,next', center: 'title', right: 'basicWeek' }, dayClick: $scope.alertOnDayClick, //eventDrop: $scope.alertOnDrop, //eventResize: $scope.alertOnResize, eventClick: $scope.alertOnEventClick //eventRender: $scope.eventRender } }; $scope.eventSources = [$scope.events]; });//END MYCONTROLLER ```
2015/01/04
[ "https://Stackoverflow.com/questions/27769608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4123518/" ]
It is looks for me you have +5 hours in time zone. ``` var WOD = new Date(); WOD.setHours(0,0,0,0);// Sun Jan 04 2015 00:00:00 GMT-0600 (CST) var WOD = new Date(); WOD.setUTCHours(0,0,0,0);// Sat Jan 03 2015 18:00:00 GMT-0600 (CST) ``` All the difference in the settings of YOUR MACHINE. Check the settings of "Time Zone".
Please see demo below; ```js var app = angular.module('app', []); app.controller('firstCtrl', function($scope) { $scope.date = new Date(); $scope.date.setHours(0, 0, 0, 0); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="app"> <div ng-controller="firstCtrl"> {{date}} </div> </body> ```
86,256
Is there a way to manually format a section of my email in Google Inbox as a block quote? I don't see the option in the Inbox UI.
2015/11/03
[ "https://webapps.stackexchange.com/questions/86256", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/23452/" ]
It would appear to be not possible with Inbox as it currently exists. Bold, italic, underline, bulleted list, numbered list, are your formatting options. Simply selecting text and then pressing some format button is not an option (although it is in Gmail proper). It's possible that pasting from somewhere else might give you an indent that would be preserved, but I wouldn't count on it. Another option is likely to be [Templates](https://webapps.stackexchange.com/a/99895/354). For what it's worth, the Gmail keyboard shortcuts for bold, italic, bullet list, etc., seem to work, but `Ctrl`+`]` doesn't indent in Inbox. (It doesn't seem to do anything.) --- Since the product is still in preview mode, be sure to use the "Feedback" feature to let Google know that they're missing this feature.
Possible solution is using browser add-on like [Markdown Here](https://chrome.google.com/webstore/detail/markdown-here/elifhakcjgalahccnjkneoccemfahfoa?hl=en-US) (for Firefox it's [here](https://addons.mozilla.org/en-US/firefox/addon/markdown-here/)). It allows you to write whole e-mail in Markdown markup language as you do for example in Stack Exchange services. Take a look at my example e-mail: [![before click](https://i.stack.imgur.com/Bc2M6.png)](https://i.stack.imgur.com/Bc2M6.png) After all you can click on the add-on icon which makes the magic (you can also right click on text or even use default shortcut `Ctrl+Alt+M`): [![addon icon](https://i.stack.imgur.com/oXuFE.png)](https://i.stack.imgur.com/oXuFE.png) And *voilà*: [![after click](https://i.stack.imgur.com/o1lnh.png)](https://i.stack.imgur.com/o1lnh.png) It's obvious it would be easier to click `quote` button like in Gmail interface, but with this add-on you can format e-mail better than Gmail itself.
86,256
Is there a way to manually format a section of my email in Google Inbox as a block quote? I don't see the option in the Inbox UI.
2015/11/03
[ "https://webapps.stackexchange.com/questions/86256", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/23452/" ]
It would appear to be not possible with Inbox as it currently exists. Bold, italic, underline, bulleted list, numbered list, are your formatting options. Simply selecting text and then pressing some format button is not an option (although it is in Gmail proper). It's possible that pasting from somewhere else might give you an indent that would be preserved, but I wouldn't count on it. Another option is likely to be [Templates](https://webapps.stackexchange.com/a/99895/354). For what it's worth, the Gmail keyboard shortcuts for bold, italic, bullet list, etc., seem to work, but `Ctrl`+`]` doesn't indent in Inbox. (It doesn't seem to do anything.) --- Since the product is still in preview mode, be sure to use the "Feedback" feature to let Google know that they're missing this feature.
I found a more practical hack to enable citation blocks in Inbox: 1. Under `Inbox Settings:Templates`, create a new template. 2. In the window that appears, paste an empty citation block copied from a Gmail window. 3. Save that under a convenient name such as "citation block". Now, you can always insert a citation block in Inbox using this template. Look for the Templates icon and select "citation block".
86,256
Is there a way to manually format a section of my email in Google Inbox as a block quote? I don't see the option in the Inbox UI.
2015/11/03
[ "https://webapps.stackexchange.com/questions/86256", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/23452/" ]
It would appear to be not possible with Inbox as it currently exists. Bold, italic, underline, bulleted list, numbered list, are your formatting options. Simply selecting text and then pressing some format button is not an option (although it is in Gmail proper). It's possible that pasting from somewhere else might give you an indent that would be preserved, but I wouldn't count on it. Another option is likely to be [Templates](https://webapps.stackexchange.com/a/99895/354). For what it's worth, the Gmail keyboard shortcuts for bold, italic, bullet list, etc., seem to work, but `Ctrl`+`]` doesn't indent in Inbox. (It doesn't seem to do anything.) --- Since the product is still in preview mode, be sure to use the "Feedback" feature to let Google know that they're missing this feature.
When I run into this issue I compose my email message using the Gmail (not Inbox) user interface. Your partially composed but not-yet-sent messages will be in the Drafts folder (Gmail and Inbox - they are just two views of the same information).
86,256
Is there a way to manually format a section of my email in Google Inbox as a block quote? I don't see the option in the Inbox UI.
2015/11/03
[ "https://webapps.stackexchange.com/questions/86256", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/23452/" ]
Possible solution is using browser add-on like [Markdown Here](https://chrome.google.com/webstore/detail/markdown-here/elifhakcjgalahccnjkneoccemfahfoa?hl=en-US) (for Firefox it's [here](https://addons.mozilla.org/en-US/firefox/addon/markdown-here/)). It allows you to write whole e-mail in Markdown markup language as you do for example in Stack Exchange services. Take a look at my example e-mail: [![before click](https://i.stack.imgur.com/Bc2M6.png)](https://i.stack.imgur.com/Bc2M6.png) After all you can click on the add-on icon which makes the magic (you can also right click on text or even use default shortcut `Ctrl+Alt+M`): [![addon icon](https://i.stack.imgur.com/oXuFE.png)](https://i.stack.imgur.com/oXuFE.png) And *voilà*: [![after click](https://i.stack.imgur.com/o1lnh.png)](https://i.stack.imgur.com/o1lnh.png) It's obvious it would be easier to click `quote` button like in Gmail interface, but with this add-on you can format e-mail better than Gmail itself.
When I run into this issue I compose my email message using the Gmail (not Inbox) user interface. Your partially composed but not-yet-sent messages will be in the Drafts folder (Gmail and Inbox - they are just two views of the same information).
86,256
Is there a way to manually format a section of my email in Google Inbox as a block quote? I don't see the option in the Inbox UI.
2015/11/03
[ "https://webapps.stackexchange.com/questions/86256", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/23452/" ]
I found a more practical hack to enable citation blocks in Inbox: 1. Under `Inbox Settings:Templates`, create a new template. 2. In the window that appears, paste an empty citation block copied from a Gmail window. 3. Save that under a convenient name such as "citation block". Now, you can always insert a citation block in Inbox using this template. Look for the Templates icon and select "citation block".
When I run into this issue I compose my email message using the Gmail (not Inbox) user interface. Your partially composed but not-yet-sent messages will be in the Drafts folder (Gmail and Inbox - they are just two views of the same information).
14,019,398
I have these codes: Contents of **main.php**: **Javascript** ``` function grab() { $("#div_id").load("/test.php"); } ``` **HTML & PHP** ``` <? $original_value = 'Original content'; ?> <div id='div_id'><?=original_value;?></div> <form action="javascript:grab($('#div_id').val())"> <input name="submit" type="submit" value="submit"> </form> ``` also **test.php** ``` <?... $update_value = "Update content"; echo $update_value;?> ``` the result of test.php will be written into #div\_id and the result for div content is: ``` Original content Update content ``` But i like to overwrite original div value and the result should be: ``` Update content ``` I mean `echo` append a new line in #div\_id, but i like to overwrite existing #div\_id content.
2012/12/24
[ "https://Stackoverflow.com/questions/14019398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1906322/" ]
Change the following in your code. 1. Remove the javascript in your action attribute. It doesn't look right. ``` <form action=""> <input name="submit" type="submit" value="submit"> </form> ``` 2. Add the following javascript. ``` $(document).ready(function () { $('form').on('submit', function (e) { e.preventDefault(); // Prevents the default submit action. // Otherwise the page is reloaded. grab(); }); }); ``` The function `grab` will be called when the form is submitted. I'm not sure if this is what you want, but you should see the new contents in the div. **UPDATE 1:** I have removed the parameter from `grab` because the function doesn't need one.
You need to replace the content while the current code appends it, change code to: ``` $("#div_id").empty().load("/test.php"); ```
21,711,548
I am trying to learn/understand more about async/await in C# and I would put myself in rookie category so all your comments/suggestions are welcome. I wrote small test to have better understanding and clarification about await/async. My program freezes after "GetStringLength" call I tried reading several things but looks like I am stuck and I thought of taking expert opinion on what I might be doing wrong. Can you please guide me or point me in right direction here? ``` using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; namespace AsyncPatterns { class Program { static void Main(string[] args) { Program p = new Program(); Task<string> url = p.FindLargtestWebPage(new Uri[]{new Uri("http://www.google.com"), new Uri("http://www.facebook.com"), new Uri("http://www.bing.com") }); Console.WriteLine(url.Result); Console.ReadLine(); } public async Task<string> FindLargtestWebPage(Uri[] uris) { string highCountUrl = string.Empty; int maxCount = 0; foreach (Uri uri in uris) { Console.WriteLine(string.Format("Processing {0}", uri.ToString())); var pageContent = await GetWebPageString(uri); var count = await GetStringLength(pageContent); if (count > maxCount) { highCountUrl = uri.ToString(); } } return highCountUrl; } public async Task<int> GetStringLength(string pageData) { Console.WriteLine("Getting length"); return await new Task<int>(() => { return pageData.Length; }); } public async Task<string> GetWebPageString(Uri uri) { WebClient webClient = new WebClient(); Console.WriteLine("Downloading string"); return await webClient.DownloadStringTaskAsync(uri.ToString()); } } } ```
2014/02/11
[ "https://Stackoverflow.com/questions/21711548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3298748/" ]
The culprit for freezing is this: ``` return await new Task<int>(() => { return pageData.Length; }); ``` This `Task` constructor doesn't start the task, so you're creating a `Task` that isn't running. When you `await` on it in `GetStringLength` you're going to be waiting forever for the result. You can either start the task manually: ``` var result = new Task<int>(() => { return pageData.Length; }); result.Start(); return result; ``` or use the `Task.Run` static method, which will create and start the task: ``` return Task.Run(() => { return pageData.Length; }); ```
Do not use the `Task` constructor in `async` code, and only use `async` when you have asynchronous work to do. `GetStringLength` has no asynchronous work to do, so it should be: ``` public int GetStringLength(string pageData) { Console.WriteLine("Getting length"); return pageData.Length; } ``` For more information, see my [`async`/`await` intro](http://blog.stephencleary.com/2012/02/async-and-await.html).
8,537,377
Is there a reason why the same Java code will produce XML files with different order of the element attributes? My guess would be different JVM, but if so how can I predict which order it will produce? Some more details: I'm using `JAXB` XML binding.
2011/12/16
[ "https://Stackoverflow.com/questions/8537377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579840/" ]
> > Is there a reason why the same Java code will produce XML files with > different order of the element attributes? > > > Because the [XML spec says](http://www.w3.org/TR/REC-xml/#dt-attr) that the order of the attributes doesn't matter. Attributes are key-value pairs that serve the purpose of clarify the features of the element. Their order has no effect to the document structure, unlike the order of elements.
Different input. If it is truly the exact same Java code, then what might varying is the inputs. I'd be surprised if the reason a different JVM. I really need to know more to give you a better answer than that.
8,537,377
Is there a reason why the same Java code will produce XML files with different order of the element attributes? My guess would be different JVM, but if so how can I predict which order it will produce? Some more details: I'm using `JAXB` XML binding.
2011/12/16
[ "https://Stackoverflow.com/questions/8537377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579840/" ]
Chances are that the attributes are being kept internally in a hash table of some kind, with the attribute name used as a key. It's a characteristic of hash tables that they don't retain order. With many hashing algorithms the order will be consistent even though it isn't predictable, but sometimes it can depend on pseudo-random factors such as where the next chunk of free memory is found.
Different input. If it is truly the exact same Java code, then what might varying is the inputs. I'd be surprised if the reason a different JVM. I really need to know more to give you a better answer than that.
8,537,377
Is there a reason why the same Java code will produce XML files with different order of the element attributes? My guess would be different JVM, but if so how can I predict which order it will produce? Some more details: I'm using `JAXB` XML binding.
2011/12/16
[ "https://Stackoverflow.com/questions/8537377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579840/" ]
Chances are that the attributes are being kept internally in a hash table of some kind, with the attribute name used as a key. It's a characteristic of hash tables that they don't retain order. With many hashing algorithms the order will be consistent even though it isn't predictable, but sometimes it can depend on pseudo-random factors such as where the next chunk of free memory is found.
> > Is there a reason why the same Java code will produce XML files with > different order of the element attributes? > > > Because the [XML spec says](http://www.w3.org/TR/REC-xml/#dt-attr) that the order of the attributes doesn't matter. Attributes are key-value pairs that serve the purpose of clarify the features of the element. Their order has no effect to the document structure, unlike the order of elements.
47,455,229
I run the service in Docker Warm Mode with these labels: ``` - "traefik.docker.network=proxy" - "traefik.backend=kibana" - "traefik.frontend.entryPoints=https,http" - "traefik.frontend.rule=Host:mydomain" - "traefik.port=5601" - "traefik.frontend.auth.basic=test:098f6bcd4621d373cade4e832627b4f6" ``` And have this problem using HTTPS ``` curl -u test:test https://my-domain.com 401 Unauthorized ``` With HTTP all is ok ``` curl -u test:test http://my-domain.com Found ```
2017/11/23
[ "https://Stackoverflow.com/questions/47455229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8137317/" ]
Using `htpassword` solved it for me. It seems Traefik uses the same algorithm to unhash the passwords. ``` apt install apache2-utils htpasswd -nb your_username "your_password_here" ``` You will receive the according hash ``` your_username:khrglahfslgkha345346 ``` Copy paste it to your .toml or your docker-compose script. Use your password (not the hash) for the login on your frontend and everything will work fine.
I found cause of problem, I deploy service as a stack with traefik variable `"traefik.frontend.auth.basic=test:$$apr1$$EaOXV0L6$DQbzuXBeb6Y8jjI2ZbGsg/"`. But after deploy value of this variable looks like `test:/`. After manually setting correct value - auth work fine. Also I have tried deploy service with command docker service create and variable have correct value.
47,455,229
I run the service in Docker Warm Mode with these labels: ``` - "traefik.docker.network=proxy" - "traefik.backend=kibana" - "traefik.frontend.entryPoints=https,http" - "traefik.frontend.rule=Host:mydomain" - "traefik.port=5601" - "traefik.frontend.auth.basic=test:098f6bcd4621d373cade4e832627b4f6" ``` And have this problem using HTTPS ``` curl -u test:test https://my-domain.com 401 Unauthorized ``` With HTTP all is ok ``` curl -u test:test http://my-domain.com Found ```
2017/11/23
[ "https://Stackoverflow.com/questions/47455229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8137317/" ]
I have recently found out you have to take care of the double dollar signs in the resulting `hash`. You have to escape the `$` in different scenarios....
I found cause of problem, I deploy service as a stack with traefik variable `"traefik.frontend.auth.basic=test:$$apr1$$EaOXV0L6$DQbzuXBeb6Y8jjI2ZbGsg/"`. But after deploy value of this variable looks like `test:/`. After manually setting correct value - auth work fine. Also I have tried deploy service with command docker service create and variable have correct value.
47,455,229
I run the service in Docker Warm Mode with these labels: ``` - "traefik.docker.network=proxy" - "traefik.backend=kibana" - "traefik.frontend.entryPoints=https,http" - "traefik.frontend.rule=Host:mydomain" - "traefik.port=5601" - "traefik.frontend.auth.basic=test:098f6bcd4621d373cade4e832627b4f6" ``` And have this problem using HTTPS ``` curl -u test:test https://my-domain.com 401 Unauthorized ``` With HTTP all is ok ``` curl -u test:test http://my-domain.com Found ```
2017/11/23
[ "https://Stackoverflow.com/questions/47455229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8137317/" ]
Using `htpassword` solved it for me. It seems Traefik uses the same algorithm to unhash the passwords. ``` apt install apache2-utils htpasswd -nb your_username "your_password_here" ``` You will receive the according hash ``` your_username:khrglahfslgkha345346 ``` Copy paste it to your .toml or your docker-compose script. Use your password (not the hash) for the login on your frontend and everything will work fine.
I have recently found out you have to take care of the double dollar signs in the resulting `hash`. You have to escape the `$` in different scenarios....
12,677,670
I have a custom C# PowerShell Cmdlet (inheriting from the Cmdlet base class) and I want to be able to identify if the "-Verbose" parameter was specified when running the Cmdlet. I realize that WriteVerbose will output when the -Verbose parameter is specified, but I would like to actually do some other code when -Verbose is specified (i.e. not output the Console.Write values when -Verbose is specified). Thanks, John
2012/10/01
[ "https://Stackoverflow.com/questions/12677670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/941076/" ]
Check the cmdlet's bound parameters like so: ``` if (this.MyInvocation.BoundParameters.ContainsKey("Verbose")) { } ```
After much digging about, this works for me. Visual Studio 2013, Powershell 3.0 C# cmdlet using the PsCmdlet namespace. import-module .\mytest.dll, then mytest -verbose ``` blnVerbose = this.MyInvocation.Line.ToLower().Contains("-verbose"); ```
61,462,110
I have an Angular app running which uses an external api to get countries ISOs. This API uses https and it's giving me an error. The thing is: when I use a proxy in my angular local environment, mapping `/iso-api/` to the real url it works ok. ``` "/iso-api/*": { "target": "https://www...", "pathRewrite": { "^/iso-api": "" }, "secure": false, "changeOrigin": true, "logLevel": "debug" } ``` But I want this to work in production, so I want to use the real url. In my server I am returning the `Access-Control-Allow-Origin: *` header already. I've tried to run the angular server with ssl (as the external api uses https), but I receive the same error. I know a solution would be to implement the proxy in the server, but I believe this should not be done and there may be a way to retrieve this data from the frontend. Help please. Response -------- This is the network error in **Chrome**: [![browser network tab](https://i.stack.imgur.com/CsJ7l.png)](https://i.stack.imgur.com/CsJ7l.png) In **Firefox**, the request ends with 200 OK and returns data, but CORS error is thrown and I cannot access the data from the app: `CORS header 'Access-Control-Allow-Origin' missing` **General** ``` Request URL: https://www... Referrer Policy: no-referrer-when-downgrade ``` **Request headers** ``` :method: GET :scheme: https accept: application/json, text/plain, */* accept-encoding: gzip, deflate, br accept-language: es-ES,es;q=0.9,en;q=0.8 origin: http://localhost:4200 referer: http://localhost:4200/app/login sec-fetch-dest: empty sec-fetch-mode: cors sec-fetch-site: cross-site ``` **Response headers** ``` accept-ranges: bytes cache-control: max-age=0 content-encoding: gzip content-language: en-US content-length: 68356 content-type: application/json date: Mon, 27 Apr 2020 14:49:30 GMT expires: Mon, 27 Apr 2020 14:49:30 GMT referrer-policy: strict-origin-when-cross-origin server-timing: cdn-cache; desc=HIT server-timing: edge; dur=1 server-timing: ACTT;dur=0,ACRTT;dur=88 set-cookie: ... expires=Mon, 27 Apr 2020 16:49:30 GMT; max-age=7200; path=/; domain=...; HttpOnly set-cookie: ... Domain=...; Path=/; Expires=Mon, 27 Apr 2020 18:49:30 GMT; Max-Age=14400; HttpOnly set-cookie: ... Domain=...; Path=/; Expires=Tue, 27 Apr 2021 14:49:30 GMT; Max-Age=31536000; Secure status: 200 vary: Accept-Encoding ``` UPDATE ====== Angular service code ```js import { HttpClient } from '@angular/common/http'; ... constructor( private _http: HttpClient, private _errorUtil: ErrorUtilService, private _converter: StoreConverter ) {} ... getCountries(): Observable<CountryWithLanguages[]> { return this._http.get<GetStoresResponse>(API.storeUrl).pipe( catchError(this._errorUtil.handle), map(result => result.stores), switchMap(stores => stores), filter(this._isActiveStore), map(store => this._converter.toView(store)), toArray() ); } ``` To serve the app I use angular dev server, I do not add the 'Access-Control-Allow-Origin' header manually but, in the browser, I see that it is being added. [![Chrome Network tab](https://i.stack.imgur.com/LPDs2.png)](https://i.stack.imgur.com/LPDs2.png) angular.json ``` "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "push-web-app:build", "proxyConfig": "src/proxy-local.conf.json" }, } ```
2020/04/27
[ "https://Stackoverflow.com/questions/61462110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974681/" ]
You cannot bypass CORS browser side. If you are not able to modify the server side, your only solution is to use a proxy. For development purposes, you can use angular's built-in proxy server, but not for production. Here is a basic nginx config to do this ``` server { listen 80; server_name yourdomain.com; #domain where your angular code is deployed location /iso-api{ RewriteRule ^/iso-api/(.*)$ /$1 break; proxy_pass https://thirdpartyapidomain.com; #url of the API you are trying to access } location { #Your normal angular location #try_files ... } } ``` This will redirects requests like `http://yourdomain.com/iso-api/countriesList` to `https://thirdpartyapidomain.com/countriesList`; Since now client and server API calls are on the same domain, you should not have CORS issues
Use this site to resolve the CORS error: <https://cors-anywhere.herokuapp.com/> Use Exemple <https://cors-anywhere.herokuapp.com/https://freegeoip.app/json> ``` this._http.get('https://cors-anywhere.herokuapp.com/https://freegeoip.app/json') ``` It's just a workaround but it works. Use it even just to understand if the error is related to CORS or something else.
61,462,110
I have an Angular app running which uses an external api to get countries ISOs. This API uses https and it's giving me an error. The thing is: when I use a proxy in my angular local environment, mapping `/iso-api/` to the real url it works ok. ``` "/iso-api/*": { "target": "https://www...", "pathRewrite": { "^/iso-api": "" }, "secure": false, "changeOrigin": true, "logLevel": "debug" } ``` But I want this to work in production, so I want to use the real url. In my server I am returning the `Access-Control-Allow-Origin: *` header already. I've tried to run the angular server with ssl (as the external api uses https), but I receive the same error. I know a solution would be to implement the proxy in the server, but I believe this should not be done and there may be a way to retrieve this data from the frontend. Help please. Response -------- This is the network error in **Chrome**: [![browser network tab](https://i.stack.imgur.com/CsJ7l.png)](https://i.stack.imgur.com/CsJ7l.png) In **Firefox**, the request ends with 200 OK and returns data, but CORS error is thrown and I cannot access the data from the app: `CORS header 'Access-Control-Allow-Origin' missing` **General** ``` Request URL: https://www... Referrer Policy: no-referrer-when-downgrade ``` **Request headers** ``` :method: GET :scheme: https accept: application/json, text/plain, */* accept-encoding: gzip, deflate, br accept-language: es-ES,es;q=0.9,en;q=0.8 origin: http://localhost:4200 referer: http://localhost:4200/app/login sec-fetch-dest: empty sec-fetch-mode: cors sec-fetch-site: cross-site ``` **Response headers** ``` accept-ranges: bytes cache-control: max-age=0 content-encoding: gzip content-language: en-US content-length: 68356 content-type: application/json date: Mon, 27 Apr 2020 14:49:30 GMT expires: Mon, 27 Apr 2020 14:49:30 GMT referrer-policy: strict-origin-when-cross-origin server-timing: cdn-cache; desc=HIT server-timing: edge; dur=1 server-timing: ACTT;dur=0,ACRTT;dur=88 set-cookie: ... expires=Mon, 27 Apr 2020 16:49:30 GMT; max-age=7200; path=/; domain=...; HttpOnly set-cookie: ... Domain=...; Path=/; Expires=Mon, 27 Apr 2020 18:49:30 GMT; Max-Age=14400; HttpOnly set-cookie: ... Domain=...; Path=/; Expires=Tue, 27 Apr 2021 14:49:30 GMT; Max-Age=31536000; Secure status: 200 vary: Accept-Encoding ``` UPDATE ====== Angular service code ```js import { HttpClient } from '@angular/common/http'; ... constructor( private _http: HttpClient, private _errorUtil: ErrorUtilService, private _converter: StoreConverter ) {} ... getCountries(): Observable<CountryWithLanguages[]> { return this._http.get<GetStoresResponse>(API.storeUrl).pipe( catchError(this._errorUtil.handle), map(result => result.stores), switchMap(stores => stores), filter(this._isActiveStore), map(store => this._converter.toView(store)), toArray() ); } ``` To serve the app I use angular dev server, I do not add the 'Access-Control-Allow-Origin' header manually but, in the browser, I see that it is being added. [![Chrome Network tab](https://i.stack.imgur.com/LPDs2.png)](https://i.stack.imgur.com/LPDs2.png) angular.json ``` "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "push-web-app:build", "proxyConfig": "src/proxy-local.conf.json" }, } ```
2020/04/27
[ "https://Stackoverflow.com/questions/61462110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974681/" ]
You can't request a resource from another domain. This would be a security hole. You can read more here: [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) Sending `Access-Control-Allow-Origin: *` from your server won't give you access to the aforementioned API. The provider of this API needs to give you permission to access the API, you can't give yourself this permission. The error you posted states that the `Access-Control-Allow-Origin` header is missing. It means that the API isn't sending this header. There might be two reasons why this API isn't sending `Access-Control-Allow-Origin` header. 1. A misconfiguration on the side of this API. In this case you have to ask the provider of this API to fix this issue. 2. The API provider is restricting access to the API on purpose. In this case you have to ask the provider of this API to give you access from your domain. You can also proxy the request through your server. The core difference when using proxy is that your server reads the resource from the API and not the client browser. See [David's response](https://stackoverflow.com/a/61636482/5591753) on how to configure proxy with nginx.
Use this site to resolve the CORS error: <https://cors-anywhere.herokuapp.com/> Use Exemple <https://cors-anywhere.herokuapp.com/https://freegeoip.app/json> ``` this._http.get('https://cors-anywhere.herokuapp.com/https://freegeoip.app/json') ``` It's just a workaround but it works. Use it even just to understand if the error is related to CORS or something else.
61,462,110
I have an Angular app running which uses an external api to get countries ISOs. This API uses https and it's giving me an error. The thing is: when I use a proxy in my angular local environment, mapping `/iso-api/` to the real url it works ok. ``` "/iso-api/*": { "target": "https://www...", "pathRewrite": { "^/iso-api": "" }, "secure": false, "changeOrigin": true, "logLevel": "debug" } ``` But I want this to work in production, so I want to use the real url. In my server I am returning the `Access-Control-Allow-Origin: *` header already. I've tried to run the angular server with ssl (as the external api uses https), but I receive the same error. I know a solution would be to implement the proxy in the server, but I believe this should not be done and there may be a way to retrieve this data from the frontend. Help please. Response -------- This is the network error in **Chrome**: [![browser network tab](https://i.stack.imgur.com/CsJ7l.png)](https://i.stack.imgur.com/CsJ7l.png) In **Firefox**, the request ends with 200 OK and returns data, but CORS error is thrown and I cannot access the data from the app: `CORS header 'Access-Control-Allow-Origin' missing` **General** ``` Request URL: https://www... Referrer Policy: no-referrer-when-downgrade ``` **Request headers** ``` :method: GET :scheme: https accept: application/json, text/plain, */* accept-encoding: gzip, deflate, br accept-language: es-ES,es;q=0.9,en;q=0.8 origin: http://localhost:4200 referer: http://localhost:4200/app/login sec-fetch-dest: empty sec-fetch-mode: cors sec-fetch-site: cross-site ``` **Response headers** ``` accept-ranges: bytes cache-control: max-age=0 content-encoding: gzip content-language: en-US content-length: 68356 content-type: application/json date: Mon, 27 Apr 2020 14:49:30 GMT expires: Mon, 27 Apr 2020 14:49:30 GMT referrer-policy: strict-origin-when-cross-origin server-timing: cdn-cache; desc=HIT server-timing: edge; dur=1 server-timing: ACTT;dur=0,ACRTT;dur=88 set-cookie: ... expires=Mon, 27 Apr 2020 16:49:30 GMT; max-age=7200; path=/; domain=...; HttpOnly set-cookie: ... Domain=...; Path=/; Expires=Mon, 27 Apr 2020 18:49:30 GMT; Max-Age=14400; HttpOnly set-cookie: ... Domain=...; Path=/; Expires=Tue, 27 Apr 2021 14:49:30 GMT; Max-Age=31536000; Secure status: 200 vary: Accept-Encoding ``` UPDATE ====== Angular service code ```js import { HttpClient } from '@angular/common/http'; ... constructor( private _http: HttpClient, private _errorUtil: ErrorUtilService, private _converter: StoreConverter ) {} ... getCountries(): Observable<CountryWithLanguages[]> { return this._http.get<GetStoresResponse>(API.storeUrl).pipe( catchError(this._errorUtil.handle), map(result => result.stores), switchMap(stores => stores), filter(this._isActiveStore), map(store => this._converter.toView(store)), toArray() ); } ``` To serve the app I use angular dev server, I do not add the 'Access-Control-Allow-Origin' header manually but, in the browser, I see that it is being added. [![Chrome Network tab](https://i.stack.imgur.com/LPDs2.png)](https://i.stack.imgur.com/LPDs2.png) angular.json ``` "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "push-web-app:build", "proxyConfig": "src/proxy-local.conf.json" }, } ```
2020/04/27
[ "https://Stackoverflow.com/questions/61462110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974681/" ]
You cannot bypass CORS browser side. If you are not able to modify the server side, your only solution is to use a proxy. For development purposes, you can use angular's built-in proxy server, but not for production. Here is a basic nginx config to do this ``` server { listen 80; server_name yourdomain.com; #domain where your angular code is deployed location /iso-api{ RewriteRule ^/iso-api/(.*)$ /$1 break; proxy_pass https://thirdpartyapidomain.com; #url of the API you are trying to access } location { #Your normal angular location #try_files ... } } ``` This will redirects requests like `http://yourdomain.com/iso-api/countriesList` to `https://thirdpartyapidomain.com/countriesList`; Since now client and server API calls are on the same domain, you should not have CORS issues
Try the .get call with option **`withCredentials: true`**: ```js return this._http.get<GetStoresResponse>(API.storeUrl, { withCredentials: true }).pipe(); ``` ...and/or making sure your browsers are up to date.
61,462,110
I have an Angular app running which uses an external api to get countries ISOs. This API uses https and it's giving me an error. The thing is: when I use a proxy in my angular local environment, mapping `/iso-api/` to the real url it works ok. ``` "/iso-api/*": { "target": "https://www...", "pathRewrite": { "^/iso-api": "" }, "secure": false, "changeOrigin": true, "logLevel": "debug" } ``` But I want this to work in production, so I want to use the real url. In my server I am returning the `Access-Control-Allow-Origin: *` header already. I've tried to run the angular server with ssl (as the external api uses https), but I receive the same error. I know a solution would be to implement the proxy in the server, but I believe this should not be done and there may be a way to retrieve this data from the frontend. Help please. Response -------- This is the network error in **Chrome**: [![browser network tab](https://i.stack.imgur.com/CsJ7l.png)](https://i.stack.imgur.com/CsJ7l.png) In **Firefox**, the request ends with 200 OK and returns data, but CORS error is thrown and I cannot access the data from the app: `CORS header 'Access-Control-Allow-Origin' missing` **General** ``` Request URL: https://www... Referrer Policy: no-referrer-when-downgrade ``` **Request headers** ``` :method: GET :scheme: https accept: application/json, text/plain, */* accept-encoding: gzip, deflate, br accept-language: es-ES,es;q=0.9,en;q=0.8 origin: http://localhost:4200 referer: http://localhost:4200/app/login sec-fetch-dest: empty sec-fetch-mode: cors sec-fetch-site: cross-site ``` **Response headers** ``` accept-ranges: bytes cache-control: max-age=0 content-encoding: gzip content-language: en-US content-length: 68356 content-type: application/json date: Mon, 27 Apr 2020 14:49:30 GMT expires: Mon, 27 Apr 2020 14:49:30 GMT referrer-policy: strict-origin-when-cross-origin server-timing: cdn-cache; desc=HIT server-timing: edge; dur=1 server-timing: ACTT;dur=0,ACRTT;dur=88 set-cookie: ... expires=Mon, 27 Apr 2020 16:49:30 GMT; max-age=7200; path=/; domain=...; HttpOnly set-cookie: ... Domain=...; Path=/; Expires=Mon, 27 Apr 2020 18:49:30 GMT; Max-Age=14400; HttpOnly set-cookie: ... Domain=...; Path=/; Expires=Tue, 27 Apr 2021 14:49:30 GMT; Max-Age=31536000; Secure status: 200 vary: Accept-Encoding ``` UPDATE ====== Angular service code ```js import { HttpClient } from '@angular/common/http'; ... constructor( private _http: HttpClient, private _errorUtil: ErrorUtilService, private _converter: StoreConverter ) {} ... getCountries(): Observable<CountryWithLanguages[]> { return this._http.get<GetStoresResponse>(API.storeUrl).pipe( catchError(this._errorUtil.handle), map(result => result.stores), switchMap(stores => stores), filter(this._isActiveStore), map(store => this._converter.toView(store)), toArray() ); } ``` To serve the app I use angular dev server, I do not add the 'Access-Control-Allow-Origin' header manually but, in the browser, I see that it is being added. [![Chrome Network tab](https://i.stack.imgur.com/LPDs2.png)](https://i.stack.imgur.com/LPDs2.png) angular.json ``` "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "push-web-app:build", "proxyConfig": "src/proxy-local.conf.json" }, } ```
2020/04/27
[ "https://Stackoverflow.com/questions/61462110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974681/" ]
You can't request a resource from another domain. This would be a security hole. You can read more here: [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) Sending `Access-Control-Allow-Origin: *` from your server won't give you access to the aforementioned API. The provider of this API needs to give you permission to access the API, you can't give yourself this permission. The error you posted states that the `Access-Control-Allow-Origin` header is missing. It means that the API isn't sending this header. There might be two reasons why this API isn't sending `Access-Control-Allow-Origin` header. 1. A misconfiguration on the side of this API. In this case you have to ask the provider of this API to fix this issue. 2. The API provider is restricting access to the API on purpose. In this case you have to ask the provider of this API to give you access from your domain. You can also proxy the request through your server. The core difference when using proxy is that your server reads the resource from the API and not the client browser. See [David's response](https://stackoverflow.com/a/61636482/5591753) on how to configure proxy with nginx.
Try the .get call with option **`withCredentials: true`**: ```js return this._http.get<GetStoresResponse>(API.storeUrl, { withCredentials: true }).pipe(); ``` ...and/or making sure your browsers are up to date.
61,462,110
I have an Angular app running which uses an external api to get countries ISOs. This API uses https and it's giving me an error. The thing is: when I use a proxy in my angular local environment, mapping `/iso-api/` to the real url it works ok. ``` "/iso-api/*": { "target": "https://www...", "pathRewrite": { "^/iso-api": "" }, "secure": false, "changeOrigin": true, "logLevel": "debug" } ``` But I want this to work in production, so I want to use the real url. In my server I am returning the `Access-Control-Allow-Origin: *` header already. I've tried to run the angular server with ssl (as the external api uses https), but I receive the same error. I know a solution would be to implement the proxy in the server, but I believe this should not be done and there may be a way to retrieve this data from the frontend. Help please. Response -------- This is the network error in **Chrome**: [![browser network tab](https://i.stack.imgur.com/CsJ7l.png)](https://i.stack.imgur.com/CsJ7l.png) In **Firefox**, the request ends with 200 OK and returns data, but CORS error is thrown and I cannot access the data from the app: `CORS header 'Access-Control-Allow-Origin' missing` **General** ``` Request URL: https://www... Referrer Policy: no-referrer-when-downgrade ``` **Request headers** ``` :method: GET :scheme: https accept: application/json, text/plain, */* accept-encoding: gzip, deflate, br accept-language: es-ES,es;q=0.9,en;q=0.8 origin: http://localhost:4200 referer: http://localhost:4200/app/login sec-fetch-dest: empty sec-fetch-mode: cors sec-fetch-site: cross-site ``` **Response headers** ``` accept-ranges: bytes cache-control: max-age=0 content-encoding: gzip content-language: en-US content-length: 68356 content-type: application/json date: Mon, 27 Apr 2020 14:49:30 GMT expires: Mon, 27 Apr 2020 14:49:30 GMT referrer-policy: strict-origin-when-cross-origin server-timing: cdn-cache; desc=HIT server-timing: edge; dur=1 server-timing: ACTT;dur=0,ACRTT;dur=88 set-cookie: ... expires=Mon, 27 Apr 2020 16:49:30 GMT; max-age=7200; path=/; domain=...; HttpOnly set-cookie: ... Domain=...; Path=/; Expires=Mon, 27 Apr 2020 18:49:30 GMT; Max-Age=14400; HttpOnly set-cookie: ... Domain=...; Path=/; Expires=Tue, 27 Apr 2021 14:49:30 GMT; Max-Age=31536000; Secure status: 200 vary: Accept-Encoding ``` UPDATE ====== Angular service code ```js import { HttpClient } from '@angular/common/http'; ... constructor( private _http: HttpClient, private _errorUtil: ErrorUtilService, private _converter: StoreConverter ) {} ... getCountries(): Observable<CountryWithLanguages[]> { return this._http.get<GetStoresResponse>(API.storeUrl).pipe( catchError(this._errorUtil.handle), map(result => result.stores), switchMap(stores => stores), filter(this._isActiveStore), map(store => this._converter.toView(store)), toArray() ); } ``` To serve the app I use angular dev server, I do not add the 'Access-Control-Allow-Origin' header manually but, in the browser, I see that it is being added. [![Chrome Network tab](https://i.stack.imgur.com/LPDs2.png)](https://i.stack.imgur.com/LPDs2.png) angular.json ``` "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "push-web-app:build", "proxyConfig": "src/proxy-local.conf.json" }, } ```
2020/04/27
[ "https://Stackoverflow.com/questions/61462110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1974681/" ]
You can't request a resource from another domain. This would be a security hole. You can read more here: [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) Sending `Access-Control-Allow-Origin: *` from your server won't give you access to the aforementioned API. The provider of this API needs to give you permission to access the API, you can't give yourself this permission. The error you posted states that the `Access-Control-Allow-Origin` header is missing. It means that the API isn't sending this header. There might be two reasons why this API isn't sending `Access-Control-Allow-Origin` header. 1. A misconfiguration on the side of this API. In this case you have to ask the provider of this API to fix this issue. 2. The API provider is restricting access to the API on purpose. In this case you have to ask the provider of this API to give you access from your domain. You can also proxy the request through your server. The core difference when using proxy is that your server reads the resource from the API and not the client browser. See [David's response](https://stackoverflow.com/a/61636482/5591753) on how to configure proxy with nginx.
You cannot bypass CORS browser side. If you are not able to modify the server side, your only solution is to use a proxy. For development purposes, you can use angular's built-in proxy server, but not for production. Here is a basic nginx config to do this ``` server { listen 80; server_name yourdomain.com; #domain where your angular code is deployed location /iso-api{ RewriteRule ^/iso-api/(.*)$ /$1 break; proxy_pass https://thirdpartyapidomain.com; #url of the API you are trying to access } location { #Your normal angular location #try_files ... } } ``` This will redirects requests like `http://yourdomain.com/iso-api/countriesList` to `https://thirdpartyapidomain.com/countriesList`; Since now client and server API calls are on the same domain, you should not have CORS issues
40,283,338
So guys, I am building a website using HTML, Javascript and CSS, and I have a file input but for some reason it won't get completely centered. ```css body { width: 100%; height: 100%; margin: auto; text-align: center; } #inp { text-align: center; margin: auto; } ``` ```html <input id="inp" type="file" accept="image/*"> ```
2016/10/27
[ "https://Stackoverflow.com/questions/40283338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7055037/" ]
It works fine, can we get the entire code ? ```css body { width: 100%; height: 100%; margin: auto; text-align: center; } #inp { text-align: center; margin: auto; } ``` ```html <body> <input id="inp" type="file" accept="image/*"> </body> ```
Not sure if you want to achieve this, but take a look at this [Fiddle](https://jsfiddle.net/cy90xeze/7/) ``` #inp { text-align: center; margin: auto; position: absolute; top: 50%; } ```
40,283,338
So guys, I am building a website using HTML, Javascript and CSS, and I have a file input but for some reason it won't get completely centered. ```css body { width: 100%; height: 100%; margin: auto; text-align: center; } #inp { text-align: center; margin: auto; } ``` ```html <input id="inp" type="file" accept="image/*"> ```
2016/10/27
[ "https://Stackoverflow.com/questions/40283338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7055037/" ]
It works fine, can we get the entire code ? ```css body { width: 100%; height: 100%; margin: auto; text-align: center; } #inp { text-align: center; margin: auto; } ``` ```html <body> <input id="inp" type="file" accept="image/*"> </body> ```
**CSS solution for most recents browsers** More detail on browsers support : <http://caniuse.com/#search=vw> CSS3 introduced `vw, vh` units that take advantage of visible screen size. Here is an example showing how you might use those value to set `width` and `height` properties of your div to `100vw` (which means 100% of the Visible Width of the screen) and `100vh` (which means 100% of the Visible Height of the screen) : ```css body { margin : 0px; } .fullscreen { width : 100vw; height : 100vh; } .table-cell { display : table-cell; background : lightgrey; } .valign-middle { vertical-align : middle; } .text-center { text-align : center; } ``` ```html <div class="fullscreen table-cell valign-middle text-center"> <input type="file" /> </div> ```
40,283,338
So guys, I am building a website using HTML, Javascript and CSS, and I have a file input but for some reason it won't get completely centered. ```css body { width: 100%; height: 100%; margin: auto; text-align: center; } #inp { text-align: center; margin: auto; } ``` ```html <input id="inp" type="file" accept="image/*"> ```
2016/10/27
[ "https://Stackoverflow.com/questions/40283338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7055037/" ]
It works fine, can we get the entire code ? ```css body { width: 100%; height: 100%; margin: auto; text-align: center; } #inp { text-align: center; margin: auto; } ``` ```html <body> <input id="inp" type="file" accept="image/*"> </body> ```
You can center the input file by enclosing it in a tag and then adding CSS to it.
40,283,338
So guys, I am building a website using HTML, Javascript and CSS, and I have a file input but for some reason it won't get completely centered. ```css body { width: 100%; height: 100%; margin: auto; text-align: center; } #inp { text-align: center; margin: auto; } ``` ```html <input id="inp" type="file" accept="image/*"> ```
2016/10/27
[ "https://Stackoverflow.com/questions/40283338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7055037/" ]
**CSS solution for most recents browsers** More detail on browsers support : <http://caniuse.com/#search=vw> CSS3 introduced `vw, vh` units that take advantage of visible screen size. Here is an example showing how you might use those value to set `width` and `height` properties of your div to `100vw` (which means 100% of the Visible Width of the screen) and `100vh` (which means 100% of the Visible Height of the screen) : ```css body { margin : 0px; } .fullscreen { width : 100vw; height : 100vh; } .table-cell { display : table-cell; background : lightgrey; } .valign-middle { vertical-align : middle; } .text-center { text-align : center; } ``` ```html <div class="fullscreen table-cell valign-middle text-center"> <input type="file" /> </div> ```
Not sure if you want to achieve this, but take a look at this [Fiddle](https://jsfiddle.net/cy90xeze/7/) ``` #inp { text-align: center; margin: auto; position: absolute; top: 50%; } ```
40,283,338
So guys, I am building a website using HTML, Javascript and CSS, and I have a file input but for some reason it won't get completely centered. ```css body { width: 100%; height: 100%; margin: auto; text-align: center; } #inp { text-align: center; margin: auto; } ``` ```html <input id="inp" type="file" accept="image/*"> ```
2016/10/27
[ "https://Stackoverflow.com/questions/40283338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7055037/" ]
Not sure if you want to achieve this, but take a look at this [Fiddle](https://jsfiddle.net/cy90xeze/7/) ``` #inp { text-align: center; margin: auto; position: absolute; top: 50%; } ```
You can center the input file by enclosing it in a tag and then adding CSS to it.
40,283,338
So guys, I am building a website using HTML, Javascript and CSS, and I have a file input but for some reason it won't get completely centered. ```css body { width: 100%; height: 100%; margin: auto; text-align: center; } #inp { text-align: center; margin: auto; } ``` ```html <input id="inp" type="file" accept="image/*"> ```
2016/10/27
[ "https://Stackoverflow.com/questions/40283338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7055037/" ]
**CSS solution for most recents browsers** More detail on browsers support : <http://caniuse.com/#search=vw> CSS3 introduced `vw, vh` units that take advantage of visible screen size. Here is an example showing how you might use those value to set `width` and `height` properties of your div to `100vw` (which means 100% of the Visible Width of the screen) and `100vh` (which means 100% of the Visible Height of the screen) : ```css body { margin : 0px; } .fullscreen { width : 100vw; height : 100vh; } .table-cell { display : table-cell; background : lightgrey; } .valign-middle { vertical-align : middle; } .text-center { text-align : center; } ``` ```html <div class="fullscreen table-cell valign-middle text-center"> <input type="file" /> </div> ```
You can center the input file by enclosing it in a tag and then adding CSS to it.
25,260,446
I have a logout function that looks like this. > > > ``` > if ($_GET["argument"]=='logOut'){ > if(session_id() == '') { > session_start(); > } > session_unset(); > session_destroy(); > $host = $_SERVER['HTTP_HOST']; > $extra = 'index.php'; > header("Location: http://$host/$extra"); > exit; > } > > ``` > > My problem is that, If I inspect the page and look at the `Network` preview and response, it looks 'fine'. There are two php files listed that was processed. `http://localhost:5000/inc/mainScripts.php?argument=logOut` which is where the function is located. and `http://localhost:5000/index.php` Which is where i would like to be redirected. The `Response` tab in the `Network` of the inspect page area in chrome contains the full login html page `login.php` but in the browser it remains in the same place. Like the `header` command has never been called. What Am I doing wrong? **HTML AJAX call to this function:** > > > ``` > $("#logout_btn").click(function() { > $.ajax({ > url: './inc/mainScripts.php?argument=logOut' > }) > }); > > ``` > > --- **SOLUTION** ------------ ***AJAX*** > > > ``` > $("#logout_btn").click(function() { > $.ajax({ > url: './inc/mainScripts.php?argument=logOut', > success: function(data){ > window.location.href = data; > } > }); > }); > > ``` > > ***PHP*** > > > ``` > if ($_GET["argument"]=='logOut'){ > if(session_id() == '') { > session_start(); > } > session_unset(); > session_destroy(); > $host = $_SERVER['HTTP_HOST']; > $link = "http://$host/index.php"; > echo $link; > } > > ``` > >
2014/08/12
[ "https://Stackoverflow.com/questions/25260446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I suggest using a CSS class for adding the border and to add / remove it like below CSS: ``` .borderRed { border : 1px solid red; } ``` jQuery: ``` //remove border from old link $('.borderRed').removeClass('borderRed'); // add border in new link $(eventC.target.parentNode).addClass('borderRed'); ```
If I clearly understand your question, you need something like this ``` var container = $("div.parent").on("click", "a", function(){ $(this).addClass("selected"); container.find("a").not($(this)).removeClass("selected"); }); ``` [demo](http://jsfiddle.net/bbdL7cpL/)
25,260,446
I have a logout function that looks like this. > > > ``` > if ($_GET["argument"]=='logOut'){ > if(session_id() == '') { > session_start(); > } > session_unset(); > session_destroy(); > $host = $_SERVER['HTTP_HOST']; > $extra = 'index.php'; > header("Location: http://$host/$extra"); > exit; > } > > ``` > > My problem is that, If I inspect the page and look at the `Network` preview and response, it looks 'fine'. There are two php files listed that was processed. `http://localhost:5000/inc/mainScripts.php?argument=logOut` which is where the function is located. and `http://localhost:5000/index.php` Which is where i would like to be redirected. The `Response` tab in the `Network` of the inspect page area in chrome contains the full login html page `login.php` but in the browser it remains in the same place. Like the `header` command has never been called. What Am I doing wrong? **HTML AJAX call to this function:** > > > ``` > $("#logout_btn").click(function() { > $.ajax({ > url: './inc/mainScripts.php?argument=logOut' > }) > }); > > ``` > > --- **SOLUTION** ------------ ***AJAX*** > > > ``` > $("#logout_btn").click(function() { > $.ajax({ > url: './inc/mainScripts.php?argument=logOut', > success: function(data){ > window.location.href = data; > } > }); > }); > > ``` > > ***PHP*** > > > ``` > if ($_GET["argument"]=='logOut'){ > if(session_id() == '') { > session_start(); > } > session_unset(); > session_destroy(); > $host = $_SERVER['HTTP_HOST']; > $link = "http://$host/index.php"; > echo $link; > } > > ``` > >
2014/08/12
[ "https://Stackoverflow.com/questions/25260446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I suggest using a CSS class for adding the border and to add / remove it like below CSS: ``` .borderRed { border : 1px solid red; } ``` jQuery: ``` //remove border from old link $('.borderRed').removeClass('borderRed'); // add border in new link $(eventC.target.parentNode).addClass('borderRed'); ```
This solution may be as: ``` Backbone.View.extend ({ events: { "event-which-delete-border a.link":"changeLink", "event-which-add-border a.link":"changeLink" }, changeLink:function(event) { if (event.type == 'event-which-delete-border') { $('a.link').css('border', 'none'); } else if (event.type == 'event-which-add-border') $('a.link').css('border', '1px solid red'); } }) ``` In this example, words 'event-which-delete-border' and 'event-which-add-border' may be all events from JavaScript, such as 'click' 'mouseover' and etc
25,260,446
I have a logout function that looks like this. > > > ``` > if ($_GET["argument"]=='logOut'){ > if(session_id() == '') { > session_start(); > } > session_unset(); > session_destroy(); > $host = $_SERVER['HTTP_HOST']; > $extra = 'index.php'; > header("Location: http://$host/$extra"); > exit; > } > > ``` > > My problem is that, If I inspect the page and look at the `Network` preview and response, it looks 'fine'. There are two php files listed that was processed. `http://localhost:5000/inc/mainScripts.php?argument=logOut` which is where the function is located. and `http://localhost:5000/index.php` Which is where i would like to be redirected. The `Response` tab in the `Network` of the inspect page area in chrome contains the full login html page `login.php` but in the browser it remains in the same place. Like the `header` command has never been called. What Am I doing wrong? **HTML AJAX call to this function:** > > > ``` > $("#logout_btn").click(function() { > $.ajax({ > url: './inc/mainScripts.php?argument=logOut' > }) > }); > > ``` > > --- **SOLUTION** ------------ ***AJAX*** > > > ``` > $("#logout_btn").click(function() { > $.ajax({ > url: './inc/mainScripts.php?argument=logOut', > success: function(data){ > window.location.href = data; > } > }); > }); > > ``` > > ***PHP*** > > > ``` > if ($_GET["argument"]=='logOut'){ > if(session_id() == '') { > session_start(); > } > session_unset(); > session_destroy(); > $host = $_SERVER['HTTP_HOST']; > $link = "http://$host/index.php"; > echo $link; > } > > ``` > >
2014/08/12
[ "https://Stackoverflow.com/questions/25260446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I suggest using a CSS class for adding the border and to add / remove it like below CSS: ``` .borderRed { border : 1px solid red; } ``` jQuery: ``` //remove border from old link $('.borderRed').removeClass('borderRed'); // add border in new link $(eventC.target.parentNode).addClass('borderRed'); ```
You can use any of these three methods- 1. you can use the .attr() to change the style of the element. ``` $(OLDLINK).attr('style', 'border: none'); $(NewLINK).attr('style','border: 1px solid red'); ``` this method is safe to cross browser defects. 2. the one you are using. 3. you can use the method as explained by Bhushan above. the difference between these could be found here- [Visibility attribute question](https://stackoverflow.com/questions/2690865/visibility-attribute-question)
25,260,446
I have a logout function that looks like this. > > > ``` > if ($_GET["argument"]=='logOut'){ > if(session_id() == '') { > session_start(); > } > session_unset(); > session_destroy(); > $host = $_SERVER['HTTP_HOST']; > $extra = 'index.php'; > header("Location: http://$host/$extra"); > exit; > } > > ``` > > My problem is that, If I inspect the page and look at the `Network` preview and response, it looks 'fine'. There are two php files listed that was processed. `http://localhost:5000/inc/mainScripts.php?argument=logOut` which is where the function is located. and `http://localhost:5000/index.php` Which is where i would like to be redirected. The `Response` tab in the `Network` of the inspect page area in chrome contains the full login html page `login.php` but in the browser it remains in the same place. Like the `header` command has never been called. What Am I doing wrong? **HTML AJAX call to this function:** > > > ``` > $("#logout_btn").click(function() { > $.ajax({ > url: './inc/mainScripts.php?argument=logOut' > }) > }); > > ``` > > --- **SOLUTION** ------------ ***AJAX*** > > > ``` > $("#logout_btn").click(function() { > $.ajax({ > url: './inc/mainScripts.php?argument=logOut', > success: function(data){ > window.location.href = data; > } > }); > }); > > ``` > > ***PHP*** > > > ``` > if ($_GET["argument"]=='logOut'){ > if(session_id() == '') { > session_start(); > } > session_unset(); > session_destroy(); > $host = $_SERVER['HTTP_HOST']; > $link = "http://$host/index.php"; > echo $link; > } > > ``` > >
2014/08/12
[ "https://Stackoverflow.com/questions/25260446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If I clearly understand your question, you need something like this ``` var container = $("div.parent").on("click", "a", function(){ $(this).addClass("selected"); container.find("a").not($(this)).removeClass("selected"); }); ``` [demo](http://jsfiddle.net/bbdL7cpL/)
This solution may be as: ``` Backbone.View.extend ({ events: { "event-which-delete-border a.link":"changeLink", "event-which-add-border a.link":"changeLink" }, changeLink:function(event) { if (event.type == 'event-which-delete-border') { $('a.link').css('border', 'none'); } else if (event.type == 'event-which-add-border') $('a.link').css('border', '1px solid red'); } }) ``` In this example, words 'event-which-delete-border' and 'event-which-add-border' may be all events from JavaScript, such as 'click' 'mouseover' and etc
25,260,446
I have a logout function that looks like this. > > > ``` > if ($_GET["argument"]=='logOut'){ > if(session_id() == '') { > session_start(); > } > session_unset(); > session_destroy(); > $host = $_SERVER['HTTP_HOST']; > $extra = 'index.php'; > header("Location: http://$host/$extra"); > exit; > } > > ``` > > My problem is that, If I inspect the page and look at the `Network` preview and response, it looks 'fine'. There are two php files listed that was processed. `http://localhost:5000/inc/mainScripts.php?argument=logOut` which is where the function is located. and `http://localhost:5000/index.php` Which is where i would like to be redirected. The `Response` tab in the `Network` of the inspect page area in chrome contains the full login html page `login.php` but in the browser it remains in the same place. Like the `header` command has never been called. What Am I doing wrong? **HTML AJAX call to this function:** > > > ``` > $("#logout_btn").click(function() { > $.ajax({ > url: './inc/mainScripts.php?argument=logOut' > }) > }); > > ``` > > --- **SOLUTION** ------------ ***AJAX*** > > > ``` > $("#logout_btn").click(function() { > $.ajax({ > url: './inc/mainScripts.php?argument=logOut', > success: function(data){ > window.location.href = data; > } > }); > }); > > ``` > > ***PHP*** > > > ``` > if ($_GET["argument"]=='logOut'){ > if(session_id() == '') { > session_start(); > } > session_unset(); > session_destroy(); > $host = $_SERVER['HTTP_HOST']; > $link = "http://$host/index.php"; > echo $link; > } > > ``` > >
2014/08/12
[ "https://Stackoverflow.com/questions/25260446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If I clearly understand your question, you need something like this ``` var container = $("div.parent").on("click", "a", function(){ $(this).addClass("selected"); container.find("a").not($(this)).removeClass("selected"); }); ``` [demo](http://jsfiddle.net/bbdL7cpL/)
You can use any of these three methods- 1. you can use the .attr() to change the style of the element. ``` $(OLDLINK).attr('style', 'border: none'); $(NewLINK).attr('style','border: 1px solid red'); ``` this method is safe to cross browser defects. 2. the one you are using. 3. you can use the method as explained by Bhushan above. the difference between these could be found here- [Visibility attribute question](https://stackoverflow.com/questions/2690865/visibility-attribute-question)
89,664
I am a new user at Stack Overflow, and I have registered in some other forums too. I found that at Stack Overflow, we get the fastest replies to my questions and it's very well-organized (like choosing an appropriate answer, giving votes, and many more that I don't know). As far as learning a programming language is concerned, there are multiple ways to do it: 1. A person can teach you like getting tuition from somebody. Plus I have to read and program after my teacher finishes his classes. [*most efficient and faster*] 2. I can read myself and learn everything on my own. [*least efficient*] 3. There are a lot of video tutorials on programming by experts available online (e.g. on YouTube and Google Video). We need to pay for some of them. Plus reading and learning. [*most efficient and faster*] I have found the 3rd option quite comfortable and helpful. Should Stack Overflow or other sites allow video tutorials? Please share your thoughts with me.
2011/05/03
[ "https://meta.stackexchange.com/questions/89664", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/161141/" ]
Stackoverflow answers can link to videos but SO is not meant to be a tutorial site. The main premise is Q&A, so if you have a question, you ask it and someone else answers it. Depending on the type of question you ask, the answer can be either very descriptive or terse and not like a tutorial at all. Also, I don't really agree with you marking option 2 as the least efficient. This would depend on personalities, I'm terrible at learning in classes, I tend to learn by diving in and then back tracking to find out what the 'correct' way to do something is.
There's nothing wrong with video tutorials but the stack exchange sites (or at least the "big 3" computing sites) are *not that kind of website*. We're not all about "teach yourself to program\build a server in 24 hours", we're more "Have a specific question about programming\server building? - Here's some specific answers". Note the "specific" - that's an important part of the equation and the reason video tutorials won't work here. Unless you're expecting video answers to every question (good luck with that) then videos would move us from that kind specific solutions to specific problems to generic tutorials, which would then generate specific questions which would need to be answered with text anyway ("In the Objective C video you installed Apple's XCode 3.2, is it OK to install XCode 4.0 instead?"). The best we could hope for from those questions is that we'd be led in a big circle back to where we are now. The worse is that we become another [videojug](http://www.videojug.com/) - a great resource as it happens but you only need one of those and it's already there.
89,664
I am a new user at Stack Overflow, and I have registered in some other forums too. I found that at Stack Overflow, we get the fastest replies to my questions and it's very well-organized (like choosing an appropriate answer, giving votes, and many more that I don't know). As far as learning a programming language is concerned, there are multiple ways to do it: 1. A person can teach you like getting tuition from somebody. Plus I have to read and program after my teacher finishes his classes. [*most efficient and faster*] 2. I can read myself and learn everything on my own. [*least efficient*] 3. There are a lot of video tutorials on programming by experts available online (e.g. on YouTube and Google Video). We need to pay for some of them. Plus reading and learning. [*most efficient and faster*] I have found the 3rd option quite comfortable and helpful. Should Stack Overflow or other sites allow video tutorials? Please share your thoughts with me.
2011/05/03
[ "https://meta.stackexchange.com/questions/89664", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/161141/" ]
Stackoverflow answers can link to videos but SO is not meant to be a tutorial site. The main premise is Q&A, so if you have a question, you ask it and someone else answers it. Depending on the type of question you ask, the answer can be either very descriptive or terse and not like a tutorial at all. Also, I don't really agree with you marking option 2 as the least efficient. This would depend on personalities, I'm terrible at learning in classes, I tend to learn by diving in and then back tracking to find out what the 'correct' way to do something is.
Why all the negative votes? This is a good question (because I came here to ask it), glad I didn't - geeze! Two days after your post, Jeff Atwood (the co-creator of Stack Exchange/Overflow) had this to say: > > We are potentially enabling this on a > site-by-site basis, as needed... Make > the case for it on your site's meta, > as it is a site specific decision. > > > I lifted that quote from here: [Adding Support for Video or Slideshow of Images](https://meta.stackexchange.com/questions/78501/adding-support-for-video-or-slideshow-of-images). So the question isn't: "*Can it be done?*", but rather, "*Should it be done and what are the potential drawbacks of doing so?*". For StackOverflow it sounds like a great idea because I'm too lazy to write up all the steps to do something when I can just use Camtasia to record a quick video and upload it. But here are the cons: 1. You can't google or site-search what the user is saying or the code they're displaying in a video. 2. You can't copy/paste the code you see in a video - again, I'm lazy. 3. Video adds cost to a site if they are hosting and streaming uploaded media. 4. If you use YouTube it's even less reliable as accounts can be deactivated, content can be removed for copywrite violations, or users can just delete the video. 5. Bad people can add ads or update the video later to promote something else after getting a high vote-count. 6. The community can't edit the videos. Just like Twitter can force you to concentrate what you're saying into 140 characters or less, making the effort to type up an good answer that'll win votes and allowing the community to edit and sharpen those answers only increases the quality of content on sites like Stack Overflow. Well, I came here to ask this question and I ended up answering it for myself. Thanks!
89,664
I am a new user at Stack Overflow, and I have registered in some other forums too. I found that at Stack Overflow, we get the fastest replies to my questions and it's very well-organized (like choosing an appropriate answer, giving votes, and many more that I don't know). As far as learning a programming language is concerned, there are multiple ways to do it: 1. A person can teach you like getting tuition from somebody. Plus I have to read and program after my teacher finishes his classes. [*most efficient and faster*] 2. I can read myself and learn everything on my own. [*least efficient*] 3. There are a lot of video tutorials on programming by experts available online (e.g. on YouTube and Google Video). We need to pay for some of them. Plus reading and learning. [*most efficient and faster*] I have found the 3rd option quite comfortable and helpful. Should Stack Overflow or other sites allow video tutorials? Please share your thoughts with me.
2011/05/03
[ "https://meta.stackexchange.com/questions/89664", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/161141/" ]
There's nothing wrong with video tutorials but the stack exchange sites (or at least the "big 3" computing sites) are *not that kind of website*. We're not all about "teach yourself to program\build a server in 24 hours", we're more "Have a specific question about programming\server building? - Here's some specific answers". Note the "specific" - that's an important part of the equation and the reason video tutorials won't work here. Unless you're expecting video answers to every question (good luck with that) then videos would move us from that kind specific solutions to specific problems to generic tutorials, which would then generate specific questions which would need to be answered with text anyway ("In the Objective C video you installed Apple's XCode 3.2, is it OK to install XCode 4.0 instead?"). The best we could hope for from those questions is that we'd be led in a big circle back to where we are now. The worse is that we become another [videojug](http://www.videojug.com/) - a great resource as it happens but you only need one of those and it's already there.
Why all the negative votes? This is a good question (because I came here to ask it), glad I didn't - geeze! Two days after your post, Jeff Atwood (the co-creator of Stack Exchange/Overflow) had this to say: > > We are potentially enabling this on a > site-by-site basis, as needed... Make > the case for it on your site's meta, > as it is a site specific decision. > > > I lifted that quote from here: [Adding Support for Video or Slideshow of Images](https://meta.stackexchange.com/questions/78501/adding-support-for-video-or-slideshow-of-images). So the question isn't: "*Can it be done?*", but rather, "*Should it be done and what are the potential drawbacks of doing so?*". For StackOverflow it sounds like a great idea because I'm too lazy to write up all the steps to do something when I can just use Camtasia to record a quick video and upload it. But here are the cons: 1. You can't google or site-search what the user is saying or the code they're displaying in a video. 2. You can't copy/paste the code you see in a video - again, I'm lazy. 3. Video adds cost to a site if they are hosting and streaming uploaded media. 4. If you use YouTube it's even less reliable as accounts can be deactivated, content can be removed for copywrite violations, or users can just delete the video. 5. Bad people can add ads or update the video later to promote something else after getting a high vote-count. 6. The community can't edit the videos. Just like Twitter can force you to concentrate what you're saying into 140 characters or less, making the effort to type up an good answer that'll win votes and allowing the community to edit and sharpen those answers only increases the quality of content on sites like Stack Overflow. Well, I came here to ask this question and I ended up answering it for myself. Thanks!
59,502,364
I am creating a project called OpenCity which contains a premium version. The premium package is the problem. The project hierarchy is: ``` opencity // is a project in PyCharm 2019.3 premium // is a package __init__.py // is a module premium.py // is a module premium_user.py // is a module premium_user.txt // is a text file ``` premium\_user.py: ``` import random as ran def premium_users_adder(): premium_user1a = open('premium_user.txt', 'a') # premium_user1w = open('premium_user.txt', 'w') # premium_user1r = open('premium_user.txt', 'r') p2 = int(input("How many members do you want to add to premium_users to database? ")) p1 = [] p3 = [] for i in range(p2): member = input("Type the person's name. ") p1.append(member) id1 = ran.randint(100000000, 99999999999) p3.append(str(id1)) for i, e in zip(p1, p3): premium_user1a.write(i + ' ' + e + '\n') premium_user1a.close() print() print("Done") def premium_users_checker(): premium_user1r = open('premium_user.txt', 'r') p2 = [] for data in premium_user1r: p2.append(data) print(p2) ``` premium.py: ``` import premium.premium_users as pu pu.premium_users_adder() pu.premium_users_checker() ``` Error when running premium.py: ``` Traceback (most recent call last): File "F:/PyCharm Python Works/OpenCity/premium/premium.py", line 1, in <module> import premium.premium_users as pu File "F:\PyCharm Python Works\OpenCity\premium\premium.py", line 1, in <module> import premium.premium_users as pu ModuleNotFoundError: No module named 'premium.premium_users'; 'premium' is not a package ``` I have given everything except the `premium_users.txt` which contains premium codes.
2019/12/27
[ "https://Stackoverflow.com/questions/59502364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11697614/" ]
These errors occur because your local module named `premium.py` shadows the installed premium module you are trying to use. The current directory is prepended to `sys.path`, so the local name takes precedence over the installed name (You can read more about **how python finds packages** [**here**](https://leemendelowitz.github.io/blog/how-does-python-find-packages.html)). An extra debugging tip when this comes up is to look at the Traceback carefully, and realize that the name of your script in question is matching the module you are trying to import: Notice the name you used in your script: ``` File "F:/PyCharm Python Works/OpenCity/premium/premium.py", line 1, in <module> ``` The module you are trying to import: `premium` Rename your module to something else to avoid the name collision. Python may generate a `premium.pyc` file next to your `premium.py` file (in the `__pycache__` directory in Python 3). Remove that as well after your rename, as the interpreter will still reference that file, reproducing the error. However, the `pyc` file in `__pycache__` should not affect your code if the py file has been removed.
you can also use `from` then `import` any module do this- ``` from premium import premium_users as pu ``` instead of- ``` import premium.premium_users as pu ```
15,352,736
I'm trying to make and distribute a Ruby Gem where I package CoffeeScript files for use in other applications. It works fine in most Sprockets apps, but when I try to include it in a Rails App I get: ``` undefined method `append_path' for Sprockets:Module ``` The error is from this line: ``` ::Sprockets.append_path File.join(root_dir, "source") ``` How come when using the gem in a Rails app Sprockets has no append\_path method? Is there a way to get Rails apps look in a specific directory for asset files? I don't want to put my files in app/assets/javascripts because this is an assets only app and burying them like that just to accomodate Rails is aesthetically displeasing.
2013/03/12
[ "https://Stackoverflow.com/questions/15352736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68210/" ]
``` class Engine < ::Rails::Engine config.paths['app/assets'] = "source" end ```
Which version of rails are you using. Sprockets has been included in rails. check out <http://guides.rubyonrails.org/asset_pipeline.html>
39,454
I have a Cisco SG300 Small business switch, and the GUI interface is creating a lot of broadcast traffic: Source IP (The GUI IP): 172.16.xx.254:5353, Destination IP (Broadcast) 224.0.0.251:5353 I have disabled Bonjour and CDP globally on the switch. How can I turn this traffic off? (Command line answer preferred, but GUI is also OK.) --- Edit #1 - JFL's answer prompted me to make a Wireshark capture just to be 100% sure that the traffic was coming from the switch.... it is. The control GUI is broadcasting. I don't need or want that to happen. I have **no bonjour enable** globally. In the **Discovery - Bonjour** menu Discovery: Enable is uncheked, and the **Bonjour Discovery Interface Control Table** is **EMPTY**. What am I missing? Here's a sample packet: ``` Frame 60: 362 bytes on wire (2896 bits), 362 bytes captured (2896 bits) on interface 0 Interface id: 0 (enp0) Encapsulation type: Ethernet (1) Arrival Time: Mar 3, 2017 16:14:17.875849274 EST [Time shift for this packet: 0.000000000 seconds] Epoch Time: 1488575657.875849274 seconds [Time delta from previous captured frame: 1.461698815 seconds] [Time delta from previous displayed frame: 4.999822643 seconds] [Time since reference or first frame: 43.461018609 seconds] Frame Number: 60 Frame Length: 362 bytes (2896 bits) Capture Length: 362 bytes (2896 bits) [Frame is marked: False] [Frame is ignored: False] [Protocols in frame: eth:ethertype:ip:udp:mdns] [Coloring Rule Name: UDP] [Coloring Rule String: udp] Ethernet II, Src: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1), Dst: IPv4mcast_fb (01:00:5e:yy:yy:yb) Destination: IPv4mcast_fb (01:00:5e:yy:yy:yb) Address: IPv4mcast_fb (01:00:5e:yy:yy:yb) .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default) .... ...1 .... .... .... .... = IG bit: Group address (multicast/broadcast) Source: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1) Address: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1) .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default) .... ...0 .... .... .... .... = IG bit: Individual address (unicast) Type: IPv4 (0x0800) Internet Protocol Version 4, Src: 172.16.xx.254, Dst: 224.0.0.251 0100 .... = Version: 4 .... 0101 = Header Length: 20 bytes Differentiated Services Field: 0xe0 (DSCP: CS7, ECN: Not-ECT) 1110 00.. = Differentiated Services Codepoint: Class Selector 7 (56) .... ..00 = Explicit Congestion Notification: Not ECN-Capable Transport (0) Total Length: 348 Identification: 0x2e4f (11855) Flags: 0x00 0... .... = Reserved bit: Not set .0.. .... = Don't fragment: Not set ..0. .... = More fragments: Not set Fragment offset: 0 Time to live: 1 [Expert Info (Note/Sequence): "Time To Live" != 255 for a packet sent to the Local Network Control Block (see RFC 3171)] ["Time To Live" != 255 for a packet sent to the Local Network Control Block (see RFC 3171)] [Severity level: Note] [Group: Sequence] Protocol: UDP (17) Header checksum: 0xca52 [validation disabled] [Good: False] [Bad: False] Source: 172.16.xx.254 Destination: 224.0.0.251 [Source GeoIP: Unknown] [Destination GeoIP: Unknown] User Datagram Protocol, Src Port: 5353 (5353), Dst Port: 5353 (5353) Source Port: 5353 Destination Port: 5353 Length: 328 Checksum: 0x6346 [validation disabled] [Good Checksum: False] [Bad Checksum: False] [Stream index: 0] Multicast Domain Name System (response) Transaction ID: 0x0000 Flags: 0x8000 Standard query response, No error 1... .... .... .... = Response: Message is a response .000 0... .... .... = Opcode: Standard query (0) .... .0.. .... .... = Authoritative: Server is not an authority for domain .... ..0. .... .... = Truncated: Message is not truncated .... ...0 .... .... = Recursion desired: Don't do query recursively .... .... 0... .... = Recursion available: Server can't do recursive queries .... .... .0.. .... = Z: reserved (0) .... .... ..0. .... = Answer authenticated: Answer/authority portion was not authenticated by the server .... .... ...0 .... = Non-authenticated data: Unacceptable .... .... .... 0000 = Reply code: No error (0) Questions: 0 Answer RRs: 1 Authority RRs: 0 Additional RRs: 0 Answers VSDPb45501._csco-sb-vsdp._mdns._udp.local: type TXT, class IN Name: VSDPb45501._csco-sb-vsdp._mdns._udp.local Type: TXT (Text strings) (16) .000 0000 0000 0001 = Class: IN (0x0001) 0... .... .... .... = Cache flush: False Time to live: 25 Data length: 255 TXT Length: 6 TXT: type=0 TXT Length: 9 TXT: version=1 TXT Length: 21 TXT: refresh-age-timeout=0 TXT Length: 10 TXT: priority=0 TXT Length: 14 TXT: refresh-flag=0 TXT Length: 34 TXT: root-mac-address=00:9e:1e:xx:xx:x1 TXT Length: 6 TXT: cost=0 TXT Length: 26 TXT: transm-address=172.16.xx.254 TXT Length: 23 TXT: transm-interface=100049 TXT Length: 16 TXT: voice-vlan-id=10 TXT Length: 16 TXT: voice-vlan-vpt=5 TXT Length: 18 TXT: voice-vlan-dscp=46 TXT Length: 43 TXT: md5-auth=01af9cba5ed0218b0848195834e6a878ae ``` --- Edit #2 I found the following by rooting around on the console. Don't know if this gives anybody any ideas, but the documentation doesn't say anything useful. ``` show bonjour Bonjour global status: disabled Bonjour L2 interfaces port list: none Service Admin Status Oper Status ------- ------------ ----------- csco-sb enabled enabled http enabled enabled https enabled enabled ssh enabled enabled telnet enabled disabled ```
2017/03/03
[ "https://networkengineering.stackexchange.com/questions/39454", "https://networkengineering.stackexchange.com", "https://networkengineering.stackexchange.com/users/34916/" ]
Unfortunately it appears to be a bug in Cisco IOS: <https://quickview.cloudapps.cisco.com/quickview/bug/CSCum51028>
224.0.0.251 is the multicast (and not broadcast) address used by the apple Bonjour protocol but also by the associated multicast DNS ([rfc6762](http://www.rfc-editor.org/rfc/rfc6762.txt)) So there's two cause of traffic sent to this multicast address: * bonjour advertisements * resolution of .local DNS names So I would first double check that bonjour advertisement are disabled (in Administration > Discovery - Bonjour.) but also check that there's no DNS name ending with .local anywhere. Analysing the frame sent (with wireshark / tcdump / MS message analyser) could also determine if they are actually bonjour discovery message If it's actually bonjour discovery packet and it's really off then I'll upgrade the switch with the latest software and see if it persists, then submit the issue to Cisco.
39,454
I have a Cisco SG300 Small business switch, and the GUI interface is creating a lot of broadcast traffic: Source IP (The GUI IP): 172.16.xx.254:5353, Destination IP (Broadcast) 224.0.0.251:5353 I have disabled Bonjour and CDP globally on the switch. How can I turn this traffic off? (Command line answer preferred, but GUI is also OK.) --- Edit #1 - JFL's answer prompted me to make a Wireshark capture just to be 100% sure that the traffic was coming from the switch.... it is. The control GUI is broadcasting. I don't need or want that to happen. I have **no bonjour enable** globally. In the **Discovery - Bonjour** menu Discovery: Enable is uncheked, and the **Bonjour Discovery Interface Control Table** is **EMPTY**. What am I missing? Here's a sample packet: ``` Frame 60: 362 bytes on wire (2896 bits), 362 bytes captured (2896 bits) on interface 0 Interface id: 0 (enp0) Encapsulation type: Ethernet (1) Arrival Time: Mar 3, 2017 16:14:17.875849274 EST [Time shift for this packet: 0.000000000 seconds] Epoch Time: 1488575657.875849274 seconds [Time delta from previous captured frame: 1.461698815 seconds] [Time delta from previous displayed frame: 4.999822643 seconds] [Time since reference or first frame: 43.461018609 seconds] Frame Number: 60 Frame Length: 362 bytes (2896 bits) Capture Length: 362 bytes (2896 bits) [Frame is marked: False] [Frame is ignored: False] [Protocols in frame: eth:ethertype:ip:udp:mdns] [Coloring Rule Name: UDP] [Coloring Rule String: udp] Ethernet II, Src: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1), Dst: IPv4mcast_fb (01:00:5e:yy:yy:yb) Destination: IPv4mcast_fb (01:00:5e:yy:yy:yb) Address: IPv4mcast_fb (01:00:5e:yy:yy:yb) .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default) .... ...1 .... .... .... .... = IG bit: Group address (multicast/broadcast) Source: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1) Address: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1) .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default) .... ...0 .... .... .... .... = IG bit: Individual address (unicast) Type: IPv4 (0x0800) Internet Protocol Version 4, Src: 172.16.xx.254, Dst: 224.0.0.251 0100 .... = Version: 4 .... 0101 = Header Length: 20 bytes Differentiated Services Field: 0xe0 (DSCP: CS7, ECN: Not-ECT) 1110 00.. = Differentiated Services Codepoint: Class Selector 7 (56) .... ..00 = Explicit Congestion Notification: Not ECN-Capable Transport (0) Total Length: 348 Identification: 0x2e4f (11855) Flags: 0x00 0... .... = Reserved bit: Not set .0.. .... = Don't fragment: Not set ..0. .... = More fragments: Not set Fragment offset: 0 Time to live: 1 [Expert Info (Note/Sequence): "Time To Live" != 255 for a packet sent to the Local Network Control Block (see RFC 3171)] ["Time To Live" != 255 for a packet sent to the Local Network Control Block (see RFC 3171)] [Severity level: Note] [Group: Sequence] Protocol: UDP (17) Header checksum: 0xca52 [validation disabled] [Good: False] [Bad: False] Source: 172.16.xx.254 Destination: 224.0.0.251 [Source GeoIP: Unknown] [Destination GeoIP: Unknown] User Datagram Protocol, Src Port: 5353 (5353), Dst Port: 5353 (5353) Source Port: 5353 Destination Port: 5353 Length: 328 Checksum: 0x6346 [validation disabled] [Good Checksum: False] [Bad Checksum: False] [Stream index: 0] Multicast Domain Name System (response) Transaction ID: 0x0000 Flags: 0x8000 Standard query response, No error 1... .... .... .... = Response: Message is a response .000 0... .... .... = Opcode: Standard query (0) .... .0.. .... .... = Authoritative: Server is not an authority for domain .... ..0. .... .... = Truncated: Message is not truncated .... ...0 .... .... = Recursion desired: Don't do query recursively .... .... 0... .... = Recursion available: Server can't do recursive queries .... .... .0.. .... = Z: reserved (0) .... .... ..0. .... = Answer authenticated: Answer/authority portion was not authenticated by the server .... .... ...0 .... = Non-authenticated data: Unacceptable .... .... .... 0000 = Reply code: No error (0) Questions: 0 Answer RRs: 1 Authority RRs: 0 Additional RRs: 0 Answers VSDPb45501._csco-sb-vsdp._mdns._udp.local: type TXT, class IN Name: VSDPb45501._csco-sb-vsdp._mdns._udp.local Type: TXT (Text strings) (16) .000 0000 0000 0001 = Class: IN (0x0001) 0... .... .... .... = Cache flush: False Time to live: 25 Data length: 255 TXT Length: 6 TXT: type=0 TXT Length: 9 TXT: version=1 TXT Length: 21 TXT: refresh-age-timeout=0 TXT Length: 10 TXT: priority=0 TXT Length: 14 TXT: refresh-flag=0 TXT Length: 34 TXT: root-mac-address=00:9e:1e:xx:xx:x1 TXT Length: 6 TXT: cost=0 TXT Length: 26 TXT: transm-address=172.16.xx.254 TXT Length: 23 TXT: transm-interface=100049 TXT Length: 16 TXT: voice-vlan-id=10 TXT Length: 16 TXT: voice-vlan-vpt=5 TXT Length: 18 TXT: voice-vlan-dscp=46 TXT Length: 43 TXT: md5-auth=01af9cba5ed0218b0848195834e6a878ae ``` --- Edit #2 I found the following by rooting around on the console. Don't know if this gives anybody any ideas, but the documentation doesn't say anything useful. ``` show bonjour Bonjour global status: disabled Bonjour L2 interfaces port list: none Service Admin Status Oper Status ------- ------------ ----------- csco-sb enabled enabled http enabled enabled https enabled enabled ssh enabled enabled telnet enabled disabled ```
2017/03/03
[ "https://networkengineering.stackexchange.com/questions/39454", "https://networkengineering.stackexchange.com", "https://networkengineering.stackexchange.com/users/34916/" ]
224.0.0.251 is the multicast (and not broadcast) address used by the apple Bonjour protocol but also by the associated multicast DNS ([rfc6762](http://www.rfc-editor.org/rfc/rfc6762.txt)) So there's two cause of traffic sent to this multicast address: * bonjour advertisements * resolution of .local DNS names So I would first double check that bonjour advertisement are disabled (in Administration > Discovery - Bonjour.) but also check that there's no DNS name ending with .local anywhere. Analysing the frame sent (with wireshark / tcdump / MS message analyser) could also determine if they are actually bonjour discovery message If it's actually bonjour discovery packet and it's really off then I'll upgrade the switch with the latest software and see if it persists, then submit the issue to Cisco.
This is a VSDP packet. Cisco's horrible and proprietary way for their small business lines of switches to communicate the agreed upon voice vlan around the network. It's a pain, will add/remove vlans, mess with your trunk port configuration, and doesn't seem to be able to be disabled. You can probably build an ACL and apply it to each port, though. VSDP Patent Request: <http://www.freepatentsonline.com/y2013/0259027.html>
39,454
I have a Cisco SG300 Small business switch, and the GUI interface is creating a lot of broadcast traffic: Source IP (The GUI IP): 172.16.xx.254:5353, Destination IP (Broadcast) 224.0.0.251:5353 I have disabled Bonjour and CDP globally on the switch. How can I turn this traffic off? (Command line answer preferred, but GUI is also OK.) --- Edit #1 - JFL's answer prompted me to make a Wireshark capture just to be 100% sure that the traffic was coming from the switch.... it is. The control GUI is broadcasting. I don't need or want that to happen. I have **no bonjour enable** globally. In the **Discovery - Bonjour** menu Discovery: Enable is uncheked, and the **Bonjour Discovery Interface Control Table** is **EMPTY**. What am I missing? Here's a sample packet: ``` Frame 60: 362 bytes on wire (2896 bits), 362 bytes captured (2896 bits) on interface 0 Interface id: 0 (enp0) Encapsulation type: Ethernet (1) Arrival Time: Mar 3, 2017 16:14:17.875849274 EST [Time shift for this packet: 0.000000000 seconds] Epoch Time: 1488575657.875849274 seconds [Time delta from previous captured frame: 1.461698815 seconds] [Time delta from previous displayed frame: 4.999822643 seconds] [Time since reference or first frame: 43.461018609 seconds] Frame Number: 60 Frame Length: 362 bytes (2896 bits) Capture Length: 362 bytes (2896 bits) [Frame is marked: False] [Frame is ignored: False] [Protocols in frame: eth:ethertype:ip:udp:mdns] [Coloring Rule Name: UDP] [Coloring Rule String: udp] Ethernet II, Src: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1), Dst: IPv4mcast_fb (01:00:5e:yy:yy:yb) Destination: IPv4mcast_fb (01:00:5e:yy:yy:yb) Address: IPv4mcast_fb (01:00:5e:yy:yy:yb) .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default) .... ...1 .... .... .... .... = IG bit: Group address (multicast/broadcast) Source: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1) Address: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1) .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default) .... ...0 .... .... .... .... = IG bit: Individual address (unicast) Type: IPv4 (0x0800) Internet Protocol Version 4, Src: 172.16.xx.254, Dst: 224.0.0.251 0100 .... = Version: 4 .... 0101 = Header Length: 20 bytes Differentiated Services Field: 0xe0 (DSCP: CS7, ECN: Not-ECT) 1110 00.. = Differentiated Services Codepoint: Class Selector 7 (56) .... ..00 = Explicit Congestion Notification: Not ECN-Capable Transport (0) Total Length: 348 Identification: 0x2e4f (11855) Flags: 0x00 0... .... = Reserved bit: Not set .0.. .... = Don't fragment: Not set ..0. .... = More fragments: Not set Fragment offset: 0 Time to live: 1 [Expert Info (Note/Sequence): "Time To Live" != 255 for a packet sent to the Local Network Control Block (see RFC 3171)] ["Time To Live" != 255 for a packet sent to the Local Network Control Block (see RFC 3171)] [Severity level: Note] [Group: Sequence] Protocol: UDP (17) Header checksum: 0xca52 [validation disabled] [Good: False] [Bad: False] Source: 172.16.xx.254 Destination: 224.0.0.251 [Source GeoIP: Unknown] [Destination GeoIP: Unknown] User Datagram Protocol, Src Port: 5353 (5353), Dst Port: 5353 (5353) Source Port: 5353 Destination Port: 5353 Length: 328 Checksum: 0x6346 [validation disabled] [Good Checksum: False] [Bad Checksum: False] [Stream index: 0] Multicast Domain Name System (response) Transaction ID: 0x0000 Flags: 0x8000 Standard query response, No error 1... .... .... .... = Response: Message is a response .000 0... .... .... = Opcode: Standard query (0) .... .0.. .... .... = Authoritative: Server is not an authority for domain .... ..0. .... .... = Truncated: Message is not truncated .... ...0 .... .... = Recursion desired: Don't do query recursively .... .... 0... .... = Recursion available: Server can't do recursive queries .... .... .0.. .... = Z: reserved (0) .... .... ..0. .... = Answer authenticated: Answer/authority portion was not authenticated by the server .... .... ...0 .... = Non-authenticated data: Unacceptable .... .... .... 0000 = Reply code: No error (0) Questions: 0 Answer RRs: 1 Authority RRs: 0 Additional RRs: 0 Answers VSDPb45501._csco-sb-vsdp._mdns._udp.local: type TXT, class IN Name: VSDPb45501._csco-sb-vsdp._mdns._udp.local Type: TXT (Text strings) (16) .000 0000 0000 0001 = Class: IN (0x0001) 0... .... .... .... = Cache flush: False Time to live: 25 Data length: 255 TXT Length: 6 TXT: type=0 TXT Length: 9 TXT: version=1 TXT Length: 21 TXT: refresh-age-timeout=0 TXT Length: 10 TXT: priority=0 TXT Length: 14 TXT: refresh-flag=0 TXT Length: 34 TXT: root-mac-address=00:9e:1e:xx:xx:x1 TXT Length: 6 TXT: cost=0 TXT Length: 26 TXT: transm-address=172.16.xx.254 TXT Length: 23 TXT: transm-interface=100049 TXT Length: 16 TXT: voice-vlan-id=10 TXT Length: 16 TXT: voice-vlan-vpt=5 TXT Length: 18 TXT: voice-vlan-dscp=46 TXT Length: 43 TXT: md5-auth=01af9cba5ed0218b0848195834e6a878ae ``` --- Edit #2 I found the following by rooting around on the console. Don't know if this gives anybody any ideas, but the documentation doesn't say anything useful. ``` show bonjour Bonjour global status: disabled Bonjour L2 interfaces port list: none Service Admin Status Oper Status ------- ------------ ----------- csco-sb enabled enabled http enabled enabled https enabled enabled ssh enabled enabled telnet enabled disabled ```
2017/03/03
[ "https://networkengineering.stackexchange.com/questions/39454", "https://networkengineering.stackexchange.com", "https://networkengineering.stackexchange.com/users/34916/" ]
224.0.0.251 is the multicast (and not broadcast) address used by the apple Bonjour protocol but also by the associated multicast DNS ([rfc6762](http://www.rfc-editor.org/rfc/rfc6762.txt)) So there's two cause of traffic sent to this multicast address: * bonjour advertisements * resolution of .local DNS names So I would first double check that bonjour advertisement are disabled (in Administration > Discovery - Bonjour.) but also check that there's no DNS name ending with .local anywhere. Analysing the frame sent (with wireshark / tcdump / MS message analyser) could also determine if they are actually bonjour discovery message If it's actually bonjour discovery packet and it's really off then I'll upgrade the switch with the latest software and see if it persists, then submit the issue to Cisco.
The `voice vlan state disabled` configuration command will stop these broadcasts.
39,454
I have a Cisco SG300 Small business switch, and the GUI interface is creating a lot of broadcast traffic: Source IP (The GUI IP): 172.16.xx.254:5353, Destination IP (Broadcast) 224.0.0.251:5353 I have disabled Bonjour and CDP globally on the switch. How can I turn this traffic off? (Command line answer preferred, but GUI is also OK.) --- Edit #1 - JFL's answer prompted me to make a Wireshark capture just to be 100% sure that the traffic was coming from the switch.... it is. The control GUI is broadcasting. I don't need or want that to happen. I have **no bonjour enable** globally. In the **Discovery - Bonjour** menu Discovery: Enable is uncheked, and the **Bonjour Discovery Interface Control Table** is **EMPTY**. What am I missing? Here's a sample packet: ``` Frame 60: 362 bytes on wire (2896 bits), 362 bytes captured (2896 bits) on interface 0 Interface id: 0 (enp0) Encapsulation type: Ethernet (1) Arrival Time: Mar 3, 2017 16:14:17.875849274 EST [Time shift for this packet: 0.000000000 seconds] Epoch Time: 1488575657.875849274 seconds [Time delta from previous captured frame: 1.461698815 seconds] [Time delta from previous displayed frame: 4.999822643 seconds] [Time since reference or first frame: 43.461018609 seconds] Frame Number: 60 Frame Length: 362 bytes (2896 bits) Capture Length: 362 bytes (2896 bits) [Frame is marked: False] [Frame is ignored: False] [Protocols in frame: eth:ethertype:ip:udp:mdns] [Coloring Rule Name: UDP] [Coloring Rule String: udp] Ethernet II, Src: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1), Dst: IPv4mcast_fb (01:00:5e:yy:yy:yb) Destination: IPv4mcast_fb (01:00:5e:yy:yy:yb) Address: IPv4mcast_fb (01:00:5e:yy:yy:yb) .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default) .... ...1 .... .... .... .... = IG bit: Group address (multicast/broadcast) Source: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1) Address: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1) .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default) .... ...0 .... .... .... .... = IG bit: Individual address (unicast) Type: IPv4 (0x0800) Internet Protocol Version 4, Src: 172.16.xx.254, Dst: 224.0.0.251 0100 .... = Version: 4 .... 0101 = Header Length: 20 bytes Differentiated Services Field: 0xe0 (DSCP: CS7, ECN: Not-ECT) 1110 00.. = Differentiated Services Codepoint: Class Selector 7 (56) .... ..00 = Explicit Congestion Notification: Not ECN-Capable Transport (0) Total Length: 348 Identification: 0x2e4f (11855) Flags: 0x00 0... .... = Reserved bit: Not set .0.. .... = Don't fragment: Not set ..0. .... = More fragments: Not set Fragment offset: 0 Time to live: 1 [Expert Info (Note/Sequence): "Time To Live" != 255 for a packet sent to the Local Network Control Block (see RFC 3171)] ["Time To Live" != 255 for a packet sent to the Local Network Control Block (see RFC 3171)] [Severity level: Note] [Group: Sequence] Protocol: UDP (17) Header checksum: 0xca52 [validation disabled] [Good: False] [Bad: False] Source: 172.16.xx.254 Destination: 224.0.0.251 [Source GeoIP: Unknown] [Destination GeoIP: Unknown] User Datagram Protocol, Src Port: 5353 (5353), Dst Port: 5353 (5353) Source Port: 5353 Destination Port: 5353 Length: 328 Checksum: 0x6346 [validation disabled] [Good Checksum: False] [Bad Checksum: False] [Stream index: 0] Multicast Domain Name System (response) Transaction ID: 0x0000 Flags: 0x8000 Standard query response, No error 1... .... .... .... = Response: Message is a response .000 0... .... .... = Opcode: Standard query (0) .... .0.. .... .... = Authoritative: Server is not an authority for domain .... ..0. .... .... = Truncated: Message is not truncated .... ...0 .... .... = Recursion desired: Don't do query recursively .... .... 0... .... = Recursion available: Server can't do recursive queries .... .... .0.. .... = Z: reserved (0) .... .... ..0. .... = Answer authenticated: Answer/authority portion was not authenticated by the server .... .... ...0 .... = Non-authenticated data: Unacceptable .... .... .... 0000 = Reply code: No error (0) Questions: 0 Answer RRs: 1 Authority RRs: 0 Additional RRs: 0 Answers VSDPb45501._csco-sb-vsdp._mdns._udp.local: type TXT, class IN Name: VSDPb45501._csco-sb-vsdp._mdns._udp.local Type: TXT (Text strings) (16) .000 0000 0000 0001 = Class: IN (0x0001) 0... .... .... .... = Cache flush: False Time to live: 25 Data length: 255 TXT Length: 6 TXT: type=0 TXT Length: 9 TXT: version=1 TXT Length: 21 TXT: refresh-age-timeout=0 TXT Length: 10 TXT: priority=0 TXT Length: 14 TXT: refresh-flag=0 TXT Length: 34 TXT: root-mac-address=00:9e:1e:xx:xx:x1 TXT Length: 6 TXT: cost=0 TXT Length: 26 TXT: transm-address=172.16.xx.254 TXT Length: 23 TXT: transm-interface=100049 TXT Length: 16 TXT: voice-vlan-id=10 TXT Length: 16 TXT: voice-vlan-vpt=5 TXT Length: 18 TXT: voice-vlan-dscp=46 TXT Length: 43 TXT: md5-auth=01af9cba5ed0218b0848195834e6a878ae ``` --- Edit #2 I found the following by rooting around on the console. Don't know if this gives anybody any ideas, but the documentation doesn't say anything useful. ``` show bonjour Bonjour global status: disabled Bonjour L2 interfaces port list: none Service Admin Status Oper Status ------- ------------ ----------- csco-sb enabled enabled http enabled enabled https enabled enabled ssh enabled enabled telnet enabled disabled ```
2017/03/03
[ "https://networkengineering.stackexchange.com/questions/39454", "https://networkengineering.stackexchange.com", "https://networkengineering.stackexchange.com/users/34916/" ]
Unfortunately it appears to be a bug in Cisco IOS: <https://quickview.cloudapps.cisco.com/quickview/bug/CSCum51028>
This is a VSDP packet. Cisco's horrible and proprietary way for their small business lines of switches to communicate the agreed upon voice vlan around the network. It's a pain, will add/remove vlans, mess with your trunk port configuration, and doesn't seem to be able to be disabled. You can probably build an ACL and apply it to each port, though. VSDP Patent Request: <http://www.freepatentsonline.com/y2013/0259027.html>
39,454
I have a Cisco SG300 Small business switch, and the GUI interface is creating a lot of broadcast traffic: Source IP (The GUI IP): 172.16.xx.254:5353, Destination IP (Broadcast) 224.0.0.251:5353 I have disabled Bonjour and CDP globally on the switch. How can I turn this traffic off? (Command line answer preferred, but GUI is also OK.) --- Edit #1 - JFL's answer prompted me to make a Wireshark capture just to be 100% sure that the traffic was coming from the switch.... it is. The control GUI is broadcasting. I don't need or want that to happen. I have **no bonjour enable** globally. In the **Discovery - Bonjour** menu Discovery: Enable is uncheked, and the **Bonjour Discovery Interface Control Table** is **EMPTY**. What am I missing? Here's a sample packet: ``` Frame 60: 362 bytes on wire (2896 bits), 362 bytes captured (2896 bits) on interface 0 Interface id: 0 (enp0) Encapsulation type: Ethernet (1) Arrival Time: Mar 3, 2017 16:14:17.875849274 EST [Time shift for this packet: 0.000000000 seconds] Epoch Time: 1488575657.875849274 seconds [Time delta from previous captured frame: 1.461698815 seconds] [Time delta from previous displayed frame: 4.999822643 seconds] [Time since reference or first frame: 43.461018609 seconds] Frame Number: 60 Frame Length: 362 bytes (2896 bits) Capture Length: 362 bytes (2896 bits) [Frame is marked: False] [Frame is ignored: False] [Protocols in frame: eth:ethertype:ip:udp:mdns] [Coloring Rule Name: UDP] [Coloring Rule String: udp] Ethernet II, Src: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1), Dst: IPv4mcast_fb (01:00:5e:yy:yy:yb) Destination: IPv4mcast_fb (01:00:5e:yy:yy:yb) Address: IPv4mcast_fb (01:00:5e:yy:yy:yb) .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default) .... ...1 .... .... .... .... = IG bit: Group address (multicast/broadcast) Source: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1) Address: 00:9e:1e:xx:xx:x1 (00:9e:1e:xx:xx:x1) .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default) .... ...0 .... .... .... .... = IG bit: Individual address (unicast) Type: IPv4 (0x0800) Internet Protocol Version 4, Src: 172.16.xx.254, Dst: 224.0.0.251 0100 .... = Version: 4 .... 0101 = Header Length: 20 bytes Differentiated Services Field: 0xe0 (DSCP: CS7, ECN: Not-ECT) 1110 00.. = Differentiated Services Codepoint: Class Selector 7 (56) .... ..00 = Explicit Congestion Notification: Not ECN-Capable Transport (0) Total Length: 348 Identification: 0x2e4f (11855) Flags: 0x00 0... .... = Reserved bit: Not set .0.. .... = Don't fragment: Not set ..0. .... = More fragments: Not set Fragment offset: 0 Time to live: 1 [Expert Info (Note/Sequence): "Time To Live" != 255 for a packet sent to the Local Network Control Block (see RFC 3171)] ["Time To Live" != 255 for a packet sent to the Local Network Control Block (see RFC 3171)] [Severity level: Note] [Group: Sequence] Protocol: UDP (17) Header checksum: 0xca52 [validation disabled] [Good: False] [Bad: False] Source: 172.16.xx.254 Destination: 224.0.0.251 [Source GeoIP: Unknown] [Destination GeoIP: Unknown] User Datagram Protocol, Src Port: 5353 (5353), Dst Port: 5353 (5353) Source Port: 5353 Destination Port: 5353 Length: 328 Checksum: 0x6346 [validation disabled] [Good Checksum: False] [Bad Checksum: False] [Stream index: 0] Multicast Domain Name System (response) Transaction ID: 0x0000 Flags: 0x8000 Standard query response, No error 1... .... .... .... = Response: Message is a response .000 0... .... .... = Opcode: Standard query (0) .... .0.. .... .... = Authoritative: Server is not an authority for domain .... ..0. .... .... = Truncated: Message is not truncated .... ...0 .... .... = Recursion desired: Don't do query recursively .... .... 0... .... = Recursion available: Server can't do recursive queries .... .... .0.. .... = Z: reserved (0) .... .... ..0. .... = Answer authenticated: Answer/authority portion was not authenticated by the server .... .... ...0 .... = Non-authenticated data: Unacceptable .... .... .... 0000 = Reply code: No error (0) Questions: 0 Answer RRs: 1 Authority RRs: 0 Additional RRs: 0 Answers VSDPb45501._csco-sb-vsdp._mdns._udp.local: type TXT, class IN Name: VSDPb45501._csco-sb-vsdp._mdns._udp.local Type: TXT (Text strings) (16) .000 0000 0000 0001 = Class: IN (0x0001) 0... .... .... .... = Cache flush: False Time to live: 25 Data length: 255 TXT Length: 6 TXT: type=0 TXT Length: 9 TXT: version=1 TXT Length: 21 TXT: refresh-age-timeout=0 TXT Length: 10 TXT: priority=0 TXT Length: 14 TXT: refresh-flag=0 TXT Length: 34 TXT: root-mac-address=00:9e:1e:xx:xx:x1 TXT Length: 6 TXT: cost=0 TXT Length: 26 TXT: transm-address=172.16.xx.254 TXT Length: 23 TXT: transm-interface=100049 TXT Length: 16 TXT: voice-vlan-id=10 TXT Length: 16 TXT: voice-vlan-vpt=5 TXT Length: 18 TXT: voice-vlan-dscp=46 TXT Length: 43 TXT: md5-auth=01af9cba5ed0218b0848195834e6a878ae ``` --- Edit #2 I found the following by rooting around on the console. Don't know if this gives anybody any ideas, but the documentation doesn't say anything useful. ``` show bonjour Bonjour global status: disabled Bonjour L2 interfaces port list: none Service Admin Status Oper Status ------- ------------ ----------- csco-sb enabled enabled http enabled enabled https enabled enabled ssh enabled enabled telnet enabled disabled ```
2017/03/03
[ "https://networkengineering.stackexchange.com/questions/39454", "https://networkengineering.stackexchange.com", "https://networkengineering.stackexchange.com/users/34916/" ]
Unfortunately it appears to be a bug in Cisco IOS: <https://quickview.cloudapps.cisco.com/quickview/bug/CSCum51028>
The `voice vlan state disabled` configuration command will stop these broadcasts.
39,248,444
How to SELECT values if id available in column(Comma separated values) using MySQL? Here I need to get all values when the given id=17 available in `group_id` column. Table: ``` +------------+---------------+ | user_id | group_id | +------------+---------------+ | 1 | 1,2,3 | | 3 | 12,23,17 | | 5 | 17,26 | +------------+---------------+ ``` I try: ``` SELECT * FROM `group` WHERE units_id IN('17'); //No result ``` Expecting result: ``` +------------+---------------+ | user_id | group_id | +------------+---------------+ | 3 | 12,23,17 | | 5 | 17,26 | +------------+---------------+ ```
2016/08/31
[ "https://Stackoverflow.com/questions/39248444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use `FIND_IN_SET` ``` SELECT * FROM `group` WHERE FIND_IN_SET(17,group_id); ``` **Note:** It's highly discouraged to store comma separated values in column. A must read: [**Is storing a delimited list in a database column really that bad?**](https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad) Yes Also you shouldn't use `MySQL reserved words` as your identifer's name. Be careful to enclose by backtick while using.
You can use ´find\_in\_set` ``` SELECT * FROM `group` WHERE find_in_set('17',units_id ); ``` `IN` checks if a column contains values from a comma separated list It is very bad db design if you store values as csv. For more infoemartion see [mysql documentation](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set)
39,248,444
How to SELECT values if id available in column(Comma separated values) using MySQL? Here I need to get all values when the given id=17 available in `group_id` column. Table: ``` +------------+---------------+ | user_id | group_id | +------------+---------------+ | 1 | 1,2,3 | | 3 | 12,23,17 | | 5 | 17,26 | +------------+---------------+ ``` I try: ``` SELECT * FROM `group` WHERE units_id IN('17'); //No result ``` Expecting result: ``` +------------+---------------+ | user_id | group_id | +------------+---------------+ | 3 | 12,23,17 | | 5 | 17,26 | +------------+---------------+ ```
2016/08/31
[ "https://Stackoverflow.com/questions/39248444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use `FIND_IN_SET` ``` SELECT * FROM `group` WHERE FIND_IN_SET(17,group_id); ``` **Note:** It's highly discouraged to store comma separated values in column. A must read: [**Is storing a delimited list in a database column really that bad?**](https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad) Yes Also you shouldn't use `MySQL reserved words` as your identifer's name. Be careful to enclose by backtick while using.
Try this one. You can use [find\_in\_set](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set) : ``` SELECT * FROM `user` WHERE find_in_set('17',group_id) ORDER BY user_id; ``` RESULT: ``` +------------+---------------+ | user_id | group_id | +------------+---------------+ | 3 | 12,23,17 | | 5 | 17,26 | +------------+---------------+ ``` REF: [MySQL query finding values in a comma separated string](https://stackoverflow.com/questions/5033047/mysql-query-finding-values-in-a-comma-separated-string)
39,248,444
How to SELECT values if id available in column(Comma separated values) using MySQL? Here I need to get all values when the given id=17 available in `group_id` column. Table: ``` +------------+---------------+ | user_id | group_id | +------------+---------------+ | 1 | 1,2,3 | | 3 | 12,23,17 | | 5 | 17,26 | +------------+---------------+ ``` I try: ``` SELECT * FROM `group` WHERE units_id IN('17'); //No result ``` Expecting result: ``` +------------+---------------+ | user_id | group_id | +------------+---------------+ | 3 | 12,23,17 | | 5 | 17,26 | +------------+---------------+ ```
2016/08/31
[ "https://Stackoverflow.com/questions/39248444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try this one. You can use [find\_in\_set](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set) : ``` SELECT * FROM `user` WHERE find_in_set('17',group_id) ORDER BY user_id; ``` RESULT: ``` +------------+---------------+ | user_id | group_id | +------------+---------------+ | 3 | 12,23,17 | | 5 | 17,26 | +------------+---------------+ ``` REF: [MySQL query finding values in a comma separated string](https://stackoverflow.com/questions/5033047/mysql-query-finding-values-in-a-comma-separated-string)
You can use ´find\_in\_set` ``` SELECT * FROM `group` WHERE find_in_set('17',units_id ); ``` `IN` checks if a column contains values from a comma separated list It is very bad db design if you store values as csv. For more infoemartion see [mysql documentation](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set)
15,800,596
My Google skills fail me =( I have the following map: ``` std::map<std::string, std::map<std::string, std::string>> spriteSheetMap; ``` And I'm trying to do this: ``` for (auto &animationKey : killerRabbit->spriteSheetMap) { for (auto &animation : animationKey) { //why doesn't this work? } } ``` The actual error: ``` Invalid range expression of type 'std::__1::pair<const std::__1::basic_string<char>, std::__1::map<std::__1::basic_string<char>, std::__1::basic_string<char>, std::__1::less<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>, std::__1::basic_string<char> > > > >'; no viable 'begin' function available ```
2013/04/04
[ "https://Stackoverflow.com/questions/15800596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1340939/" ]
The first loop invokes [`begin()`](http://www.cplusplus.com/reference/map/map/begin/) which returns `std::pair`'s (i.e. `value_type` of `std::map`'s). So it doesn't make much sense to iterate over a pair like that. I think what you want is: ``` for (auto &animation : animationKey.second) { ``` Which will iterate over the inner-map. Just remember that the same thing will happen with `animation`: `animation` will be a pair, with `animation.first` referring to the key and `animation.second` referring to the value.
The error is saying it can't iterate over a pair. The following fixes the problem as you're getting the key-value pair result from iterating over a map in the first loop. ``` for (auto &animation : animationKey.second) ``` See [map.begin()](http://www.cplusplus.com/reference/map/map/begin/) to see examples of how the first loop outputs pairs and not values to the auto variable.
8,274,413
What are my options for using the same JavaScript code to validate both on client side and on server side (Node.js)?
2011/11/25
[ "https://Stackoverflow.com/questions/8274413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616504/" ]
Take a look at [revalidator](https://github.com/flatiron/revalidator). It is described as "A cross-browser / node.js validator used by resourceful and flatiron."
None, you are validating entirely different criteria on the server-side. Client-side validation is purely user-acceptance criteria and has nothing to do with security. Server-side validation almost exclusively concerned with security.
30,550,235
I'm trying to install package with pip on Ubuntu server: ``` $ pip install MySQLdb Downloading/unpacking MySQLdb Killed ``` And it's getting killed. There is enough free RAM on server. Why it is killed? UPD Logs: > > Out of memory: Kill process 6627 (pip) score 297 or sacrifice child > > > Thats strange, because I have about 150 mb free RAM.
2015/05/30
[ "https://Stackoverflow.com/questions/30550235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497132/" ]
If you are running low on memory you could try with `pip install <your-package-name> --no-cache-dir`
I was facing this error and the process was getting killed for the torch package. Then I browsed the web and found the solution. ``` cd ~/.cache mv pip pip.bk ``` This cleared the cache memory with regards to pip. Uninstalling and installing pip did not help.
30,550,235
I'm trying to install package with pip on Ubuntu server: ``` $ pip install MySQLdb Downloading/unpacking MySQLdb Killed ``` And it's getting killed. There is enough free RAM on server. Why it is killed? UPD Logs: > > Out of memory: Kill process 6627 (pip) score 297 or sacrifice child > > > Thats strange, because I have about 150 mb free RAM.
2015/05/30
[ "https://Stackoverflow.com/questions/30550235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497132/" ]
In my case the cleaning cache of pip by using `pip3 cache purge` was was the solution, but be careful: it removes the entire pip cache. I have enough free RAM in idle state (~3Gb) but installation of torch being killed again and again, even without showing downoading progress: ``` Collecting torch>=1.5.0 Killed ``` So I supposed, just like @embiem guessed, that I had corrupted files in the cache, because I had aborted installation of the dependencies for the module once. After clearing the whole pip cache the installation was successful (And 15GB of free disk space was freed up - I use a lot of virtual environments). You can check brief info with `pip3 cache info` and all cache managing command `pip3 cache -h`, it's very useful in some cases.
I was facing this error and the process was getting killed for the torch package. Then I browsed the web and found the solution. ``` cd ~/.cache mv pip pip.bk ``` This cleared the cache memory with regards to pip. Uninstalling and installing pip did not help.
30,550,235
I'm trying to install package with pip on Ubuntu server: ``` $ pip install MySQLdb Downloading/unpacking MySQLdb Killed ``` And it's getting killed. There is enough free RAM on server. Why it is killed? UPD Logs: > > Out of memory: Kill process 6627 (pip) score 297 or sacrifice child > > > Thats strange, because I have about 150 mb free RAM.
2015/05/30
[ "https://Stackoverflow.com/questions/30550235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497132/" ]
If the `--no-cache-dir` flag isn't enough, try increasing the swap space. I was trying to install PyTorch on a Linode server which had 2GB RAM and 512 of Swap space. Adding 2GB of Swap space solved the issue. > > Method # 3 : Create a swap file. > > > 1. Create a swap file on the current File system for example on root, for this a new Directory can be created. > $ sudo mkdir /swap > 2. Create a new file into this new directory, in this example a new file for 2Gb is create. > $ sudo dd if=/dev/zero of=/swap/swapfile1 bs=1M count=2048 > 3. Create a new swap area on the file that has been created. > $ sudo mkswap /swap/swapfile1 > 4. Change the permissions on the file. > $ sudo chmod 600 /swap/swapfile1 > 5. Add the swap partition to the /etc/fstab file as indicated below on this step: > /swap/swapfile1 swap swap defaults 0 0 > 6. Load the new swap space that had been created for the Instance. > $ sudo swapon -a > > > Source for Guide: [TheGeekDiary](https://www.thegeekdiary.com/3-ways-of-increasing-swap-space-on-linux/)
I faced this same issue when installing `torch` as one of the dependencies. I checked that during the installation process it overshoots the RAM utilization as reported by logs. In my case, during the peak it increases the RAM usage to almost +3GB. I just closed the Firefox instance that was using almost 1GB from my 6GB laptop and run `pip install` again an it worked.
30,550,235
I'm trying to install package with pip on Ubuntu server: ``` $ pip install MySQLdb Downloading/unpacking MySQLdb Killed ``` And it's getting killed. There is enough free RAM on server. Why it is killed? UPD Logs: > > Out of memory: Kill process 6627 (pip) score 297 or sacrifice child > > > Thats strange, because I have about 150 mb free RAM.
2015/05/30
[ "https://Stackoverflow.com/questions/30550235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497132/" ]
You have to check logs, depending on the version of ubuntu and stuff, it should be in `/var/log/messages` or at least in `/var/log` so you can grep python or pip in that folder. This should provide hints. Also, if you're not in a virtualenv, you should probably use `sudo` to perform (implicit) privileged operations, such as copying the library in the global lib folder.
### Step1: `pip install package --no-cache-dir` If the problem persists, go to step 2. ### Step2: `sudo swapoff -a` `sudo swapon -a` Then try step 1 again.
30,550,235
I'm trying to install package with pip on Ubuntu server: ``` $ pip install MySQLdb Downloading/unpacking MySQLdb Killed ``` And it's getting killed. There is enough free RAM on server. Why it is killed? UPD Logs: > > Out of memory: Kill process 6627 (pip) score 297 or sacrifice child > > > Thats strange, because I have about 150 mb free RAM.
2015/05/30
[ "https://Stackoverflow.com/questions/30550235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497132/" ]
### Step1: `pip install package --no-cache-dir` If the problem persists, go to step 2. ### Step2: `sudo swapoff -a` `sudo swapon -a` Then try step 1 again.
I was facing this error and the process was getting killed for the torch package. Then I browsed the web and found the solution. ``` cd ~/.cache mv pip pip.bk ``` This cleared the cache memory with regards to pip. Uninstalling and installing pip did not help.
30,550,235
I'm trying to install package with pip on Ubuntu server: ``` $ pip install MySQLdb Downloading/unpacking MySQLdb Killed ``` And it's getting killed. There is enough free RAM on server. Why it is killed? UPD Logs: > > Out of memory: Kill process 6627 (pip) score 297 or sacrifice child > > > Thats strange, because I have about 150 mb free RAM.
2015/05/30
[ "https://Stackoverflow.com/questions/30550235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497132/" ]
If you are running low on memory you could try with `pip install <your-package-name> --no-cache-dir`
You have to check logs, depending on the version of ubuntu and stuff, it should be in `/var/log/messages` or at least in `/var/log` so you can grep python or pip in that folder. This should provide hints. Also, if you're not in a virtualenv, you should probably use `sudo` to perform (implicit) privileged operations, such as copying the library in the global lib folder.
30,550,235
I'm trying to install package with pip on Ubuntu server: ``` $ pip install MySQLdb Downloading/unpacking MySQLdb Killed ``` And it's getting killed. There is enough free RAM on server. Why it is killed? UPD Logs: > > Out of memory: Kill process 6627 (pip) score 297 or sacrifice child > > > Thats strange, because I have about 150 mb free RAM.
2015/05/30
[ "https://Stackoverflow.com/questions/30550235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497132/" ]
If you are running low on memory you could try with `pip install <your-package-name> --no-cache-dir`
I faced this same issue when installing `torch` as one of the dependencies. I checked that during the installation process it overshoots the RAM utilization as reported by logs. In my case, during the peak it increases the RAM usage to almost +3GB. I just closed the Firefox instance that was using almost 1GB from my 6GB laptop and run `pip install` again an it worked.
30,550,235
I'm trying to install package with pip on Ubuntu server: ``` $ pip install MySQLdb Downloading/unpacking MySQLdb Killed ``` And it's getting killed. There is enough free RAM on server. Why it is killed? UPD Logs: > > Out of memory: Kill process 6627 (pip) score 297 or sacrifice child > > > Thats strange, because I have about 150 mb free RAM.
2015/05/30
[ "https://Stackoverflow.com/questions/30550235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497132/" ]
In my case the cleaning cache of pip by using `pip3 cache purge` was was the solution, but be careful: it removes the entire pip cache. I have enough free RAM in idle state (~3Gb) but installation of torch being killed again and again, even without showing downoading progress: ``` Collecting torch>=1.5.0 Killed ``` So I supposed, just like @embiem guessed, that I had corrupted files in the cache, because I had aborted installation of the dependencies for the module once. After clearing the whole pip cache the installation was successful (And 15GB of free disk space was freed up - I use a lot of virtual environments). You can check brief info with `pip3 cache info` and all cache managing command `pip3 cache -h`, it's very useful in some cases.
I faced this same issue when installing `torch` as one of the dependencies. I checked that during the installation process it overshoots the RAM utilization as reported by logs. In my case, during the peak it increases the RAM usage to almost +3GB. I just closed the Firefox instance that was using almost 1GB from my 6GB laptop and run `pip install` again an it worked.
30,550,235
I'm trying to install package with pip on Ubuntu server: ``` $ pip install MySQLdb Downloading/unpacking MySQLdb Killed ``` And it's getting killed. There is enough free RAM on server. Why it is killed? UPD Logs: > > Out of memory: Kill process 6627 (pip) score 297 or sacrifice child > > > Thats strange, because I have about 150 mb free RAM.
2015/05/30
[ "https://Stackoverflow.com/questions/30550235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497132/" ]
If you are running low on memory you could try with `pip install <your-package-name> --no-cache-dir`
In my case the cleaning cache of pip by using `pip3 cache purge` was was the solution, but be careful: it removes the entire pip cache. I have enough free RAM in idle state (~3Gb) but installation of torch being killed again and again, even without showing downoading progress: ``` Collecting torch>=1.5.0 Killed ``` So I supposed, just like @embiem guessed, that I had corrupted files in the cache, because I had aborted installation of the dependencies for the module once. After clearing the whole pip cache the installation was successful (And 15GB of free disk space was freed up - I use a lot of virtual environments). You can check brief info with `pip3 cache info` and all cache managing command `pip3 cache -h`, it's very useful in some cases.
30,550,235
I'm trying to install package with pip on Ubuntu server: ``` $ pip install MySQLdb Downloading/unpacking MySQLdb Killed ``` And it's getting killed. There is enough free RAM on server. Why it is killed? UPD Logs: > > Out of memory: Kill process 6627 (pip) score 297 or sacrifice child > > > Thats strange, because I have about 150 mb free RAM.
2015/05/30
[ "https://Stackoverflow.com/questions/30550235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497132/" ]
If you are running low on memory you could try with `pip install <your-package-name> --no-cache-dir`
If the `--no-cache-dir` flag isn't enough, try increasing the swap space. I was trying to install PyTorch on a Linode server which had 2GB RAM and 512 of Swap space. Adding 2GB of Swap space solved the issue. > > Method # 3 : Create a swap file. > > > 1. Create a swap file on the current File system for example on root, for this a new Directory can be created. > $ sudo mkdir /swap > 2. Create a new file into this new directory, in this example a new file for 2Gb is create. > $ sudo dd if=/dev/zero of=/swap/swapfile1 bs=1M count=2048 > 3. Create a new swap area on the file that has been created. > $ sudo mkswap /swap/swapfile1 > 4. Change the permissions on the file. > $ sudo chmod 600 /swap/swapfile1 > 5. Add the swap partition to the /etc/fstab file as indicated below on this step: > /swap/swapfile1 swap swap defaults 0 0 > 6. Load the new swap space that had been created for the Instance. > $ sudo swapon -a > > > Source for Guide: [TheGeekDiary](https://www.thegeekdiary.com/3-ways-of-increasing-swap-space-on-linux/)
49,100,034
I'm trying to create a functional interface that can throw an custom exception, what I've come up with is. ``` public class MyException extends Exception { public MyException(String message) { super(message); } } @FunctionalInterface public interface ThrowingFunction<T, R> { R apply(T t) throws MyException; } ``` This works great for using the apply function but the problem is I'd also like to use the andThen capabilities of Java's functions. When I try to do something like. ``` ThrowingFunction<Integer, Integer> times2WithException = (num) -> { if(num == null) { throw new MyException("Cannot multiply null by 2"); } return num * 2; }; times2WithException.andThen(times2WithException).apply(4); ``` I get the error ``` Cannot find symbol: method andThen(ThrowingFunction<Integer, Integer>) ``` Is there something I should use instead of FunctionalInterface? Or is there another function I need to implement to get it to work with andThen? Thanks!
2018/03/04
[ "https://Stackoverflow.com/questions/49100034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2488335/" ]
Functional interfaces are only allowed to specify one unimplemented function. But you can specify `default` functions that already have an implementation like this: ``` @FunctionalInterface public interface ThrowingFunction<T, R> { R apply(T t) throws MyException; default <U> ThrowingFunction<T, U> andThen(ThrowingFunction<R, U> follow) { Objects.requireNonNull(follow); // Fail fast return t -> follow.apply(this.apply(t)); } } ```
Where are you expecting the `andThen` method to come from? You haven't defined it anywhere! ``` @FunctionalInterface interface ThrowingFunction<T, R> { R apply(T t) throws MyException; default <V> ThrowingFunction<T, V> andThen(ThrowingFunction<R, V> after) { return (T t) -> after.apply(apply(t)); } } ``` Here, you can take advantage of `default` methods in interfaces to create an `andThen` function.
19,367,589
From what I understand, the keyword `void` in Javascript is some kind of function that takes one argument and always returns the `undefined` value. For some reason you need to pass it an argument; it won't work without one. Is there any reason why it requires this argument? What is the point? Why won't it work without an argument. The only use I have seen for it is to produce an `undefined` result. Are there any other uses for it? If not then it would seem that the requirement for an expression to be passed would be pointless.
2013/10/14
[ "https://Stackoverflow.com/questions/19367589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/421652/" ]
As per this page <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void> void is an operator, which simply returns `undefined`, after evaluating the expression you pass to it. An operator needs an operand to operate on. That is why pass a parameter. ``` console.log(void true); console.log(void 0); console.log(void "Welcome"); console.log(void(true)); console.log(void(0)); console.log(void("Welcome")); ``` All these statements would print `undefined` ``` var a = 1, b = 2; void(a = a + b) console.log(a); ``` And this would print `3`. So, it is evident that, it evaluates the expressions we pass to it. **Edit:** As I learn from this answer <https://stackoverflow.com/a/7452352/1903116> `undefined` is just a global property which can be written to. For example, ``` console.log(undefined); var undefined = 1; console.log(undefined); ``` It prints ``` undefined 1 ``` So, if you want to absolutely make sure that the `undefined` is used, you can use `void` operator. As it is an operator, it cannot be overridden in javascript.
`void` also evaluates the expression you pass to it. It doesn't *just* return `undefined`.
60,934,272
I need to understand how we can delete a docker image using Kubernetes. I'm using Jenkins for pipeline automation and Jenkins only has access to the master node, not the slaves. So when I generate the deploy everything works fine, the deploy makes the slaves pull from the repository and I get everything going. But if Jenkins kills the deploy and tries to remove the image, it only deletes the image on the master node and not on other slaves. So I don't want to manually delete the image. Is there a way to delete images on slave nodes from the master node?
2020/03/30
[ "https://Stackoverflow.com/questions/60934272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12712285/" ]
Kubelet does eventually garbage collect old unused images when disk usage gets beyond 85% (default setting). Otherwise kubernetes doesn't provide a remote interface for deleting images. To do it would require something like an SSH to each node or to run a Daemonset that has permissions to manage the underlying container runtime. See [Mr.Axe answer for the Docker/SSH variant](https://stackoverflow.com/a/60939609/1318694).
From master node, You can write shell script/ansible playbook to ssh into slave nodes and remove images- ``` docker images -f "dangling=true" -q | xargs --no-run-if-empty docker rmi ```
60,934,272
I need to understand how we can delete a docker image using Kubernetes. I'm using Jenkins for pipeline automation and Jenkins only has access to the master node, not the slaves. So when I generate the deploy everything works fine, the deploy makes the slaves pull from the repository and I get everything going. But if Jenkins kills the deploy and tries to remove the image, it only deletes the image on the master node and not on other slaves. So I don't want to manually delete the image. Is there a way to delete images on slave nodes from the master node?
2020/03/30
[ "https://Stackoverflow.com/questions/60934272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12712285/" ]
Kubernetes is responsible for deleting images, It is kubelet that makes garbage collection on nodes, including image deletion, it is customizable. Deleting images by external methods is not recomended as these tools can potentially break the behavior of kubelet by removing containers expected to exist. Kubelet verify if the storage available for the images is more than 85% full, in that case it delete some images to make room. Min and Max threshold can be customized in the file /var/lib/kubelet/config.yaml imageGCHighThresholdPercent is the percent of disk usage after which image garbage collection is always run. ImageGCHighThresholdPercent is the percent of disk usage before which image garbage collection is never run. Lowest disk usage to garbage collect to. Default values are : ImageGCHighThresholdPercent 85 ImageGCLowThresholdPercent 80
From master node, You can write shell script/ansible playbook to ssh into slave nodes and remove images- ``` docker images -f "dangling=true" -q | xargs --no-run-if-empty docker rmi ```
60,934,272
I need to understand how we can delete a docker image using Kubernetes. I'm using Jenkins for pipeline automation and Jenkins only has access to the master node, not the slaves. So when I generate the deploy everything works fine, the deploy makes the slaves pull from the repository and I get everything going. But if Jenkins kills the deploy and tries to remove the image, it only deletes the image on the master node and not on other slaves. So I don't want to manually delete the image. Is there a way to delete images on slave nodes from the master node?
2020/03/30
[ "https://Stackoverflow.com/questions/60934272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12712285/" ]
Kubernetes is responsible for deleting images, It is kubelet that makes garbage collection on nodes, including image deletion, it is customizable. Deleting images by external methods is not recomended as these tools can potentially break the behavior of kubelet by removing containers expected to exist. Kubelet verify if the storage available for the images is more than 85% full, in that case it delete some images to make room. Min and Max threshold can be customized in the file /var/lib/kubelet/config.yaml imageGCHighThresholdPercent is the percent of disk usage after which image garbage collection is always run. ImageGCHighThresholdPercent is the percent of disk usage before which image garbage collection is never run. Lowest disk usage to garbage collect to. Default values are : ImageGCHighThresholdPercent 85 ImageGCLowThresholdPercent 80
Kubelet does eventually garbage collect old unused images when disk usage gets beyond 85% (default setting). Otherwise kubernetes doesn't provide a remote interface for deleting images. To do it would require something like an SSH to each node or to run a Daemonset that has permissions to manage the underlying container runtime. See [Mr.Axe answer for the Docker/SSH variant](https://stackoverflow.com/a/60939609/1318694).
72,859
Kann man die Subjunktion "so da" heutzutage noch verwenden? Also im Sinne von: > > Ich werde dies machen, so da die Bedingungen erfüllt sind. > > > So ähnliche wie der Eidesformelzusatz: "... , so wahr mir Gott helfe." Nur eben mit leicht anderer Bedeutung.
2023/01/28
[ "https://german.stackexchange.com/questions/72859", "https://german.stackexchange.com", "https://german.stackexchange.com/users/54984/" ]
Gibt es das denn wirklich? Das habe ich mit diesem Sinn noch nicht bewusst gehört und finde es auch in keinen Wörterbüchern. Ich kann die Bedeutung nur aus dem Kontext ableiten. Gibt es irgendwelche Belege aus der Literatur dafür? "So da" kenne ich nur aus Zusammenhängen, in denen "so" statt eines Relativpronomens genutzt wird: > > Ich besuche gern die Läden in der Schillerstraße, so da sind ein Bäcker, eine Drogerie und ein Delikatessgeschäft. > > Tom und Anne habe drei Kinder, so da heißen Anna, Laura und Benjamin. > > > DWDS findet: > > Man wird den Dingen, so da kommen sollen, mit Ruhe und Gelassenheit entgegensehen > > > Bei [49 angezeigten Treffern von "so da" im DWDS-Kernkorpus](https://www.dwds.de/r/?corpus=kern&q=%22so%20da%22) ist keiner dabei, bei dem es so verwendet wird wie in der Frage. Das gleiche ohne "da" gibt es natürlich ("so" anstelle von "falls"): > > Ich werde dies machen, so die Bedingungen erfüllt sind. > > > Kann es sein, dass in den Beispiel der Frage einfach "so" statt "falls" benutzt wird, und das "da" eine davon unabhängige Bedeutung im Satz hat? Benutzen kann man natürlich viel, wenn man die Bedeutung sowieso aus dem Kontext ableiten kann, aber für mich persönlich ist das fremd, und ich bin im Moment noch nicht überzeugt, dass das richtig ist. Für mich also: Nein.
Ja, aber das ist dann schon eine sehr abgehobene, wichtigtuerische Ausdrucksweise. Die weitaus gängigere Alternative ist *sofern*, was auch schon ziemlich selten gesagt sondern hauptsächlich geschrieben wird. Sagen tut man eigentlich immer *wenn*. Nicht einmal *falls*.
72,859
Kann man die Subjunktion "so da" heutzutage noch verwenden? Also im Sinne von: > > Ich werde dies machen, so da die Bedingungen erfüllt sind. > > > So ähnliche wie der Eidesformelzusatz: "... , so wahr mir Gott helfe." Nur eben mit leicht anderer Bedeutung.
2023/01/28
[ "https://german.stackexchange.com/questions/72859", "https://german.stackexchange.com", "https://german.stackexchange.com/users/54984/" ]
Eine Konjunktion "so da" ist mir nicht bekannt. Ich denke, dass das "da" zum Nebensatz gehört. Derselbe Satz in modernerem Deutsch würde *sofern* (oder auch *wenn*) statt *so* benutzen, d.h.: > > Ich werde dies machen, sofern da die Bedingungen erfüllt sind. > > > Ohne weiteren Kontext lässt sich das allerdings nicht verifizieren. Die Konjunktion *so* kann heute noch verwendet werden, so es nicht stört, dass der Satz dann ein wenig altertümlich wirkt. ;) Meist wird *so* als Einleitung eines Nebensatzes allerdings mit *denn* verwendet. Hierzu existiert auch schon eine Frage: [Bedeutung von "so denn überhaupt eine stattfindet"](https://german.stackexchange.com/questions/22544/bedeutung-von-so-denn-%C3%BCberhaupt-eine-stattfindet)
Ja, aber das ist dann schon eine sehr abgehobene, wichtigtuerische Ausdrucksweise. Die weitaus gängigere Alternative ist *sofern*, was auch schon ziemlich selten gesagt sondern hauptsächlich geschrieben wird. Sagen tut man eigentlich immer *wenn*. Nicht einmal *falls*.
72,859
Kann man die Subjunktion "so da" heutzutage noch verwenden? Also im Sinne von: > > Ich werde dies machen, so da die Bedingungen erfüllt sind. > > > So ähnliche wie der Eidesformelzusatz: "... , so wahr mir Gott helfe." Nur eben mit leicht anderer Bedeutung.
2023/01/28
[ "https://german.stackexchange.com/questions/72859", "https://german.stackexchange.com", "https://german.stackexchange.com/users/54984/" ]
Zunächst eine Antwort auf die Frage: ja, natürlich kann man "so" als Subjunktion (ähnlich zu "sofern", "falls", "wenn", etc.) verwenden, man muß sich allerdings bewußt sein, daß diese Ausdrucksweise mittlerweile ungewöhnlich ist, was nicht *per se* gegen die Verwendung spricht. Womit, wie von @Janka angemerkt, das Kriterium für "wichtigtuerisch" oder "abgehoben" erfüllt sein sollte, *tut sich mir entziehen*. Da allerdings in einigen Anworten angemerkt wurde, daß "so da" keine Konjunktion sei, sei hier eine Auflösung angemerkt: das "da" gehört nicht zur Konjunktion, sondern zum Nebensatz und wird analog zu "dort" verwendet: > > Ich ziehe Bad Sowieso als Urlaubsort in Betracht, *so da* [nämlich: dort] ein Thermalbad ist. > > > Im Falle des Originalsatzes könnte "da" auch für "in dieser Sache/Angelegenheit" stehen, was aber mangels Kontext schwer zu sagen ist.
Ja, aber das ist dann schon eine sehr abgehobene, wichtigtuerische Ausdrucksweise. Die weitaus gängigere Alternative ist *sofern*, was auch schon ziemlich selten gesagt sondern hauptsächlich geschrieben wird. Sagen tut man eigentlich immer *wenn*. Nicht einmal *falls*.
9,572,265
Over the years there must be a dozen ways to show/hide rows or showing/hiding page sections to the client in ASP.NET on the server or through client side methods like JavaScript and I am getting lost on what to do. Here are several of the ways I have used: * ASP.NET Table, with .Visible True/False on Rows server side * ASP.NET MultiView - all or nothing kind of control so each row would have to be in a MV. More of a corase grained option IMO. * HTML table with tags set to runat="server" to maipulate .Visible True/False on Rows server side either directly or through adding CSS attributes like: `Me.tr1.Attributes("class") = "ShowRows"` * HTML Table with CSS to show/hide and client side JavaScript to show rows. Gets a little bit more involved when server side results dictate when to show/hide in JS back on client. * Ajax Control Toolkit controls like Accordian or CollapsiblePanel. * jQuery with .find() to get to the proper and then .show() ...and probably many, many more. Most of the time a server-side action dictates for me at least when to show/hide rows in the UI, so I typically lean toward the server side options, but I want to get some input as to which one of these methods is most advantageous and why so I can be more consistient in my approach to doing this. Thanks!
2012/03/05
[ "https://Stackoverflow.com/questions/9572265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410937/" ]
Why do you think that the value `x` is stored in a coherent cache location? Each core has it's own cache memory but there are no guarantees of coherency between those caches unless you ask for them. And there is no guarantee about the *order* of the cache updates -- nor the frequency. One thread could add 100 to x and then the cache could be synchronized overwriting the other thread's increment of 20. The first time `x` is referenced, it gets pulled into a processor (or core) memory cache from central memory. Most likely each thread will get a 0 the first time. But it may be at the very end of the loop that anything is written back to central memory and each thread might easily write back 1000 to `x`. There is certainly no guarantees that `x` will be updated with each `x++` -- either written or re-read. In fact, you are pretty much guaranteed that `x` will *not* be updated each time unless it is synchronized. In terms of this tight loop, `x` will never be evicted from the cache so it will never be re-read automatically. Even if it wasn't such a tight loop, making some guess about when `x` will be evicted would be extremely hard to do -- even if you were always working on the same hardware. Lastly, the word really is "synchronization" instead of "atomic". `x++` is rarely an atomic operation these days (it is actually read, increment, store) but it certainly is not synchronized between cache memory locations or central storage.
Cache coherency means that as soon as one core (or a bus mastering device) writes to a memory location that location is invalidated in other (all) caches that contain it. This forces them to reload the location (in the form of a 64-byte cache line) before they can access it (R or W) the next time. So cache coherency is not data coherency it's just a guarantee that an updated location will be invalidated asap. Caches can't do more, they're always way behind the executing cores and somewhat behind each other. If one core updates a location and another does the same slightly later both caches concerned will think their location is valid (and they will both probably invalidate each other's cache lines). What kind of a guarantee is this if the data isn't guaranteed to be valid? It's the best that can be done under the circumstances. The choice is between completely synchronized cores (which would run exceedingly slowly) and running at full speed with caches (with specific, defined consequences and working solutions to handle them). The solutions are essentially very short slowdowns such that everything is synchronized afterwards. These intermittent, very short slowdowns should be weighed against the permanent slowdown of fully synchronized cores. Under normal circumstances there is no contention over the same location from different cores or bus-mastering devices. But once they begin to share certain memory locations the solutions provided allow the programmer to make sure that the necessary synchronization can be implemented. [This seems like a pretty good paper on caches](http://research.cs.wisc.edu/multifacet/theses/michael_marty_phd.pdf) ... [and this](http://www.rdrop.com/users/paulmck/scalability/paper/whymb.2010.06.07c.pdf). Edit: to be more precise on cache coherency: when a core writes to a location its own cache system will first make sure that the pertinent cache information in the caches of other cores is invalidated. So after a write only the cache of the core that wrote to the location will contain cached data about the location.
9,572,265
Over the years there must be a dozen ways to show/hide rows or showing/hiding page sections to the client in ASP.NET on the server or through client side methods like JavaScript and I am getting lost on what to do. Here are several of the ways I have used: * ASP.NET Table, with .Visible True/False on Rows server side * ASP.NET MultiView - all or nothing kind of control so each row would have to be in a MV. More of a corase grained option IMO. * HTML table with tags set to runat="server" to maipulate .Visible True/False on Rows server side either directly or through adding CSS attributes like: `Me.tr1.Attributes("class") = "ShowRows"` * HTML Table with CSS to show/hide and client side JavaScript to show rows. Gets a little bit more involved when server side results dictate when to show/hide in JS back on client. * Ajax Control Toolkit controls like Accordian or CollapsiblePanel. * jQuery with .find() to get to the proper and then .show() ...and probably many, many more. Most of the time a server-side action dictates for me at least when to show/hide rows in the UI, so I typically lean toward the server side options, but I want to get some input as to which one of these methods is most advantageous and why so I can be more consistient in my approach to doing this. Thanks!
2012/03/05
[ "https://Stackoverflow.com/questions/9572265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410937/" ]
I agree 100% with Gray's answer. However, the non-atomicity of increment is a known issue and it's not just applicable to multi-cores, as it can just as well occur on a single core machine. The fact is that `x++` is (usually) actually accomplished through several assembler instructions, for example: ``` load r,[x] ; load memory into register incr r ; increment register stor [x],r ; store register back to memory ``` so although it's a single operation in the C program, it's actually a non-atomic sequence of assembler instructions that can be interrupted at any point. So even on a single core machine, a thread might be interrupted before completing the increment, thus leaving the variable in an inconsistent state. Some compilers or architectures may indeed treat increment as atomic, but it's not a good idea to assume this.
Cache coherency means that as soon as one core (or a bus mastering device) writes to a memory location that location is invalidated in other (all) caches that contain it. This forces them to reload the location (in the form of a 64-byte cache line) before they can access it (R or W) the next time. So cache coherency is not data coherency it's just a guarantee that an updated location will be invalidated asap. Caches can't do more, they're always way behind the executing cores and somewhat behind each other. If one core updates a location and another does the same slightly later both caches concerned will think their location is valid (and they will both probably invalidate each other's cache lines). What kind of a guarantee is this if the data isn't guaranteed to be valid? It's the best that can be done under the circumstances. The choice is between completely synchronized cores (which would run exceedingly slowly) and running at full speed with caches (with specific, defined consequences and working solutions to handle them). The solutions are essentially very short slowdowns such that everything is synchronized afterwards. These intermittent, very short slowdowns should be weighed against the permanent slowdown of fully synchronized cores. Under normal circumstances there is no contention over the same location from different cores or bus-mastering devices. But once they begin to share certain memory locations the solutions provided allow the programmer to make sure that the necessary synchronization can be implemented. [This seems like a pretty good paper on caches](http://research.cs.wisc.edu/multifacet/theses/michael_marty_phd.pdf) ... [and this](http://www.rdrop.com/users/paulmck/scalability/paper/whymb.2010.06.07c.pdf). Edit: to be more precise on cache coherency: when a core writes to a location its own cache system will first make sure that the pertinent cache information in the caches of other cores is invalidated. So after a write only the cache of the core that wrote to the location will contain cached data about the location.
21,913,640
How do I upload a excel spreadsheet into existing table using ColdFusion10? I have an an excel spreadsheet that has been saved and I have CFQuery ("myQuery") that outputs the data I need. How do I loop through the query and import into an existing table? Database: MS SQL Server Thus far, I understand that I need to loop through the query I have that has all the data. ``` <cffunction name="uploadDogSheet" access="public" output="yes" returnType="void" hint="upload the spreadSheet"> <cfset currentRowChecked = "1"> <cfset lastRow = numberOfRows> <!-- sets the number of rows that it will validate--> <cfspreadsheet action="read" src="#SESSION.theExcelFile#" headerrow= "1" excludeHeaderRow = "true" query = "allDoggyData" rows = "1-#lastRow#" /> <cfscript> allDataQuery = new Query( sql ="SELECT * FROM allDoggyData", dbtype = "query", allData = allData); allDataQueryResult = allDataQuery.execute().getResult(); </cfscript> <cfloop query="allDoggyData"> <CFQUERY DATASOURCE="#mydatabase#" name="input_req"> insert into temp_dog_upload (dogNameColumn, dogBreedColumn, dogColor) values ( <cfqueryparam value="#allDoggyData.dogNameExcelColumn#" cfsqltype="cf_sql_varchar">, <cfqueryparam value="#allDoggyData.dogBreedExcelColumn#" cfsqltype="cf_sql_varchar">, <cfqueryparam value="#allDoggyData.dogColorExcelColumn#" cfsqltype="cf_sql_varchar"> ) </CFQUERY> </cfloop> <p>The sheet has been uploaded!<p></span> ```
2014/02/20
[ "https://Stackoverflow.com/questions/21913640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1245463/" ]
What you are asking is pretty simple. Upload the spreadsheet to your sever then use cfspreadsheet to read it. ``` <cfspreadsheet action="read" src = "filepath" columns = "range" columnnames = "comma-delimited list" excludeHeaderRow = "true | false" format = "CSV|HTML" headerrow = "row number" name = "text" query = "query name" rows = "range" sheet = "number" sheetname = "text"> ``` Then simply loop through the query that you defined in the cfspreadsheet ``` <cfloop query="queryname"> <cfquery name="" datasource=""> INSERT INTO .... </cfquery </cfloop> ``` P.S. This was my answer BEFORE you deleted the post and I was no longer able to submit my answer.
There are a couple of approaches to take. They both have one very important detail in common. Put the spreadsheet data into a staging table first. Process and validate as required first, and then write to your main tables from your staging table. Method 1 is to have your web page accept files from your users and put them somewhere. Then, write an SSIS package that looks for these files, loads them into your staging table, and carrys on until the job is done. Then write an agent to schedule this job to run at the appropriate interval. Method 2 is to use continue with ColdFusion. You have already read the spreadsheet into a query. Loop through that query to populate your staging table and carry on processing. There are a couple of things to look out for with each method. With Method 1, there might be more than one file to be processed. Your package will have to handle that. With Method 2, there might be two users looking to process files at the same time. You'll have to make sure the two requests don't interfere with each other. As far as your specific question of "How do I loop through the query and import into an existing table? ", like this: ``` <cfoutput query="yourquery"> <cfquery datasource="something"> insert into atable (fields go here) values (values, using cfqueryparam go here) </cfquery> </cfoutput> ```
27,990,239
So i just created a new google maps activity and it gives me a null pointer exception if i try to run my application ``` private GoogleMap mMap; // Might be null if Google Play services APK is not available. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setUpMapIfNeeded(); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } private void setUpMap() { mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker")); } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } ``` this is my layout ``` <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/map" tools:context="android.ehb.be.lab4sqlliteex.MapsActivity" android:name="com.google.android.gms.maps.SupportMapFragment"/> ``` it is just auto-generated by android studio when i added my activity. My class extends FragmentActivity this is my manifest file ``` <?xml version="1.0" encoding="utf-8"?> ``` ``` <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/> <!-- The ACCESS_COARSE/FINE_LOCATION permissions are not required to use Google Maps Android API v2, but are recommended. --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="@string/google_maps_key"/> <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="17" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyBxMzLA6jjVtPQEHOrOPTRzKnjPu6bKKGA" /> <activity android:name="android.ehb.be.lab4sqlliteex.MapsActivity" android:label="@string/title_activity_maps"> </activity> <activity android:name=".BucketListActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".AlbumsActivity" android:label="Albums" android:parentActivityName=".BucketListActivity"> </activity> </application> ``` Anybody an idea how to fix this? This is the error i get: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{android.ehb.be.lab4sqlliteex/android.ehb.be.lab4sqlliteex.MapsActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2641) at android.app.ActivityThread.access$800(ActivityThread.java:156) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:157) at android.app.ActivityThread.main(ActivityThread.java:5867) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at android.ehb.be.lab4sqlliteex.MapsActivity.setUpMapIfNeeded(MapsActivity.java:46) at android.ehb.be.lab4sqlliteex.MapsActivity.onCreate(MapsActivity.java:18) ```
2015/01/16
[ "https://Stackoverflow.com/questions/27990239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3598993/" ]
**Update:** Are you posting and redirecting? When you refresh the form does it prompt you about posting again? If not, it's because you have accidentally followed the best practice of 302ing from a form post (prevents a user refreshing and reposting form data). The examples I was following for login surface controllers all used `return RedirectToCurrentUmbracoPage()` which I blindly followed. But, as the name implies that really is doing a redirect and it is really two requests! (I stubbornly had to verify in Fiddler before I believed it). ViewData and ViewBag are only good for one request--so they are fundamentally broken in a POST 302. Session is good for multiple requests which is why it worked for you. TempData will work for you too, because as it turns out, TempData is a construct that is built on top of session and was specifically designed to carry state between two posts (removed on retrieve). I read somewhere that TempData would have been better named `RedirectData` and that helped it click for me. So when you're dealing with Surface Controllers and POSTing you have three options that I know work: * Session (which you proved worked) * TempData (which is built on session, and from what I've read is both best practice and built specifically for this situation) * Use `return CurrentUmbracoPage();` in your form post. I just verified in Fiddler that this is exactly one request (refreshing in the browser prompts a repost warning). I also verified that ViewData works this way. But, because the surface controller is rendered as a Child Action using `@Html.Action(...)` you have to use `ParentActionViewContext` to get at the right ViewData (my first answer which I'll leave for others that find this question). --- Original answer is still useful when there is no redirect involved (GET or a POST that returns `CurrentUmbracoPage()`)... In many cases you're actually making a child action. Usually you're only one level deep but if you mix macros and partials you can actually get multiple levels deep. There is a ViewData for each level and you have to walk your way up the stack with `ParentActionViewContext` to get to the top `ViewData` that you populated in your controller. See [this comment from Shannon](http://our.umbraco.org/forum/developers/api-questions/36614-411-Using-SurfaceController-Child-Action-with-Post?p=2#comment136281) in answer to a question about surface controllers and viewdata (Shannon is a core contributor on the HQ team and has a lot of great content out there). Quoting here: > > If you want to access the ViewData that you've set on the master ViewContext's on a ChildAction being rendered from the master's ViewContext then you need to use @ViewContext.ParentActionViewContext.ViewData["ErrorMessage"] > > > The ParentActionViewContext in this example is the ViewContext that is rendering the Umbraco template, not the ChildAction. That is because when you POST (whether inside of Umbraco or normal MVC), you are posting to a new Action and the rendering process starts from scratch, when you validate your model, update the ViewData, etc... this all happens on what will become the 'master' ViewContext when the view renders. This view then will render your ChildAction. > > >
Twamley's answer above is excellent, in addition to this, I have found that using `TempData.Add(key, value)` works nicely. An bare bones would look like: **SurfaceController** ``` public class MyController : Umbraco.Web.Mvc.SurfaceController { public MyController() {} public ActionResult DoSomething() { // surface controller does something // get a page by it's document/model type alias var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); var node = umbracoHelper.TypedContentSingleAtXPath("//" + "Home") TempData.Add("Message", "This value will be passed through"); return redirectToUmbracoPage(node); } } ``` **View** ``` @inherits UmbracoTemplatePage @{ Layout = null; } @if (TempData.ContainsKey("Message")) { <p>@TempData["Message"]</p> } ``` <http://localhost/umbraco/Surface/My/DoSomething>
10,323,013
I've been working on a existing project at a new company and one of the problems we're running into is Javascript code duplication. We're working in Google App Engine, and I have heard of the [Django media generator asset manager](http://www.allbuttonspressed.com/projects/django-mediagenerator) which seems like it could solve some of our problems. However, after reading through the docs on that page and pages [like this one on running Django in Google App Engine](https://developers.google.com/appengine/articles/django), I'm not sure if it is even possible to run django-mediagenerator on Google App engine. Is it still possible to use django-mediagenerator on Google App Engine? Has the project gone stale? Is there some other media generator that I should be using in app engine? Any help would be appreciated. Thanks :)
2012/04/25
[ "https://Stackoverflow.com/questions/10323013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
You simply need:`document.getElementById('nameofform').submit()` is easier to find elements by its id than for the name. Other way is to get elements by name, you can do it with `document.getElementsByName('nameofform')`...But that returns an array so you need to iterate that array to find which of those forms is needed to be uploaded. So, I think you should use the id.
The name of your form contains characters that cannot be used in a JavaScript identifier (dashes). Use `document.getElementById('vintro-upload-form').submit();` instead.
10,323,013
I've been working on a existing project at a new company and one of the problems we're running into is Javascript code duplication. We're working in Google App Engine, and I have heard of the [Django media generator asset manager](http://www.allbuttonspressed.com/projects/django-mediagenerator) which seems like it could solve some of our problems. However, after reading through the docs on that page and pages [like this one on running Django in Google App Engine](https://developers.google.com/appengine/articles/django), I'm not sure if it is even possible to run django-mediagenerator on Google App engine. Is it still possible to use django-mediagenerator on Google App Engine? Has the project gone stale? Is there some other media generator that I should be using in app engine? Any help would be appreciated. Thanks :)
2012/04/25
[ "https://Stackoverflow.com/questions/10323013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
This JavaScript: `document.forms["vintro-upload-form"].elements['file'].value` is looking for the NAME attribute of the form tag: `document.forms[{form_name}].elements[{field_name}].value` You just have an ID. Copy the value of the ID to a NAME and you're done. However, document.getElementById() is the preferred, modern way of doing this with plain JavaScript. **HOWEVER: You can't have a submit / button named "submit".** When you do and you call the JavaScript submit() function, you get a conflict.
You simply need:`document.getElementById('nameofform').submit()` is easier to find elements by its id than for the name. Other way is to get elements by name, you can do it with `document.getElementsByName('nameofform')`...But that returns an array so you need to iterate that array to find which of those forms is needed to be uploaded. So, I think you should use the id.
10,323,013
I've been working on a existing project at a new company and one of the problems we're running into is Javascript code duplication. We're working in Google App Engine, and I have heard of the [Django media generator asset manager](http://www.allbuttonspressed.com/projects/django-mediagenerator) which seems like it could solve some of our problems. However, after reading through the docs on that page and pages [like this one on running Django in Google App Engine](https://developers.google.com/appengine/articles/django), I'm not sure if it is even possible to run django-mediagenerator on Google App engine. Is it still possible to use django-mediagenerator on Google App Engine? Has the project gone stale? Is there some other media generator that I should be using in app engine? Any help would be appreciated. Thanks :)
2012/04/25
[ "https://Stackoverflow.com/questions/10323013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
This JavaScript: `document.forms["vintro-upload-form"].elements['file'].value` is looking for the NAME attribute of the form tag: `document.forms[{form_name}].elements[{field_name}].value` You just have an ID. Copy the value of the ID to a NAME and you're done. However, document.getElementById() is the preferred, modern way of doing this with plain JavaScript. **HOWEVER: You can't have a submit / button named "submit".** When you do and you call the JavaScript submit() function, you get a conflict.
The name of your form contains characters that cannot be used in a JavaScript identifier (dashes). Use `document.getElementById('vintro-upload-form').submit();` instead.
54,282,689
I have an android ProgressBar which is indeterminate so it is simply a revolving circle animation. It starts off displaying fine, but after I set the visibility of its parent (`overlayLayout`) to either gone or invisible and then set it back to visible later on, the progress bar is unseen? ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/overlayLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:gravity="center" > <TextView android:text="" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_width="match_parent" android:textAlignment="center" android:layout_margin="10dp" android:layout_height="wrap_content" android:id="@+id/overlayLabelText" /> <ProgressBar android:id="@+id/overlayProgressBar" android:layout_below="@id/overlayLabelText" android:layout_width="match_parent" android:layout_height="wrap_content" android:foregroundGravity="center" android:indeterminate="true" /> </RelativeLayout> ``` EDIT: I'm unsure if the view is included but the progress bar is just not rendered or whether the ProgressBar view itself is completely excluded as I can't access the UI view hierarchy. So far I have tried: ``` ProgressBar.Enabled = true; ProgressBar.ForceLayout(); ProgressBar.Invalidate(); ProgressBar.SetProgress(0, true); ProgressBar.Visibility = ViewStates.Visible; ``` But have had no breakthroughs yet. **EDIT 2:** Thankyou everyone for your help so far. I have switched to creating the layout programatically - this is my full code: ``` overlay = new RelativeLayout(mainActivity) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent) }; overlay.SetBackgroundColor(Color.WhiteSmoke); overlay.SetGravity(GravityFlags.Center); description = new TextView(mainActivity) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent), Gravity = GravityFlags.Center, TextSize = 18, Id = 1523112 }; description.Text = "Waiting for GPS"; description.SetBackgroundColor(Color.Aqua); progressBar = new ProgressBar(mainActivity) { Indeterminate = true, }; RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); lp.AddRule(LayoutRules.Below, description.Id); progressBar.LayoutParameters = lp; progressBar.SetBackgroundColor(Color.Red); container.AddView(overlay); overlay.AddView(description); overlay.AddView(progressBar); ``` With the two hiding and showing methods: ``` private void OnGpsUpdate() { overlay.Visibility = ViewStates.Gone; } private void NoGPS() { description.Text = "Waiting for GPS"; overlay.Visibility = ViewStates.Visible; } ``` When the layout is first rendered, before its hidden for the first time: *(I screenshotted at a bad time, but blue drawing shows where the circle is moving around its loading animation)* [![enter image description here](https://i.stack.imgur.com/nmKYc.png)](https://i.stack.imgur.com/nmKYc.png) After its been hidden and shown again, the progressBar loading view is there but there's no loading circle anymore: [![enter image description here](https://i.stack.imgur.com/3a5dm.png)](https://i.stack.imgur.com/3a5dm.png) I am starting to think it may just be a problem with my android emulator? Nope, same problem when testing on my physical phone. Text view still shows fine, its just the progress bar doesnt show? **SOLUTION** I don't fully understand it, seeing as everything else seemed to work except the progressBar, but a solution came from wrapping my visibility calls in a RunOnUIThread() call.
2019/01/21
[ "https://Stackoverflow.com/questions/54282689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8250558/" ]
**Few points** Based on how the problem was described, there is a need for you to show the code snippet you used for hiding/showing the `overlayLayout` **Recommendations** If you're only concerned with how the progress bar should behave in terms of hiding/showing, there's no need for this snippet: ```java ProgressBar.Enabled = true; ProgressBar.ForceLayout(); ProgressBar.Invalidate(); ProgressBar.SetProgress(0, true); ProgressBar.Visibility = ViewStates.Visible; ``` You just need to control the root layout which has the id of `overlayLayout` ```java private RelativeLayout overlayLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); // Instantiate the layout overlayLayout = findViewById(R.id.overlayLayout); // Do the logic how you inflate/show the layout ... // Hide the overlay layout overlayLayout.setVisibility(View.GONE); // Show the overlay layout overlayLayout.setVisibility(View.VISIBLE); } ``` Decide on the visibility value, for this scenario, I'd recommend `View.GONE` rather than `View.INVISIBLE` Read more on: * <https://developer.android.com/reference/android/view/View.html#GONE> * <https://developer.android.com/reference/android/view/View.html#INVISIBLE> * <http://tips.androidgig.com/invisible-vs-gone-view-in-android/>
to hide layout: ``` findViewById(R.id.overlayLayout).setVisibility(View.GONE); ``` to display it again : ``` findViewById(R.id.overlayLayout).setVisibility(View.VISIBLE); ```
54,282,689
I have an android ProgressBar which is indeterminate so it is simply a revolving circle animation. It starts off displaying fine, but after I set the visibility of its parent (`overlayLayout`) to either gone or invisible and then set it back to visible later on, the progress bar is unseen? ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/overlayLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:gravity="center" > <TextView android:text="" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_width="match_parent" android:textAlignment="center" android:layout_margin="10dp" android:layout_height="wrap_content" android:id="@+id/overlayLabelText" /> <ProgressBar android:id="@+id/overlayProgressBar" android:layout_below="@id/overlayLabelText" android:layout_width="match_parent" android:layout_height="wrap_content" android:foregroundGravity="center" android:indeterminate="true" /> </RelativeLayout> ``` EDIT: I'm unsure if the view is included but the progress bar is just not rendered or whether the ProgressBar view itself is completely excluded as I can't access the UI view hierarchy. So far I have tried: ``` ProgressBar.Enabled = true; ProgressBar.ForceLayout(); ProgressBar.Invalidate(); ProgressBar.SetProgress(0, true); ProgressBar.Visibility = ViewStates.Visible; ``` But have had no breakthroughs yet. **EDIT 2:** Thankyou everyone for your help so far. I have switched to creating the layout programatically - this is my full code: ``` overlay = new RelativeLayout(mainActivity) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent) }; overlay.SetBackgroundColor(Color.WhiteSmoke); overlay.SetGravity(GravityFlags.Center); description = new TextView(mainActivity) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent), Gravity = GravityFlags.Center, TextSize = 18, Id = 1523112 }; description.Text = "Waiting for GPS"; description.SetBackgroundColor(Color.Aqua); progressBar = new ProgressBar(mainActivity) { Indeterminate = true, }; RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); lp.AddRule(LayoutRules.Below, description.Id); progressBar.LayoutParameters = lp; progressBar.SetBackgroundColor(Color.Red); container.AddView(overlay); overlay.AddView(description); overlay.AddView(progressBar); ``` With the two hiding and showing methods: ``` private void OnGpsUpdate() { overlay.Visibility = ViewStates.Gone; } private void NoGPS() { description.Text = "Waiting for GPS"; overlay.Visibility = ViewStates.Visible; } ``` When the layout is first rendered, before its hidden for the first time: *(I screenshotted at a bad time, but blue drawing shows where the circle is moving around its loading animation)* [![enter image description here](https://i.stack.imgur.com/nmKYc.png)](https://i.stack.imgur.com/nmKYc.png) After its been hidden and shown again, the progressBar loading view is there but there's no loading circle anymore: [![enter image description here](https://i.stack.imgur.com/3a5dm.png)](https://i.stack.imgur.com/3a5dm.png) I am starting to think it may just be a problem with my android emulator? Nope, same problem when testing on my physical phone. Text view still shows fine, its just the progress bar doesnt show? **SOLUTION** I don't fully understand it, seeing as everything else seemed to work except the progressBar, but a solution came from wrapping my visibility calls in a RunOnUIThread() call.
2019/01/21
[ "https://Stackoverflow.com/questions/54282689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8250558/" ]
I wrote a demo based on your code. And to test it, I added a button to control the show and hide of the layout. You may try this: ``` protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.activity_main); // Instantiate the layout overlayLayout = FindViewById<LinearLayout>(Resource.Id.overlayLayout); progressBar = FindViewById<ProgressBar>(Resource.Id.overlayProgressBar); description = FindViewById<TextView>(Resource.Id.textView1); description.Text = "Waiting for GPS"; description.SetBackgroundColor(Color.Aqua); progressBar.SetBackgroundColor(Color.Red); switchBtn = FindViewById<Button>(Resource.Id.switchButton); switchBtn.Click += SwitchBtn_Click; overlayLayout.Visibility = Android.Views.ViewStates.Visible; isShown = true; } private void SwitchBtn_Click(object sender, System.EventArgs e) { if (isShown) { overlayLayout.Visibility = Android.Views.ViewStates.Gone; isShown = false; switchBtn.Text = "Show"; } else { overlayLayout.Visibility = Android.Views.ViewStates.Visible; isShown = true; switchBtn.Text = "Hide"; } ``` You can download the demo from [this](https://github.com/lemontreexf123/app10)
to hide layout: ``` findViewById(R.id.overlayLayout).setVisibility(View.GONE); ``` to display it again : ``` findViewById(R.id.overlayLayout).setVisibility(View.VISIBLE); ```
54,282,689
I have an android ProgressBar which is indeterminate so it is simply a revolving circle animation. It starts off displaying fine, but after I set the visibility of its parent (`overlayLayout`) to either gone or invisible and then set it back to visible later on, the progress bar is unseen? ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/overlayLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:gravity="center" > <TextView android:text="" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_width="match_parent" android:textAlignment="center" android:layout_margin="10dp" android:layout_height="wrap_content" android:id="@+id/overlayLabelText" /> <ProgressBar android:id="@+id/overlayProgressBar" android:layout_below="@id/overlayLabelText" android:layout_width="match_parent" android:layout_height="wrap_content" android:foregroundGravity="center" android:indeterminate="true" /> </RelativeLayout> ``` EDIT: I'm unsure if the view is included but the progress bar is just not rendered or whether the ProgressBar view itself is completely excluded as I can't access the UI view hierarchy. So far I have tried: ``` ProgressBar.Enabled = true; ProgressBar.ForceLayout(); ProgressBar.Invalidate(); ProgressBar.SetProgress(0, true); ProgressBar.Visibility = ViewStates.Visible; ``` But have had no breakthroughs yet. **EDIT 2:** Thankyou everyone for your help so far. I have switched to creating the layout programatically - this is my full code: ``` overlay = new RelativeLayout(mainActivity) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent) }; overlay.SetBackgroundColor(Color.WhiteSmoke); overlay.SetGravity(GravityFlags.Center); description = new TextView(mainActivity) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent), Gravity = GravityFlags.Center, TextSize = 18, Id = 1523112 }; description.Text = "Waiting for GPS"; description.SetBackgroundColor(Color.Aqua); progressBar = new ProgressBar(mainActivity) { Indeterminate = true, }; RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); lp.AddRule(LayoutRules.Below, description.Id); progressBar.LayoutParameters = lp; progressBar.SetBackgroundColor(Color.Red); container.AddView(overlay); overlay.AddView(description); overlay.AddView(progressBar); ``` With the two hiding and showing methods: ``` private void OnGpsUpdate() { overlay.Visibility = ViewStates.Gone; } private void NoGPS() { description.Text = "Waiting for GPS"; overlay.Visibility = ViewStates.Visible; } ``` When the layout is first rendered, before its hidden for the first time: *(I screenshotted at a bad time, but blue drawing shows where the circle is moving around its loading animation)* [![enter image description here](https://i.stack.imgur.com/nmKYc.png)](https://i.stack.imgur.com/nmKYc.png) After its been hidden and shown again, the progressBar loading view is there but there's no loading circle anymore: [![enter image description here](https://i.stack.imgur.com/3a5dm.png)](https://i.stack.imgur.com/3a5dm.png) I am starting to think it may just be a problem with my android emulator? Nope, same problem when testing on my physical phone. Text view still shows fine, its just the progress bar doesnt show? **SOLUTION** I don't fully understand it, seeing as everything else seemed to work except the progressBar, but a solution came from wrapping my visibility calls in a RunOnUIThread() call.
2019/01/21
[ "https://Stackoverflow.com/questions/54282689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8250558/" ]
The solution was to add a `RunOnUIThread` like so: ``` private void OnNewGPS() { mainActivity.RunOnUiThread(() => { overlay.Visibility = ViewStates.Gone; }); } private void NoGPS() { mainActivity.RunOnUiThread(() => { overlay.Visibility = ViewStates.Visible; }); } ``` Where mainActivity is a reference to the Activity the views are running in.
to hide layout: ``` findViewById(R.id.overlayLayout).setVisibility(View.GONE); ``` to display it again : ``` findViewById(R.id.overlayLayout).setVisibility(View.VISIBLE); ```
54,282,689
I have an android ProgressBar which is indeterminate so it is simply a revolving circle animation. It starts off displaying fine, but after I set the visibility of its parent (`overlayLayout`) to either gone or invisible and then set it back to visible later on, the progress bar is unseen? ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/overlayLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:gravity="center" > <TextView android:text="" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_width="match_parent" android:textAlignment="center" android:layout_margin="10dp" android:layout_height="wrap_content" android:id="@+id/overlayLabelText" /> <ProgressBar android:id="@+id/overlayProgressBar" android:layout_below="@id/overlayLabelText" android:layout_width="match_parent" android:layout_height="wrap_content" android:foregroundGravity="center" android:indeterminate="true" /> </RelativeLayout> ``` EDIT: I'm unsure if the view is included but the progress bar is just not rendered or whether the ProgressBar view itself is completely excluded as I can't access the UI view hierarchy. So far I have tried: ``` ProgressBar.Enabled = true; ProgressBar.ForceLayout(); ProgressBar.Invalidate(); ProgressBar.SetProgress(0, true); ProgressBar.Visibility = ViewStates.Visible; ``` But have had no breakthroughs yet. **EDIT 2:** Thankyou everyone for your help so far. I have switched to creating the layout programatically - this is my full code: ``` overlay = new RelativeLayout(mainActivity) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent) }; overlay.SetBackgroundColor(Color.WhiteSmoke); overlay.SetGravity(GravityFlags.Center); description = new TextView(mainActivity) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent), Gravity = GravityFlags.Center, TextSize = 18, Id = 1523112 }; description.Text = "Waiting for GPS"; description.SetBackgroundColor(Color.Aqua); progressBar = new ProgressBar(mainActivity) { Indeterminate = true, }; RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); lp.AddRule(LayoutRules.Below, description.Id); progressBar.LayoutParameters = lp; progressBar.SetBackgroundColor(Color.Red); container.AddView(overlay); overlay.AddView(description); overlay.AddView(progressBar); ``` With the two hiding and showing methods: ``` private void OnGpsUpdate() { overlay.Visibility = ViewStates.Gone; } private void NoGPS() { description.Text = "Waiting for GPS"; overlay.Visibility = ViewStates.Visible; } ``` When the layout is first rendered, before its hidden for the first time: *(I screenshotted at a bad time, but blue drawing shows where the circle is moving around its loading animation)* [![enter image description here](https://i.stack.imgur.com/nmKYc.png)](https://i.stack.imgur.com/nmKYc.png) After its been hidden and shown again, the progressBar loading view is there but there's no loading circle anymore: [![enter image description here](https://i.stack.imgur.com/3a5dm.png)](https://i.stack.imgur.com/3a5dm.png) I am starting to think it may just be a problem with my android emulator? Nope, same problem when testing on my physical phone. Text view still shows fine, its just the progress bar doesnt show? **SOLUTION** I don't fully understand it, seeing as everything else seemed to work except the progressBar, but a solution came from wrapping my visibility calls in a RunOnUIThread() call.
2019/01/21
[ "https://Stackoverflow.com/questions/54282689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8250558/" ]
**Few points** Based on how the problem was described, there is a need for you to show the code snippet you used for hiding/showing the `overlayLayout` **Recommendations** If you're only concerned with how the progress bar should behave in terms of hiding/showing, there's no need for this snippet: ```java ProgressBar.Enabled = true; ProgressBar.ForceLayout(); ProgressBar.Invalidate(); ProgressBar.SetProgress(0, true); ProgressBar.Visibility = ViewStates.Visible; ``` You just need to control the root layout which has the id of `overlayLayout` ```java private RelativeLayout overlayLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_example); // Instantiate the layout overlayLayout = findViewById(R.id.overlayLayout); // Do the logic how you inflate/show the layout ... // Hide the overlay layout overlayLayout.setVisibility(View.GONE); // Show the overlay layout overlayLayout.setVisibility(View.VISIBLE); } ``` Decide on the visibility value, for this scenario, I'd recommend `View.GONE` rather than `View.INVISIBLE` Read more on: * <https://developer.android.com/reference/android/view/View.html#GONE> * <https://developer.android.com/reference/android/view/View.html#INVISIBLE> * <http://tips.androidgig.com/invisible-vs-gone-view-in-android/>
I wrote a demo based on your code. And to test it, I added a button to control the show and hide of the layout. You may try this: ``` protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.activity_main); // Instantiate the layout overlayLayout = FindViewById<LinearLayout>(Resource.Id.overlayLayout); progressBar = FindViewById<ProgressBar>(Resource.Id.overlayProgressBar); description = FindViewById<TextView>(Resource.Id.textView1); description.Text = "Waiting for GPS"; description.SetBackgroundColor(Color.Aqua); progressBar.SetBackgroundColor(Color.Red); switchBtn = FindViewById<Button>(Resource.Id.switchButton); switchBtn.Click += SwitchBtn_Click; overlayLayout.Visibility = Android.Views.ViewStates.Visible; isShown = true; } private void SwitchBtn_Click(object sender, System.EventArgs e) { if (isShown) { overlayLayout.Visibility = Android.Views.ViewStates.Gone; isShown = false; switchBtn.Text = "Show"; } else { overlayLayout.Visibility = Android.Views.ViewStates.Visible; isShown = true; switchBtn.Text = "Hide"; } ``` You can download the demo from [this](https://github.com/lemontreexf123/app10)
54,282,689
I have an android ProgressBar which is indeterminate so it is simply a revolving circle animation. It starts off displaying fine, but after I set the visibility of its parent (`overlayLayout`) to either gone or invisible and then set it back to visible later on, the progress bar is unseen? ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/overlayLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:gravity="center" > <TextView android:text="" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_width="match_parent" android:textAlignment="center" android:layout_margin="10dp" android:layout_height="wrap_content" android:id="@+id/overlayLabelText" /> <ProgressBar android:id="@+id/overlayProgressBar" android:layout_below="@id/overlayLabelText" android:layout_width="match_parent" android:layout_height="wrap_content" android:foregroundGravity="center" android:indeterminate="true" /> </RelativeLayout> ``` EDIT: I'm unsure if the view is included but the progress bar is just not rendered or whether the ProgressBar view itself is completely excluded as I can't access the UI view hierarchy. So far I have tried: ``` ProgressBar.Enabled = true; ProgressBar.ForceLayout(); ProgressBar.Invalidate(); ProgressBar.SetProgress(0, true); ProgressBar.Visibility = ViewStates.Visible; ``` But have had no breakthroughs yet. **EDIT 2:** Thankyou everyone for your help so far. I have switched to creating the layout programatically - this is my full code: ``` overlay = new RelativeLayout(mainActivity) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent) }; overlay.SetBackgroundColor(Color.WhiteSmoke); overlay.SetGravity(GravityFlags.Center); description = new TextView(mainActivity) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent), Gravity = GravityFlags.Center, TextSize = 18, Id = 1523112 }; description.Text = "Waiting for GPS"; description.SetBackgroundColor(Color.Aqua); progressBar = new ProgressBar(mainActivity) { Indeterminate = true, }; RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); lp.AddRule(LayoutRules.Below, description.Id); progressBar.LayoutParameters = lp; progressBar.SetBackgroundColor(Color.Red); container.AddView(overlay); overlay.AddView(description); overlay.AddView(progressBar); ``` With the two hiding and showing methods: ``` private void OnGpsUpdate() { overlay.Visibility = ViewStates.Gone; } private void NoGPS() { description.Text = "Waiting for GPS"; overlay.Visibility = ViewStates.Visible; } ``` When the layout is first rendered, before its hidden for the first time: *(I screenshotted at a bad time, but blue drawing shows where the circle is moving around its loading animation)* [![enter image description here](https://i.stack.imgur.com/nmKYc.png)](https://i.stack.imgur.com/nmKYc.png) After its been hidden and shown again, the progressBar loading view is there but there's no loading circle anymore: [![enter image description here](https://i.stack.imgur.com/3a5dm.png)](https://i.stack.imgur.com/3a5dm.png) I am starting to think it may just be a problem with my android emulator? Nope, same problem when testing on my physical phone. Text view still shows fine, its just the progress bar doesnt show? **SOLUTION** I don't fully understand it, seeing as everything else seemed to work except the progressBar, but a solution came from wrapping my visibility calls in a RunOnUIThread() call.
2019/01/21
[ "https://Stackoverflow.com/questions/54282689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8250558/" ]
The solution was to add a `RunOnUIThread` like so: ``` private void OnNewGPS() { mainActivity.RunOnUiThread(() => { overlay.Visibility = ViewStates.Gone; }); } private void NoGPS() { mainActivity.RunOnUiThread(() => { overlay.Visibility = ViewStates.Visible; }); } ``` Where mainActivity is a reference to the Activity the views are running in.
I wrote a demo based on your code. And to test it, I added a button to control the show and hide of the layout. You may try this: ``` protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.activity_main); // Instantiate the layout overlayLayout = FindViewById<LinearLayout>(Resource.Id.overlayLayout); progressBar = FindViewById<ProgressBar>(Resource.Id.overlayProgressBar); description = FindViewById<TextView>(Resource.Id.textView1); description.Text = "Waiting for GPS"; description.SetBackgroundColor(Color.Aqua); progressBar.SetBackgroundColor(Color.Red); switchBtn = FindViewById<Button>(Resource.Id.switchButton); switchBtn.Click += SwitchBtn_Click; overlayLayout.Visibility = Android.Views.ViewStates.Visible; isShown = true; } private void SwitchBtn_Click(object sender, System.EventArgs e) { if (isShown) { overlayLayout.Visibility = Android.Views.ViewStates.Gone; isShown = false; switchBtn.Text = "Show"; } else { overlayLayout.Visibility = Android.Views.ViewStates.Visible; isShown = true; switchBtn.Text = "Hide"; } ``` You can download the demo from [this](https://github.com/lemontreexf123/app10)
6,245,898
When I add a number beginning with 0 into my MySQL database, it automatically gets converted to a single digit. These are mobile numbers, so I need to keep it starting with 0.
2011/06/05
[ "https://Stackoverflow.com/questions/6245898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/785129/" ]
Store phone numbers as strings, not integers. (related: [Common MySQL fields and their appropriate data types](https://stackoverflow.com/questions/354763/common-mysql-fields-and-their-appropriate-data-types) )
Try storing the numbers as varchars instead. When you retreive them from the database you could cast them using (int) if needed.
39,810,097
Using JavaScript, Is there a way to split the string to an array with two separators: ':' and ',' For var str = "21:223, 310:320"; would like the Result to be: [21, 223, 310, 320]; Thanks!
2016/10/01
[ "https://Stackoverflow.com/questions/39810097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355407/" ]
You could use a regular expression which looks for a `:` or for a comma with an optional space `,`. ```js console.log("21:223, 310:320,42".split(/:|, */)); ```
You can use `match` if your expression is like this `"21:223, 310:320"` ```js var str = "21 : 223 , 310 : 320 "; //---------^^----^^^---^^^----^^^-- // group of digits(represented by ^) will be matched console.log(str.match(/(\d+)/g)); // will return ["21", "223", "310", "320"] ```
15,093,973
I have a Java program I am converting into objective-c. In Java I uses dot notation and for for example have the following line of code: ``` this.m_root.computeGlobalTransforms(); ``` Which calls a method called computeGlobalTransforms(). Am I able to use dot notation like this in objective-c or will I need to write the line as and pass 'm\_root' as an object: ``` [self computeGlobalTransforms:m_root]; ```
2013/02/26
[ "https://Stackoverflow.com/questions/15093973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1245216/" ]
If `computeGlobalTransforms` is an instance method of the class `m_root` object, and if `m_root` is a class property of `self`, then the syntax is: ``` [self.m_root computeGlobalTransforms]. ``` I'd suggest you refer to [Methods and Messaging](https://developer.apple.com/library/mac/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/) in *Learning Objective-C: A Primer.* --- If `computeGlobalTransforms` is a `VA_Bone` method, the syntax would be: ``` VA_Bone *bone = [[VA_Bone alloc] init]; [bone computeGlobalTransforms]; ``` Your `bone` variable is a simple local variable, thus no reference to `self.m_root` is needed. --- By the way, as a matter of convention, the underscores in the middle of variable and class names is generally not used. See [Naming Properties and Data Types](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html) in the *Coding Guidelines for Cocoa.* Also see references to "camel case" in the [Conventions](http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/Conventions/Conventions.html) of *Programming with Objective-C.* Thus, a more common naming convention would be `VABone` for your class. Likewise for your original `m_root` property that you alluded to, you'd (a) give it a more descriptive name; and (b) use camel case. Now I don't know what the "m" of `m_root` is supposed to stand for (which, alone, illustrates the problem), but let's say it it was for medium sized images, then it might be `mediumSizedImagesRoot`, or whatever.
No you can't, you can only use Dot.Notation for setters and getters for your properties.
15,093,973
I have a Java program I am converting into objective-c. In Java I uses dot notation and for for example have the following line of code: ``` this.m_root.computeGlobalTransforms(); ``` Which calls a method called computeGlobalTransforms(). Am I able to use dot notation like this in objective-c or will I need to write the line as and pass 'm\_root' as an object: ``` [self computeGlobalTransforms:m_root]; ```
2013/02/26
[ "https://Stackoverflow.com/questions/15093973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1245216/" ]
You *can* use dot notation to call zero parameter methods. You absolutely shouldn't. Dot notation is handled by the compiler, rather than the run time - there's a very good answer to a similar question that talks about why it works, and why you shouldn't use it (...for anything other than setters/getters) here: [Objective-C dot notation with class methods?](https://stackoverflow.com/questions/2375943/objective-c-2-0-dot-notation-class-methods)
No you can't, you can only use Dot.Notation for setters and getters for your properties.
15,093,973
I have a Java program I am converting into objective-c. In Java I uses dot notation and for for example have the following line of code: ``` this.m_root.computeGlobalTransforms(); ``` Which calls a method called computeGlobalTransforms(). Am I able to use dot notation like this in objective-c or will I need to write the line as and pass 'm\_root' as an object: ``` [self computeGlobalTransforms:m_root]; ```
2013/02/26
[ "https://Stackoverflow.com/questions/15093973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1245216/" ]
If `computeGlobalTransforms` is an instance method of the class `m_root` object, and if `m_root` is a class property of `self`, then the syntax is: ``` [self.m_root computeGlobalTransforms]. ``` I'd suggest you refer to [Methods and Messaging](https://developer.apple.com/library/mac/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/) in *Learning Objective-C: A Primer.* --- If `computeGlobalTransforms` is a `VA_Bone` method, the syntax would be: ``` VA_Bone *bone = [[VA_Bone alloc] init]; [bone computeGlobalTransforms]; ``` Your `bone` variable is a simple local variable, thus no reference to `self.m_root` is needed. --- By the way, as a matter of convention, the underscores in the middle of variable and class names is generally not used. See [Naming Properties and Data Types](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html) in the *Coding Guidelines for Cocoa.* Also see references to "camel case" in the [Conventions](http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/Conventions/Conventions.html) of *Programming with Objective-C.* Thus, a more common naming convention would be `VABone` for your class. Likewise for your original `m_root` property that you alluded to, you'd (a) give it a more descriptive name; and (b) use camel case. Now I don't know what the "m" of `m_root` is supposed to stand for (which, alone, illustrates the problem), but let's say it it was for medium sized images, then it might be `mediumSizedImagesRoot`, or whatever.
You *can* use dot notation to call zero parameter methods. You absolutely shouldn't. Dot notation is handled by the compiler, rather than the run time - there's a very good answer to a similar question that talks about why it works, and why you shouldn't use it (...for anything other than setters/getters) here: [Objective-C dot notation with class methods?](https://stackoverflow.com/questions/2375943/objective-c-2-0-dot-notation-class-methods)
69,280,948
I am running a simple Java application as follows: ``` class MyApp { public static void main(String[] args) { // Do stuff } } ``` Now I want to get the process ID (PID) of this application from inside my `main()` function so that I can save it to a file. How can I do that in a platform-independent way? --- EDIT: The existing solutions on Stackoverflow are many years old and probably better solutions exist today. This is why I'm asking this question. --- EDIT 2: I would prefer solutions that do NOT require Java 9.
2021/09/22
[ "https://Stackoverflow.com/questions/69280948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11786586/" ]
My operating environment is jdk6 ``` import java.lang.management.ManagementFactory; public static void main(String[] args) { String name = ManagementFactory.getRuntimeMXBean().getName(); System.out.print(name.split("@")[0]); } ```
Use RuntimeMXBean ``` RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); long pid = runtime.getPid(); ```
69,280,948
I am running a simple Java application as follows: ``` class MyApp { public static void main(String[] args) { // Do stuff } } ``` Now I want to get the process ID (PID) of this application from inside my `main()` function so that I can save it to a file. How can I do that in a platform-independent way? --- EDIT: The existing solutions on Stackoverflow are many years old and probably better solutions exist today. This is why I'm asking this question. --- EDIT 2: I would prefer solutions that do NOT require Java 9.
2021/09/22
[ "https://Stackoverflow.com/questions/69280948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11786586/" ]
Use RuntimeMXBean ``` RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); long pid = runtime.getPid(); ```
You can get PID by following ``` ManagementFactory.getRuntimeMXBean().getSystemProperties().get("PID") ``` Or ``` System.getProperty("PID"); ``` [![enter image description here](https://i.stack.imgur.com/LR5zV.png)](https://i.stack.imgur.com/LR5zV.png)
69,280,948
I am running a simple Java application as follows: ``` class MyApp { public static void main(String[] args) { // Do stuff } } ``` Now I want to get the process ID (PID) of this application from inside my `main()` function so that I can save it to a file. How can I do that in a platform-independent way? --- EDIT: The existing solutions on Stackoverflow are many years old and probably better solutions exist today. This is why I'm asking this question. --- EDIT 2: I would prefer solutions that do NOT require Java 9.
2021/09/22
[ "https://Stackoverflow.com/questions/69280948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11786586/" ]
My operating environment is jdk6 ``` import java.lang.management.ManagementFactory; public static void main(String[] args) { String name = ManagementFactory.getRuntimeMXBean().getName(); System.out.print(name.split("@")[0]); } ```
You can get PID by following ``` ManagementFactory.getRuntimeMXBean().getSystemProperties().get("PID") ``` Or ``` System.getProperty("PID"); ``` [![enter image description here](https://i.stack.imgur.com/LR5zV.png)](https://i.stack.imgur.com/LR5zV.png)