source
sequence
text
stringlengths
99
98.5k
[ "math.stackexchange", "0000478136.txt" ]
Q: Pulling out the limit inside another limit In proving the second order derivative formula $$\lim_{h\rightarrow 0}\frac{f(a+h)-2f(a)+f(a-h)}{h^2}=f''(a)$$for a function $f$ of class $C^2$, we can approach by using the definition of derivative: \begin{align}f''(x) &= \lim_{h\rightarrow 0}\dfrac{f'(x)-f'(x-h)}{h} \\ &= \lim_{h\rightarrow 0}\dfrac{\lim_{t\rightarrow 0}\dfrac{f(x+t)-f(x)}{t}-\lim_{t\rightarrow 0}\dfrac{f(x)-f(x-t)}{t}}{h} \\&= \lim_{h\rightarrow 0}\dfrac{\lim_{t\rightarrow 0}\dfrac{f(x+t)-2f(x)+f(x-t)}{t}}{h}\end{align} If we can somehow "take $t=h$", we get the desired formula. But why can we do it? A: You can prove it using l'Hopital rule: $$\lim_{h\rightarrow 0}\frac{f(a+h)-f(a)-f(a)+f(a-h)}{h^2}=\lim_{h\rightarrow 0}\frac{f'(a+h)-f'(a-h)}{2h}$$ $$=\lim_{h\rightarrow 0}\frac{f'(a+h)-f(a)+f(a)-f'(a-h)}{2h}=\lim_{h\rightarrow 0}\frac{f'(a+h)-f'(a)+f'(a)-f'(a-h)}{2h}$$ $$=\lim_{h\rightarrow 0}\frac{f'(a+h)-f'(a)}{2h}+\lim_{h\rightarrow 0}\frac{f'(a)-f'(a-h)}{2h}$$ $$=\frac{1}{2}f''(a)+\lim_{h\rightarrow 0}\frac{f'(a-h)-f'(a)}{-2h}$$ $$=\frac{1}{2}f''(a)+\frac{1}{2}f''(a)$$ $$=f''(a)$$
[ "stackoverflow", "0023025787.txt" ]
Q: ngrepeat doesn't work properly, returned blank my plunker : http://plnkr.co/edit/5bRMwOJhwW8RQCfnfkK6?p=preview in main.html line 35 I declared <li ng-repeat="friend in tabFriends"> {{friend[0].name}} </li> to try to echo out friends' name but it returned blank. The data is in data.js. The todo list item work well, I wonder why. A: The problem lies in the value your passing to your taskform directive. You are only passing tab.tasks where as tab.tabFriends is a different array of objects. You really need to reconstruct how you directive is made. You are assigning $scope.tabs inside your directive where there is no guarantee that where it will be used will have that value. You should divide your directive in to a controller: function() and a linker: function() the latter being for the initialization of the directive. If you want to find a really awesome example of directives with controllers and linker functions look in the angularjs javascript itself for the ng-model directive. It will give you a really good idea how it should be structured!
[ "stackoverflow", "0009159121.txt" ]
Q: Logging POST data in NGINX and avoiding unnecessary parameters I want to log POST data in NGINX and am using $request_body to do the same. But there are POST fields that I don't want to log (like password, email etc). Is it possible to parse the post data OR asynchronously send data to a PHP/RUBY or any other script so that i can parse the POST data there ? A: I achieved this by using Nginx LUA module. and then by calling ngx.req.get_post_args() in the lua script, i was able to get the post content in the form of a table (LUA's arrays). Hence parsing this in lua itself removing unnecessary parameters and logging it solved this issue.
[ "stackoverflow", "0026936476.txt" ]
Q: MySQL flags for an image I have got a column of images in my MySQL database, but I would like to know what column flag I should use? (PK, NN, UQ, BIN, UN, ZF, AI) Or do they even matter? Edit: maybe I should mention that it's a blob datatype Thanks.. A: First: Understand what each flag means: PK: Primary key: Meant for primary keys (obviously, a BLOB can't be a PK) NN: Not nullable: Is the field mandatory? If it is, use this flag UQ: Unique: Forces a unique index on the column (again, not a good idea on a BLOB) BIN: Binary: Stores strings as binary strings (not necesary for BLOB) UN: Unsigned: Only non-negative numbers (could a BLOB be positive or negative?) ZF: Zero-fill: Left-pad number values with zeros (do I really need to say anything related to BLOBs regarding this?) AI: Auto-incremental (Do I really need to explain this?)
[ "stackoverflow", "0008828603.txt" ]
Q: php mass variables from sql query I have this section of my PHP script that loops through a recordset and stores the data into variables. $sql_result5 = mysql_query("SELECT * FROM turfs WHERE city = '$city'", $db); $query++; while ($rs5 = mysql_fetch_array($sql_result5)) { if ($rs5[plot] != "") { ${$rs5[plot].'_exist'} = 1; ${'$p_color_'.$rs5[plot]} = $rs5[color]; ${$rs5[plot].'_1'} = $rs5[color1]; } } I then use this data to populate a 20x20 grid, so that loop would be going through 400 records storing data for each, and for each record (box in the grid) there needs to be about 5 or so variables. Is it a bad idea creating so many variables? Is there a better way to do this? Maybe an array? A: Creating variables, as you've done, isn't the best way to do this. Instead, either use an array, or create the grid within the while loop. Create an Array $sql_result5 = mysql_query("SELECT * FROM turfs WHERE city = '$city'", $db); $query++; while($rs5 = mysql_fetch_array($sql_result5)){ if($rs5[plot]){ $plot[$rs5[plot]] = array( 'color' => $rs5[color], 'color1' => $rs5[color1], ); } } Then... foreach($plot as $this_plot){ $color = $this_plot['color']; $color1 = $this_plot['color1']; // Do something here } Or, Create Grid Within while $sql_result5 = mysql_query("SELECT * FROM turfs WHERE city = '$city'", $db); $query++; while($rs5 = mysql_fetch_array($sql_result5)){ if($rs5[plot]){ $color = $rs5['color']; $color1 = $rs5['color1']; // Do something here } }
[ "boardgames.stackexchange", "0000045419.txt" ]
Q: Which discard pile for instant items played on another player's lane? In XenoShyft Onslaught, in which discard pile goes an Instant Card when played in another player's lane? For example, if I use a "Hi-Ex Grenade" in the reaction phase of another player, do I discard that grenade in my or his/her discard pile? For references, the rulebook only mentions what happens for troops and equipment played in another player's lane. Nothing about Instant Items: Note that you can deploy a Troop in a lane that is not your own. If you do so, the owner of that lane becomes the owner of that Troop (it goes to their discard pile if killed). A player may also at this time equip Troops with the various Equipment Cards they has purchased. To do so simply place the Equipment Card under the Troop you wish to equip it to. It is now equipped to that Troop. A Troop can only have one Weapon Card and one Armor Card equipped at any time. Just like with deploying Troops, you may also Equip Troops that you do not own. If you do so, the owner of that lane becomes the owner of that Equipment card (it goes to their discard pile if the equipped Troop is killed). The "Hi-Ex Grenade" has the "Instant Keyword": A: I found the answer in the official FAQ (not included in the box published by EDGE) published on CMON website (game creator) : https://cmon.com/product/xenoshyft/xenoshyft-onslaught Q: If I play an Instant on another player’s lane (such as a Med Pack or Hi-Ex Grenade), does that card go to their discard pile? A: No, it goes to its owner’s discard pile. The only time a card goes to another player is if it is deployed into their lane. Keeping Instant Cards played on someone else's lane in one's own discard pile allows us to better "build" around Division Cards abilities (such as "Whenever you play a [Symbol] card, heal 1 troop up to 2").
[ "stackoverflow", "0042358752.txt" ]
Q: How can I restrict null values from being stored in my array? Unfortunately, my instructor won't let me to use Lists for this assignment. I want to restrict null values from being stored in my array. I tried to use an if statement but it's not working. public static void main(String[] args) { System.out.println(messages(3, 10)); } public static String message(int n) { String message = null; if ((n % 3 != 0) && (n % 5 != 0)){ message = null; } else if((n % 3 == 0) && (n % 5 == 0)) { message = n + ": FizzBuzz"; } else if (n % 3 == 0) { message = n + ": Fizz"; } else if (n % 5 == 0) { message = n + ": Buzz"; } return message; } public static String[] messages(int start, int end) throws IllegalArgumentException { if (end < start) { throw new IllegalArgumentException(); } else { String[] msgArray = new String[end - start]; int j = 0; for(int i = start; i < end; i++) { String theMsg = message(i); /* Where I need help */ // I'm trying to use the if statement to restrict //all null values from being stored in my msgArray */ if(theMsg != null) { msgArray[j] = theMsg; } j++; } System.out.println(); for(String s: msgArray) { System.out.println(s); } return msgArray; } } Desired Output 3: Fizz 5: Buzz 6: Fizz 9: Fizz Actual Output 3: Fizz null 5: Buzz 6: Fizz null null 9: Fizz A: If you create a an array, you specify a size. The array then get created and populated with a default values. In this case, that's null for Strings (it's 0 for int[]s). There isn't a way around this. You have to specify the correct length from the creation of the array and this length does not change. So you have two options: Somehow calculate the number of actual, non-null values before creating your array, then create an array with that size instead of your current calculation. This involves a lot of change in your logic so, I would recommending just creating a new array from your current array and check to see if a value is null before you put it in. See below: // inside your function // instead of returning msgArray, create a new array and modify it. // get the count of values that aren't null int nonNull = 0; for (int index = 0; index < msgArray.length; index++) { if (msgArray[index] != null) nonNull++; } // create the new array because you can't change the size of your other array String[] newMsgArray = new String[nonNull]; // populate the array int newIndex = 0; for (int index = 0; index < msgArray.length; index++) { if (msgArray[index] != null) { newMsgArray[newIndex] = msgArray[index]; newIndex++; } } return newMsgArray;
[ "math.stackexchange", "0001821807.txt" ]
Q: Does this transformation and reparametrization preserve non-analyticity of smooth functions A $C^{\infty}$ function $f : \mathbb{R} \to \mathbb{R}_+$ is non-analytic for some $x_0 \in \mathbb{R}$. Can we conclude that $x\mapsto\log(f(e^x))$ is non-analytic at $x = \log(x_0)$? A: Assume that $f(y)>0$ in some neighborhood of $y_0\in{\mathbb R}$. If the function $g:=\log \circ f\circ \exp$ is analytic at $x_0:=\log y_0$ then $f=\exp\circ g\circ\log$ is analytic at $y_0$.
[ "stackoverflow", "0021659068.txt" ]
Q: How to put confimation box in extjs In my UI, I have 3 buttons which are 'add','save' and 'cancel' and an Editor Grid Panel. Now if the user add or edit a record and try to save but accidentally clicked the cancel button, automatically all the records that supposed to be change and saved will remain the same. My problem is that how can I put a confirmation box at the cancel button that it will only show if there are changes made in the records? This is what I've tried so far: var grid = new Ext.grid.EditorGridPanel({ id: 'maingrid', store: store, cm: cm, width: 785.5, anchor: '100%', height: 700, frame: true, loadMask: true, waitMsg: 'Loading...', clicksToEdit: 2, tbar: [ '->', { text: 'Add', iconCls: 'add', id: 'b_add', disabled: true, handler : function(){ var Put = grid.getStore().recordType; var p = new Put({ action_take: 'add', is_active: '', allowBlank: false }); Ext.getCmp('b_save').enable(); Ext.getCmp('b_cancel').enable(); grid.stopEditing(); store.insert(0, p); grid.startEditing(0, 1); } },'-',{ text: 'Save', iconCls: 'save', id: 'b_save', disabled: true, handler : function(){ var objectStore = Ext.getCmp("maingrid").getStore(); var objectModified = objectStore.getModifiedRecords(); // console.log(objectModified); var customer_id = Ext.getCmp("maingrid").getStore().baseParams['customer_id']; var objectData = new Array(); var dont_include; if(objectModified.length > 0) { for(var i = 0; i < objectModified.length; i++) { dont_include = false; //all fields are null, then prompt that it should be filled-in (for edit) if(objectModified[i].data.id && ( (objectModified[i].data.firstname == undefined || objectModified[i].data.firstname == null|| objectModified[i].data.firstname == '') || (objectModified[i].data.lastname == undefined || objectModified[i].data.lastname == null|| objectModified[i].data.lastname == '') || (objectModified[i].data.email_address == undefined || objectModified[i].data.email_address == null|| objectModified[i].data.email_address == '') ) ) { Ext.Msg.show({ title: 'Warning', msg: "Input value required.", icon: Ext.Msg.WARNING, buttons: Ext.Msg.OK }); return; } else//no id, means new record { //all fields are not filled-in, just do nothing if((objectModified[i].data.firstname == undefined || objectModified[i].data.firstname == null|| objectModified[i].data.firstname == '')&& (objectModified[i].data.lastname == undefined || objectModified[i].data.lastname == null|| objectModified[i].data.lastname == '')&& (objectModified[i].data.email_address == undefined || objectModified[i].data.email_address == null|| objectModified[i].data.email_address == '')) { //boolean flag to determine whether to include this in submission dont_include = true; } //either one field is not filled-in prompt to fill in all fields else if((objectModified[i].data.firstname == undefined || objectModified[i].data.firstname == null|| objectModified[i].data.firstname == '')|| (objectModified[i].data.lastname == undefined || objectModified[i].data.lastname == null|| objectModified[i].data.lastname == '')|| (objectModified[i].data.email_address == undefined || objectModified[i].data.email_address == null|| objectModified[i].data.email_address == '')) { Ext.Msg.show({ title: 'Warning', msg: "Input value required.", icon: Ext.Msg.WARNING, buttons: Ext.Msg.OK }); return; } } //the data for submission if(!dont_include) { objectData.push({ firstname: objectModified[i].data.firstname, lastname: objectModified[i].data.lastname, email_address: objectModified[i].data.email_address, id: objectModified[i].data.id, customer_id: customer_id }); } } // console.log(objectData) // return; //check if data to submit is not empty if(objectData.length < 1)//empty { Ext.Msg.show({ title: 'Warning', msg: "No record to save", icon: Ext.Msg.WARNING, buttons: Ext.Msg.OK }); Ext.getCmp('maingrid').getStore().reload(); return; } // return; Ext.Msg.wait('Saving Records...'); Ext.Ajax.request({ timeout:900000, params: {objdata: Ext.encode(objectData)}, url: '/index.php/saveContent', success: function(resp){ var response = Ext.decode(resp.responseText); Ext.Msg.hide(); if(response.success == true){ Ext.Msg.show({ title: "Information", msg: response.msg, buttons: Ext.Msg.OK, icon: Ext.Msg.INFO, fn: function(btn){ Ext.getCmp('maingrid').getStore().reload(); Ext.getCmp('b_save').disable(); Ext.getCmp('b_cancel').disable(); } }); }else{ Ext.Msg.show({ title: "Warning", msg: response.msg, buttons: Ext.Msg.OK, icon: Ext.Msg.WARNING }); } }, failure: function(resp){ Ext.Msg.hide(); Ext.Msg.show({ title: "Warning1", msg: response.msg, buttons: Ext.Msg.OK, icon: Ext.Msg.WARNING }); } }); } else{ Ext.Msg.show({ title: 'Warning', msg: "No changes made.", icon: Ext.Msg.WARNING, buttons: Ext.Msg.OK }); } } },'-', { text: 'Cancel', iconCls: 'cancel', id: 'b_cancel', disabled: true, handler : function(){ Ext.getCmp('maingrid').getStore().reload(); Ext.getCmp('b_save').disable(); Ext.getCmp('b_cancel').disable(); } } ], bbar: pager }); A: You can use Ext.data.Store getModifiedRecords() and getRemovedRecords() methods to detect if grid store contains changes. For displaying confirmation dialog you can use Ext.MessageBox.confirm() method and then reload store only if user click on "yes" button. var store = Ext.getCmp('maingrid').getStore(); var modified = store.getModifiedRecords(); var removed = store.getRemovedRecords(); if (modified.length || removed.length) { Ext.MessageBox.confirm('Cancel', 'Do you want cancel changes?', function(btnId) { if (btnId == 'yes') { store.reload(); Ext.getCmp('b_save').disable(); Ext.getCmp('b_cancel').disable(); } }); }
[ "stackoverflow", "0018052934.txt" ]
Q: How to determine the right number if "(" and ")" for a boolean IF statement? Is this correct? Should it be made more simple somehow? Should there be more "(" and ")" on it, is this a safe 'if' statement for all situations? if (empty($depart_raw) || empty($arrival_raw)) { return ""; } I ask because I get confused with how to know how many "(" and ")" to surround these kind of statements. To be clear, the above is attempting to check to see if either of the two variables are empty then to return a blank for the function. A: The if statement requires one set of parentheses: if (...) Whether any ... expression within that requires parentheses or not depends on what the expression is. empty is a function language construct which requires its own set of parentheses as part of the function call: empty($a) Two expressions joined by an operator do not require parentheses; this is just fine: $a || $b empty($a) || empty($b) If you have multiple operators, you may need to influence their precedence grouping using parentheses, just like in math: (1 + 2) * 3 1 + (2 * 3) ($a || $b) && $c $a || ($b && $c) Adjust as needed.
[ "electronics.stackexchange", "0000197339.txt" ]
Q: Is there a way to build a 2k*12 RAM using only 2 4k*4 Chips Okay so I know when I need to build a parallel design I can put them near each other and make a 4k*8 to expand the databus. But on this one I only need to use half of them and the databus length is larger than my total chips can reach. But I thought 2k*12 requires 24k b of data and i have 32k of space to store data. So there has to be a way to do so. When I use a parallel design I can reach 4k*8 but it is not enough. A: The only way to increase the apparent width of a physical memory is to wrap it in a sequential circuit that executes multiple cycles internally for each external read or write cycle. This requires a means of multiplexing the data during write cycles and demultiplexing it during read cycles. For example, you could turn your 4k × 8 physical memory into a 2k × 16 virtual memory by storing each 16-bit word in two consecutive 8-bit locations in the physical memory. The physical memory would execute two read or write cycles internally for each external cycle.
[ "stackoverflow", "0012378281.txt" ]
Q: Centering images within 300 px by 300 px table grid My code is below and I'm looking for the best way via CSS to center an image (horizontally and vertically) in a 300 by 300 pixel square. Larger images will be fit down to that size and smaller images should be centered, not stretched. <table width="100%"> <tr> <td><div class="300box"><img class="centeredimage" /></div></td> <td><div class="300box"><img class="centeredimage" /></div></td> <td><div class="300box"><img class="centeredimage" /></div></td> </tr> </table> css: .300box { height: 300px; width: 300px; } .centeredimage { vertical-align: middle; text-align: center; } I know the above is incorrect so I'm hoping to find a more efficient way to do it. Each table row has 3 300x300 pixel divs with images centered within. A: Using a div inside a td is not worse than any other way of using tables. You can try this-- CSS: .blocks.table td { width: 300px; height: 300px; border: 1px solid #ff0000; vertical-align: middle; text-align: center; } p.centeredimage img { max-height: 300px; max-width: 300px; } HTML: <table width="100%" class="table blocks"> <tr> <td> <p class="centeredimage" ><img src = "http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/185106_431273290248855_254736287_n.jpg" /></p> </td> <td> <p class="centeredimage" ><img src = "http://a6.sphotos.ak.fbcdn.net/hphotos-ak-ash4/304640_10151181184992355_456123210_n.jpg" /></p> </td> <td> <p class="centeredimage" ><img src = "http://sphotos-b.ak.fbcdn.net/hphotos-ak-snc7/s480x480/422953_410146439043183_1035950087_n.jpg" /></p> </td> <td> <p class="centeredimage" ><img src = "http://sphotos-e.ak.fbcdn.net/hphotos-ak-ash3/s480x480/561574_467101546644877_728463753_n.jpg" /></p> </td> </tr> </table>
[ "superuser", "0000132561.txt" ]
Q: How to measure network traffic by protocol? I would like to select a type of traffic, as I do in Wireshark, and measure the total traffic in each way for this filter. Is it possible with Wireshark? Is it possible with another Windows tool? A: Seems like you found your answer but I just wanted to mention for anyone else reading this question, ntop is an excellent tool for this. Apparently it can be installed under windows.
[ "stackoverflow", "0036204393.txt" ]
Q: Realtime Overview Analytics only showing one user at a time When viewing the RealTime Overview section, I notice that when a new user comes online the previous user immediately disappears and is no longer shown in realTime. The next day analytics only shows history data for one visiting user, I know for a fact that this is incorrect, there should be data for multiple users. I send up analytics data with a simple https request(shown below) . This works for all my other applications. The only difference is that I send up the uid for this app , could this be causing the issue that I am seeing ? Views https://www.google-analytics.com/collect ?v=1 &z=14807 &tid=<OUR-UA-ID> &cid=2535285330542042 &dp=message_6 &dt=message_6 &cd=message_6 &an=freemium_3 &av=3 &uid=123456789 &t=screenview Events https://www.google-analytics.com/collect ?v=1 &z=52130 &tid=<OUR-UA-ID> &cid=2535285331158735 &dp=authentication &dt=authentication &cd=authentication &an=freemium_3 &av=3 &uid=123456789 &ec=authentication &ea=get_user_info &t=event A: The "cid" in your http call is the client id, where client refers to the device or program that makes the request. It is usually stored in a cookie (on the web) or generated by an SDK (in an app) and is used to unify subsequent requests from the same device into sessions. Since it is set by the client it differs from device to device (and browser to browser), so it can not be used to identify a person across multiple devices. After it became the rule that any given person might have two or more devices Google came up with the uid, the user id (which by their own TOS might not identify the user, so this is a bit of a misnomer; think "cross device tracking id" and the concept becomes clearer). The uid is set by serverside code, i.e. after the user logs in. Not only this allows to unify visits from multiple devices into distinct users, it also alleviates privacy concerns (since it is supposed to be only created after a users action; there are separate TOS which you have to accept if you create a user id view in the GA interface, and they stipulate that you have to secure the users agreement to use to user id feature). So if you set the same user id in your code the sessions will be attributed to the same user, even when the cid differs; this is by design and is indeed the point of the uid.
[ "ru.stackoverflow", "0000198365.txt" ]
Q: Просмотр дополнительной информации на jQuery Всем доброго времени суток :) Возник очень геморный вопросик, поэтому просьба слабонервных и товарищей которые любят ставить дизлайки, дальше не читать ^^. И так, если Вы не не нашли себя в выше перечисленном списке, тогда вопросик к вам. Имеется: 16-летний балбес (Тобишь я) Желание воплотить игрушку детства (Покемошки ^^) Сам вопрос: У этих товарищей, покемонов, имеется такие характеристики как: Статы (HP, Атака, Скорость и т.п.) Атаки (То, чем они друг друга греют ^^) Информация (Пол, Хозяин и т.п.) Задача: Есть такой html код: <center class='errorMess'>#999 Pokemon</center> <table> <tr> <td> <span id='pokeTitle'><img src='/style/pok/norm/.jpg' width='250' height='190' border='1'></span> <table border=0 cellspacing=0 width=252 height=10> <tr> <td style='padding:0'> <div style='width:2%;background:green;height:15px;font-size:9pt;color:black;'>0</div> </td> </tr> <tr> <td style='padding:0'> <div style='width:2%;background:blue;height:6px;font-size:0pt;'>0</div> </td> </tr> </table> <div class='itemUse'> <a href='0' id='dropItemFromPok'><img src=/style/items/.gif width=32 height=32 alt='' title='' border='0'></a> </div> </td> <td> <div style='text-align:center; font:11px Tahoma; color: #1D4141;'> <a href='#' id='clickInfoPok1-1'>инфо</a> - <a href='#' id='clickInfoPok2-1'>статы</a> - <a href='#' id='clickInfoPok3-1'>атаки</a> </div> <div style='height:200;'> <div id='infoPok1-1'> <center><b>Информация</b></center> <img src='/style/another/0.gif' width='7' height='13' border='0'><b></b><BR> <b>Тип:</b> <BR> <b>Характер:</b> <BR> <p><a href='2' id='makeStart'>Сделать стартовым</a></p> </div> <div id='infoPok2-1'> <center><b>Статы</b></center> <table> <td><td><i>Стат</i></td> <td><i>Ген</i></td> <td><i>EV</i></td></tr> <tr><td>НР:</td> <td>0</td> <td width='30'>0</td> <td>0</td></tr> <tr><td>Атака:</td> <td>0</td> <td>0</td> <td>0</td></tr> <tr><td>Защита:</td> <td>0</td> <td>0</td> <td>0</td></tr> <tr><td>Скорость:</td> <td>0</td> <td>0</td> <td>0</td></tr> <tr><td>Спец. Атака:</td> <td>0</td> <td>0</td> <td>0</td></tr> <tr><td>Спец. Защита:</td> <td>0</td> <td>0</td> <td>0</td></tr> <tr><td><b>&nbsp;EV: 0</b></td> <td></td> <td></td></tr> </table> </div> <div id='infoPok3-1'> <center><b>Атаки</b></center> <table> <tr><td>0</td> <td>0</td></tr> <tr><td>0</td> <td>0</td></tr> </table> <p><center><a href='#' id='teachAtk'>Начать тренировку</a></center></p> </div> </div> </td> </tr> </table> ` А также, есть код на jQuery: var i=1; while(i <= 6){ $('#infoPok1-'+i).hide(); $('#infoPok3-'+i).hide(); $('#clickInfoPok1-'+i).click(function(){ $('#infoPok1-'+i).fadeIn(700); $('#infoPok2-'+i).hide(); $('#infoPok3-'+i).hide(); }); $('#clickInfoPok2-'+i).click(function(){ $('#infoPok1-'+i).hide(); $('#infoPok2-'+i).fadeIn(700); $('#infoPok3-'+i).hide(); }); $('#clickInfoPok3-'+i).click(function(){ $('#infoPok1-'+i).hide(); $('#infoPok2-'+i).hide(); $('#infoPok3-'+i).fadeIn(700); }); i++; } Вот, суть вопроса состоит в том, чтобы можно было листать характеристики покемонов. Объяснения: Такие блоки как: infoPok1-1 infoPok2-1 infoPok3-1 Должны по очереди чередоваться. Например, блок <div id='infoPok1-1'> открытый, но остальные же блоки должны быть закрыты. Наш <div id='infoPok1-1'> отвечает за информацию о покемоне. Но если пользователь захотел узнать какие статы у его питомцы, он нажимает на статы, и блок <div id='infoPok1-1'> закрывается, а блок <div id='infoPok2-1'> открывается. Буду очень благодарен тому кто поможет :) A: По jquery, весь ваш while не нужен сделайте в html <div class="menu" style='text-align:center; font:11px Tahoma; color: #1D4141;'> <a href='#' class='clickinfo' data-target='Info'>инфо</a> - <a href='#' class='clickinfo' data-target='Stats'>статы</a> - <a href='#' class='clickinfo' data-target='Attacks'>атаки</a> </div> и <div style='height:200;' class='info'> <div class='Info'> <center><b>Информация</b> в js $('.info div').hide(); $('.info .Stats').show(); $('body').on('click', '.PockemonContainer .menu > a', function () { var $this = $(this); var target = $this.data('target'); var show = $this.parents('.PockemonContainer').find('.info .' + target); $this.parents('.PockemonContainer').find('.info').children(':visible').not(show).fadeOut(100); show.fadeIn(100); return false; }); демо;
[ "stackoverflow", "0033173816.txt" ]
Q: Finding Possible Words in an Ever Changing Grid I am working on a word game where the user creates words from an ever changing grid of letters. Validating the users selection is easy enough to do using a wordlist. Since the playing grid is randomly generated and previously played tiles are removed and replaced with new letters, I need to be able to effectively check for possible valid plays between each user submission, so if there are no possible valid words I can reset the grid or something to that affect. The solution only needs to detect that there is at least one valid 3 - 7 letter word within the current set of tiles. It does not need to know ever possible combination. A user can start on any tile and build a word using one tile away in any direction from the currently selected letter. Important: The solution can't slow the game play down. As soon as the user submits the current word and the new tiles appear they can start a new selection without delay. Any direction would be greatly appreciated as I have not been able to find what I think I'm looking for with any google searches so far. Building with Swift for iOS8+ A: As @jamesp mentioned, a trie is your best bet. You have a couple of advantages for yourself here, the first one being is that you can bail out the second you have found a word. You don't have to scan the whole grid for all possible words, just find one and be done with it. Start with any random letter and look at the ones around it, and match those up against the trie. If you find a match, continue with the letters around that one and so on until you have found a word or a dead end. If the current start tile doesn't have a full word around it, go on to the next tile in the grid and try from there again.
[ "stackoverflow", "0033987349.txt" ]
Q: iOS - playing video from remote database Is there a best practice for providing video to an iOS app from a database? For example, should the actual video data be provided from the database to the app or should a URL be return and the actual data access via the URL later by the app? A: I believe the best practice would be to store the video file either on your server or some sort of cloud based storage like s3. Store the url in your database or somewhere that you can access in your app. Then use the url to access the file when it's needed in the app. As a side note, you might need to look into HTTP Live streaming depending on how your app will be delivering the video. check this out for more details
[ "math.stackexchange", "0002109535.txt" ]
Q: If $B = A^T$ where $B$ is an $m \times n$ matrix, find the size of $A, AA^2, A^{T}A$ If $B = A^T$ where $B$ is an $m \times n$ matrix, find the size of $A, AA^2, A^{T}A$. We know that since $B = A^T$, and $B = m \times n$ matrix, that means $A$ is $n \times m$ matrix. What about $AA^2$? That is, $A (A \times A) = (n \times m)((n \times m)\times (n \times m))$ For this multiplication to be defined, we must have $n=m$, in order words, square matrix. My question is though, in the back it says the answer is $n \times n$ matrix? Can I also say that it is $m \times m$? Is there more then one correct answer in this case? A: $A^2$ is not defined when it is not a square matrix. The question regarding the size of $A^2$ is meaningful only when $A$ is a square matrix, i.e., it is of the size $n\times n$ for some positive integer $n$. You have said in your question that "For this multiplication to be defined, we must have $n=m$". In this case, there is no difference between $n\times n$ and $m\times m$.
[ "stackoverflow", "0039837066.txt" ]
Q: MySQL transaction, rollback doesn't work, (PHP PDO) I have a loop that inserts data in two tables, in the first iteration of the loop the insert is succesfull, but in the second iteration the insert will fail. I have written the script so that if any of the iterations fail, the entire transaction should be rollbacked. However, this doesn't work. The first iteration (that succeeded) isn't rolled back... <?php include('model/dbcon.model.php'); $languages = array('project_nl', 'project_en'); DBCon::getCon()->beginTransaction(); $rollback = true; foreach($languages as $language) { $Q = DBCon::getCon()->prepare('INSERT INTO `'.$language.'`(`id`, `name`, `description`, `big_image`) VALUES (:id,:name,:description,:big_image)'); $Q->bindValue(':id', '1', PDO::PARAM_INT); $Q->bindValue(':name', 'test', PDO::PARAM_INT); $Q->bindValue(':description', 'test', PDO::PARAM_INT); $Q->bindValue(':big_image', 'test', PDO::PARAM_INT); try { $Q->execute(); } catch (PDOException $e) { $rollback = true; } } if ($rollback) { echo 'rollbacking...'; DBCon::getCon()->rollBack(); } else { echo 'commiting...'; DBCon::getCon()->commit(); } ?> Why isn't the entire transaction rolled back? Thanks in advance. A: Either auto-commit is enabled, or the connection is not persisting, or you're not using innodb. This will work, which means DBCon::getCon() is not doing what you think it's doing. <?php include('model/dbcon.model.php'); $languages = array('project_nl', 'project_en'); $connection = DBCon::getCon(); $connection->beginTransaction(); $rollback = true; foreach($languages as $language) { $Q = $connection->prepare('INSERT INTO `'.$language.'`(`id`, `name`, `description`, `big_image`) VALUES (:id,:name,:description,:big_image)'); $Q->bindValue(':id', '1', PDO::PARAM_INT); $Q->bindValue(':name', 'test', PDO::PARAM_INT); $Q->bindValue(':description', 'test', PDO::PARAM_INT); $Q->bindValue(':big_image', 'test', PDO::PARAM_INT); try { $Q->execute(); } catch (PDOException $e) { $rollback = true; } } if ($rollback) { echo 'rollbacking...'; $connection->rollBack(); } else { echo 'commiting...'; $connection->commit(); } ?>
[ "stackoverflow", "0005675330.txt" ]
Q: cms made simple how to include javascript in my template Hi I'm a bit stuck here, i cant seem to be able to include the javascript file in my cmsms template. <script src="js/slides.min.jquery.js"></script> <script> $(function(){ $('#slides').slides({ preload: true, preloadImage: 'img/loading.gif', play: 5000, pause: 2500, hoverPause: true }); }); </script> This code doesent work, it neither includes the js/slides.min.jquery.js nor does it run the script,, can any one please explain how javascript is included in cmsms templates... A: You need to include the javascript in {literal} tags, to avoid cmsms trying to parse it. This is an example (from one of my sites), that includes the Google analytics javascript. {literal} <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXXX-X']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> {/literal}
[ "stackoverflow", "0055956593.txt" ]
Q: Combine text and a fontawesome icon in facet titles in a ggplot2 chart? Is it possible to insert an icon from fontawesome in a facet title of a ggplot2 chart? I would like to combine an icon with text: Using a new column, that pastes the fontawesome-icon to the label does not. Is there another way to achieve this? library(ggplot2) library(emojifont) mpg %>% mutate(fa_class = paste0(fontawesome('fa-linux'), class)) %>% ggplot(aes(x = year, y = displ)) + geom_point() + facet_wrap(~ fa_class) The icons are not recognized: A: I couldn't find an easy fix using fontawesome() but since you are using emojifont you could use the emoji() function and then change the font family. library(tidyverse) library(emojifont) mpg %>% mutate(fa_class = paste(emoji("car"), class)) %>% ggplot(aes(x = year, y = displ)) + geom_point() + facet_wrap(~ fa_class) + theme(strip.text = element_text(family = "EmojiOne"))
[ "stackoverflow", "0060552618.txt" ]
Q: Create a new dataframe with every 2 columns of a dataframe I am new to Python and I am struggling with this. I want to create a number of new dataframes, each from columns in an existing dataframe. The original has the format of Time, x1, Time2, x2... I've gotten as far as a loop to search for 'Time' for col in df.columns: if 'Time' in col: I'd need to call the column found and the one next to it and assign it to a new dataframe which has the columns of ['Time', 'x1'] then loop through for every pair of Timen & xn. I would like to name the dataframes by xn. thanks for any help. A: If I'm interpreting your question correctly, I think what you want is df.iloc[<row index>, <column index>]. If your dataframe is always formatted as Time1, x1, Time2, x2, ..., TimeN, xN (as in you are always grabbing consecutive columns to make your new dataframe), you can use do something like the following: df_1 = df.iloc[ : , [0,1] ] The : in the <row_index> will select all rows, and the [0,1] in the <column index> is a list of column indexes that you want. You could then loop over the number of columns in your original dataframe to grab each pair: # number of columns in your dataframe number_of_columns = len(df.columns) # store the split dataframes in a list split_dfs = [] # loop over column indexes with step size 2 for i in range(0, number_of_columns, 2): split_dfs.append(df.iloc[:, [i,i+1]])
[ "stackoverflow", "0028448038.txt" ]
Q: List all occurences of a particular string or number in the file : UNIX I have multiple files containing phone numbers in a format XXX XXX XXXX or +XX XXXXXX XXXX or maybe XXXXXXXXXX. Can I list all the phone numbers containing particular no. '845' against each file name. Currently I am using:- egrep -H 845 * A: This might do what you want (uses GNU for word delimiters): $ cat file now is the 123 845 1234 winter of +01 238456 5432 our 1845234567 discontent. $ cat tst.awk { while ( match($0,/(\<(([0-9]{3} ){2}[0-9]{4}|[0-9]{10})|[+][0-9]{2} [0-9]{6} [0-9]{4})\>/) ) { tgt = substr($0,RSTART,RLENGTH) $0 = substr($0,RSTART+RLENGTH) if ( tgt ~ /845/ ) { print tgt } } } $ awk -f tst.awk file 123 845 1234 +01 238456 5432 1845234567 If not, edit your question to provide some sample input and expected output.
[ "stats.stackexchange", "0000384267.txt" ]
Q: Kalman Filter vs. Regression I'm an economics undergraduate with a fundamental understanding of regression and some experience with machine learning models (e.g. regression trees, boosting). To my knowledge, Kalman Filter is superior in that 1. it can converge to a reliable estimate quickly without the entire population data, and 2. as it updating based on the errors of both the prior estimate and the measurement, it is computationally faster than say rerunning an entire regression. My application is intended for the finance industry (e.g. asset prices & returns data). My question is: is Kalman Filter more accurate? I think that as a state-space model, it is able to adapt to time series with irregular intervals. As an online model, it should also be far more performant than say a traditional regression model. I think that it is also more accurate than a traditional ARMA model, but I'm not sure how? Also, I think I have some fundamental misconceptions about the Kalman Filter. From my understanding, it is an algorithm and not a model—what does that mean? K-means is an algorithm that separates data into homogeneous clusters; heterogeneously apart. This answer refers to Kalman Filter as a linear estimator—does that mean that KF is just a way of estimating things, and isn't actually a different way of modelling things? A: Building a state space model involves defining two basic distributions: The transition distribution of the state: $p(X_t|X_{t-1}, \theta)$. The observation distribution, conditional on the state: $p(Y_t|X_t, \theta)$ In the special case where the state space model is linear and Gaussian, the Kalman filter is then a way of deriving the associated sequence of filtering distributions $p(X_t|Y_1, ..., Y_t, \theta)$, for each $t$, recursively. It also produces the likelihood, as a function of the parameters $\theta$, allowing for maximum likelihood estimation of those parameters. So, the state space model is the model, and the Kalman filter is an algorithm which allows for estimation of that model, yes. I'm not sure what you are getting at with the Kalman filter being "superior" to regression, but you can consider the Kalman filter to be a generalization of least squares: there is a state space model that corresponds to running a regression, and the mean of the last filtering distribution is exactly the least squares estimate. If you do that, and you save the necessary information about the state of the filter, then yes you can add one more observation and compute the least squares estimate by running just one more step of Kalman filter, without refitting the whole thing. Of course, if that basic linear regression model is wrong (say, the coefficients should vary over time rather than be fixed), then you can handle a wider class of models with the Kalman filter so, sure, in that sense it is "superior". As for ARMA: every ARMA model is a linear Gaussian state space model, and in fact most software implementations for the estimation of ARMA models begin by casting them to state space form and then use the Kalman filter. If by "more accurate" you mean "better at prediction", then in some sense because the state space class is strictly larger than ARMA, you can fit non-ARMA state space models with the Kalman filter which may provide better forecasts (although that is certainly not guaranteed in practice).
[ "superuser", "0000868119.txt" ]
Q: How to prevent automactically jumping from dedicated card (Nvidia) to integrated card I have a laptop with the graphic card GTX760m and the integrated card HD4600. The things is that when I play games, it always selects the integrated card instead of the nvidia card. I change the settings in the Nvidia control panel to make the game run on the Nvidia card, but everytime I open the game, it automatically switch the settings back to the integrated card. For some games, I can right click on the game icon and select run this with the nvidia card, then the game will use the nvidia card even if the settings are still the integrated card. But for some other games, right click and select the nviddia card doesn't work, it still uses the integrated card. I tried this with the charger on, battery on. And with charger on, battery off. Neither of it works. So doesn't seem to be the battery problem. Any helps? Thanks. A: From this post: From NVIDIA Control Panel 3D Settings->Manage 3D Settings Tab "Global setttings" Preferred Graphics Processor Select : High performance NVIDIA rocessor Alternatively, you could check if you can set the Nvidia card as the preferred graphics card for the game you're using. You could try what is described here: Go to the NVIDIA Control Panel by right clicking on your desk top and clicking on "NVIDIA Control Panel". In the default screen that pops up (it should be "manage 3D settings", and the "Program Settings" tab should be automatically selected), under "1. Select a program to customize:" hit the "Add" button. From here, navigate to the folder where your steam games are located. For me, it is C:\Program Files (x86)\Steam\steamapps\common. Select the folder for the game you want to use your NVIDIA card for, and find the .exe for that game (it's usually right in the main game folder). Select it and hit open. Then, under "2. Select the preferred graphics processor for this program:" open the drop-down menu and select "High-performance NVIDIA processor". Finally, hit apply in the far bottom right corner, and you should be good to go! According to the author of what I've quoted, this should work for any .exe.
[ "stackoverflow", "0003577384.txt" ]
Q: Getting iOS outlets wired in InterfaceBuilder I'm new to developing in iOS and successfully ran through a tutorial on how to create and connect outlets in a Mac OSX Cocoa App. However, when I try to follow the same process for my iPhone app, I keep hitting walls... (Apologies for the lengthy example- please bear with) Project A: In xCode: Create new Mac OSX Cocoa Application Create a new class SimpleViewController : NSObject #import <Cocoa/Cocoa.h> @interface SimpleViewController : NSObject { IBOutlet NSTextField *aField; IBOutlet NSButton *aButton; } @end In Interface Builder: File > Read class files Drag SimpleViewController from my library into the main.nib Ctl-drag from SimpleViewController to view elements to connect my outlets Everything above works great. Now for the same thing in an iPhone app: Project B: In XCode: Create new iPhone OS Window-Based Application Create a new class SimpleViewController : UIViewController #import <UIKit/UIKit.h> @class NSTextField; @class NSButton; @interface EmbedComplexViewController : UIViewController { IBOutlet NSTextField *aField; IBOutlet NSButton *aButton; } @end (Notice my view controller is now an extension of UIViewController, not NSObject. Also, this time I need to use forward class declarations for my outlet classes. Not a problem, but is this necessary?) In Interface Builder: File > Read class files Drag SimpleViewController from my library into the main.nib Ctl-drag from SimpleViewController to view elements - BUT now I can't see any of my declared outlet member variables. Instead, the only outlet option I have is 'view' What more do I need to do to have my declared outlets show up? Thanks- Yarin A: In iOS development, we use UIButton and UITextField and etc, (see the iphone developer documentation). And no, you don't need to forward declare those classes (it made you since they weren't included in UIKit
[ "stackoverflow", "0062928879.txt" ]
Q: time is changing while we use react-datepicker i have selected 12:00 Pm in datepicker and i also console log it .... it shows Thu Jul 09 2020 12:00:00 GMT+0530 (India Standard Time) which is right time. but when i click on save then it sends wrong time (2020-07-09T06:30:00.454Z). It sends 5 and half hour less to the time which user selected. It should send (2020-07-09T012:00:00.454Z)----Expected Behaviour i dont know what is the issue and how to fixx this my code <DatePicker selected={new Date(value)} onChange={(e) => setFieldValue(field.name, e)} className={classes.datePicker} todayButton="Today" {...rest} /> I need to pass exact same time which user has selected . I think this issue occurs due to timezone or utc etc . so please help A: This is a common problem with javascript. I usually write a "fix timezone offset" function ald call this function before I send my code to the backend: export const fixTimezoneOffset = (date: Date) : string => { if(!date) return ""; return new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON(); } And you call it like this: fixTimezoneOffset(my_date) Disclaimer: fixTimezoneOffset returns a string which will automatically be computed into a datetime object in your backend. Call fixTimezoneOffset only once and not multiple times!!
[ "stackoverflow", "0045511804.txt" ]
Q: Zeppelin + Spark: Reading Parquet from S3 throws NoSuchMethodError: com.fasterxml.jackson Using Zeppelin 0.7.2 binaries from the main download, and Spark 2.1.0 w/ Hadoop 2.6, the following paragraph: val df = spark.read.parquet(DATA_URL).filter(FILTER_STRING).na.fill("") Produces the following: java.lang.NoSuchMethodError: com.fasterxml.jackson.module.scala.deser.BigDecimalDeserializer$.handledType()Ljava/lang/Class; at com.fasterxml.jackson.module.scala.deser.NumberDeserializers$.<init>(ScalaNumberDeserializersModule.scala:49) at com.fasterxml.jackson.module.scala.deser.NumberDeserializers$.<clinit>(ScalaNumberDeserializersModule.scala) at com.fasterxml.jackson.module.scala.deser.ScalaNumberDeserializersModule$class.$init$(ScalaNumberDeserializersModule.scala:61) at com.fasterxml.jackson.module.scala.DefaultScalaModule.<init>(DefaultScalaModule.scala:20) at com.fasterxml.jackson.module.scala.DefaultScalaModule$.<init>(DefaultScalaModule.scala:37) at com.fasterxml.jackson.module.scala.DefaultScalaModule$.<clinit>(DefaultScalaModule.scala) at org.apache.spark.rdd.RDDOperationScope$.<init>(RDDOperationScope.scala:82) at org.apache.spark.rdd.RDDOperationScope$.<clinit>(RDDOperationScope.scala) at org.apache.spark.SparkContext.withScope(SparkContext.scala:701) at org.apache.spark.SparkContext.parallelize(SparkContext.scala:715) at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat$.mergeSchemasInParallel(ParquetFileFormat.scala:594) at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat.inferSchema(ParquetFileFormat.scala:235) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$7.apply(DataSource.scala:184) at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$7.apply(DataSource.scala:184) at scala.Option.orElse(Option.scala:289) at org.apache.spark.sql.execution.datasources.DataSource.org$apache$spark$sql$execution$datasources$DataSource$$getOrInferFileFormatSchema(DataSource.scala:183) at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:387) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:152) at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:441) at org.apache.spark.sql.DataFrameReader.parquet(DataFrameReader.scala:425) ... 47 elided This error does not happen in the normal spark-shell, only in Zeppelin. I have attempted the following fixes, which do nothing: Download jackson 2.6.2 jars to the zeppelin lib folder and restart Add jackson 2.9 dependencies from the maven repositories to the interpreter settings Deleting the jackson jars from the zeppelin lib folder Googling is turning up no similar situations. Please don't hesitate to ask for more information, or make suggestions. Thanks! A: I had the same problem. I added com.amazonaws:aws-java-sdk and org.apache.hadoop:hadoop-aws as dependencies for the Spark interpreter. These dependencies bring in their own versions of com.fasterxml.jackson.core:* and conflict with Spark's. You also must exclude com.fasterxml.jackson.core:* from other dependencies, this is an example ${ZEPPELIN_HOME}/conf/interpreter.json Spark interpreter depenency section: "dependencies": [ { "groupArtifactVersion": "com.amazonaws:aws-java-sdk:1.7.4", "local": false, "exclusions": ["com.fasterxml.jackson.core:*"] }, { "groupArtifactVersion": "org.apache.hadoop:hadoop-aws:2.7.1", "local": false, "exclusions": ["com.fasterxml.jackson.core:*"] } ]
[ "stackoverflow", "0055575321.txt" ]
Q: Memory Configuration for 32-bit, 64-bit and PAE enabled OS I am confuse about memory configuration, i have below questions. if 32-bit os maximum virtual address is 4GB, When i have 4 gb of ram for 32-bit os, What about the virtual memory size ? is it required virtual memory or we can directly use physical memory ? In 32-bit os 12 bits are offset because page size=4k i.e 2^12 and 2^20 for page addresses What about 64-bit os, What is offset size ? What is page size ? How it calculated. What is PAE? If enabled how to decide size of PAE, what is maximum and minimum size of extended memory. A: Q.1 Ans:- The 32-bit processor includes a 32-bit register, which can store 2^32 and the 64-bit processor includes a 64-bit register, which can store 2^64. A 64-bit register can theoretically 16 exabytes of memory. For 32-bit os maximum virtual memory is 4GB, it can address only up to 4GB of physical RAM (Without PAE). For the Linux kernel, it works on virtual memory management i.e CPU address, There are many types of addresses For example. bus address, physical address(There are other concepts to access physical memory eg. DMA and IOMMU) The virtual memory size is the maximum virtual size of a single process. For more details of 32-bit and 64-bit processor use link. Q.2 Ans:- For 64-bit OS address space is 16 exabyte RAM. and generally page size is 8K i.e 2^13 (apart from that there is the concept of hugepages and hugetlb). 64-bit currently uses 48-bit physical addresses that allow you to address up to 256 TBytes of main memory. because the page table is also a page itself and consists of page table entries. Since the number of entries in one table is limited and depends on the entry size and page size, so tables are arranged in multiple levels. There are usually 2 or 3 levels, and sometimes even 4 levels. General calculation of 64-bit os:- Number of entries in page table = virtual address space size/page size = 2^(64-13) (if page size is 8K) = 2^51 for maximum page table entries (if you are using whole 64 bits) Page Size == Frame Size. Q.3 Ans:- For PAE, the page table entry expands from 32 to 36 bits. This allows more space for the physical page address, or page frame number(PFN) field, in the page table entry. In the initial implementations of PAE, the page frame number(PFN) field was expanded from 20 to 24 bits. The size of the "byte offset" from the address being translated is still 12 bits, so total physical address size increases from 32 bits to 36 bits (from 20+12 to 24+12). This increased the physical memory that is theoretically addressable by the CPU from 4 GB to 64 GB. Maximum size of PAE is = 64GB (2^36). For PAE in details use link
[ "stackoverflow", "0034981403.txt" ]
Q: BufferedImage not being cleared before each rendering I'm trying to learn how to build a simple game through a tutorial i'm watching. Up to now everything was fine, but when I move the image the previous image doesn't get erased or disposed. I'm not sure exactly whats wrong, or why its happening. I have 3 classes, a main class, player class, and a bufferimageloader class. Main class: import java.awt.Canvas; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.io.IOException; import javax.swing.JFrame; public class Main extends Canvas implements Runnable { private boolean running = false; private Thread thread; private BufferedImage player; private Player p; public void init(){ // load and initiliaze BufferedImageLoader loader = new BufferedImageLoader(); try { player = loader.loadImage("/player_shotgun2.png"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } p = new Player(100, 100, this); } private synchronized void start(){ if(running) return; running = true; thread = new Thread(this); thread.start(); } private synchronized void stop(){ if(!running) return; running = false; try { thread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(1); } public void run() { init(); long lastTime = System.nanoTime(); final double amountOfTicks = 60.0; double ns = 1000000000 / amountOfTicks;// 1 second divided by 60, run 60 times per second double delta = 0; int updates = 0; int frames = 0; long timer = System.currentTimeMillis(); System.out.println("hi"); while(running){ long now = System.nanoTime(); delta += (now - lastTime) / ns; lastTime = now; if(delta >= 1){// delta = 1 = 1 second tick(); updates++; delta--; } render(); frames++; if(System.currentTimeMillis() - timer > 1000){ timer+= 1000; System.out.println(updates + " Ticks, Fps " + frames); updates = 0; frames = 0; } } stop(); } // Everything thats is updated in the game private void tick(){ p.tick(); } // Everything that is rendered in the game private void render(){ BufferStrategy bs = this.getBufferStrategy(); if(bs == null){ createBufferStrategy(3); return; } Graphics g = bs.getDrawGraphics(); ////////////////////////////// p.render(g); ////////////////////////////// g.dispose(); bs.show(); } public static void main(String[] args) { // TODO Auto-generated method stub Main main = new Main(); JFrame window = new JFrame(); window.setSize(500,600); window.setTitle("Zombie Game"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); window.add(main); main.start(); } public BufferedImage getPlayerImage(){ return player; } } Player class: import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JPanel; public class Player extends JPanel { private double x; private double y; public BufferedImage player; public Player(double x, double y, Main main){ this.x = x; this.y = y; player = main.getPlayerImage(); } public void tick(){ x++; } public void render(Graphics g){ super.paintComponent(g); g.drawImage(player, (int)x, (int)y, null); g.dispose(); } } Bufferedimageloader class: import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; public class BufferedImageLoader { private BufferedImage image; public BufferedImage loadImage(String path) throws IOException{ image = ImageIO.read(getClass().getResource(path)); return image; } } This is the output I get when I start up and the image moves: A: This is a simple Swing application called Moving Eyes. The eyeballs in the GUI follow the mouse cursor as you move the cursor in the drawing area of the GUI. I realize that it's not doing what you want to do. I'm providing this code so you can see how to do a simple Swing animation. You may use this code as a basis to do your own animation. Here's the Swing GUI. I used the model / view / controller model when creating this Swing GUI. This means that: The view may read values from the model. The view may not update the model. The controller will update the model. The controller will repaint / revalidate the view. Basically, the model is ignorant of the view and controller. This allows you to change the view and controller from Swing to a web site, or an Android app. The model / view / controller pattern allows you to focus on one part of the Swing GUI at a time. In general, you’ll create the model first, then the view, and finally the controllers. You will have to go back and add fields to the model. And here's the code: package com.ggl.testing; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class MovingEyes implements Runnable { private static final int drawingWidth = 400; private static final int drawingHeight = 400; private static final int eyeballHeight = 150; private static final int eyeballWidthMargin = 125; private DrawingPanel drawingPanel; private Eye[] eyes; private JFrame frame; public static void main(String[] args) { SwingUtilities.invokeLater(new MovingEyes()); } public MovingEyes() { this.eyes = new Eye[2]; this.eyes[0] = new Eye(new Point(eyeballWidthMargin, eyeballHeight)); this.eyes[1] = new Eye(new Point(drawingWidth - eyeballWidthMargin, eyeballHeight)); } @Override public void run() { frame = new JFrame("Moving Eyes"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); drawingPanel = new DrawingPanel(drawingWidth, drawingHeight); frame.add(drawingPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public class DrawingPanel extends JPanel { private static final long serialVersionUID = -2977860217912678180L; private static final int eyeballOuterRadius = 50; private static final int eyeballInnerRadius = 20; public DrawingPanel(int width, int height) { this.addMouseMotionListener(new EyeballListener(this, eyeballOuterRadius - eyeballInnerRadius - 5)); this.setBackground(Color.WHITE); this.setPreferredSize(new Dimension(width, height)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); for (Eye eye : eyes) { drawCircle(g, eye.getOrigin(), eyeballOuterRadius); fillCircle(g, eye.getEyeballOrigin(), eyeballInnerRadius); } } private void drawCircle(Graphics g, Point origin, int radius) { g.drawOval(origin.x - radius, origin.y - radius, radius + radius, radius + radius); } private void fillCircle(Graphics g, Point origin, int radius) { g.fillOval(origin.x - radius, origin.y - radius, radius + radius, radius + radius); } } public class Eye { private final Point origin; private Point eyeballOrigin; public Eye(Point origin) { this.origin = origin; this.eyeballOrigin = origin; } public Point getEyeballOrigin() { return eyeballOrigin; } public void setEyeballOrigin(Point eyeballOrigin) { this.eyeballOrigin = eyeballOrigin; } public Point getOrigin() { return origin; } } public class EyeballListener extends MouseMotionAdapter { private final double eyeballDistance; private final DrawingPanel drawingPanel; public EyeballListener(DrawingPanel drawingPanel, double eyeballDistance) { this.drawingPanel = drawingPanel; this.eyeballDistance = eyeballDistance; } @Override public void mouseMoved(MouseEvent event) { Point p = event.getPoint(); for (Eye eye : eyes) { Point origin = eye.getOrigin(); double theta = Math.atan2((double) (p.y - origin.y), (double) (p.x - origin.x)); int x = (int) Math.round(Math.cos(theta) * eyeballDistance) + origin.x; int y = (int) Math.round(Math.sin(theta) * eyeballDistance) + origin.y; eye.setEyeballOrigin(new Point(x, y)); } drawingPanel.repaint(); } } } Model The Eye class is a Java object that holds the origin of the eye (circle) and the origin of the eyeball. The Eye class is the model in this simple example. View The MovingEyes class is the class that defines the JFrame. The MovingEyes class is part of the view. The main method of this class invokes the SwingUtilities invokeLater method to ensure that the Swing components are defined and modified on the Event Dispatch thread. We use a JFrame. We do not extend a JFrame. The only time you extend a Swing component, or any Java class, is when you want to override one of the class methods. We’ll see this when I talk about the DrawingPanel. The constructor of the MovingEyes class defines 2 instances of the Eye class. The run method defines the JFrame. The code in the run method will be similar for all Swing GUIs. The DrawingPanel class makes up the rest of the view. The DrawingPanel class extends JPanel because we want to override the paintComponent method. The constructor of the DrawingPanel class sets the preferred size of the drawing area, and adds the mouse motion listener. The mouse motion listener is the controller of this Swing GUI. The paintComponent method of the DrawingPanel class first calls the super paintComponent method. This maintains the Swing paint chain, and should always be the first statement of the overwritten paintComponent method. The rest of the code in the paintComponent method of the DrawingPanel class draws the eyes. We only have drawing (painting) code in the paintComponent method. Control code belongs in the controller. Controller The EyeballListener class is the controller class. You can have more than one controller class in a more complicated Swing GUI. The EyeballListener class extends the MouseMotionAdapter. You can implement the MouseMotionListener. I’m overriding one method, so the code is shorter when I extend the MouseMotionAdapter. The mouseMoved method of the EyeballListener class fires a MouseEvent when the mouse is moved. We calculate a new position for the center of an eyeball by finding the theta angle from the center of the eye to the mouse position. The theta angle is used to calculate the new center of the eyeball. Each Eye instance is updated separately in the for loop. After both eyes are updated, the drawing panel is repainted. This happens so fast that there’s no need for an animation loop in a separate thread. An animation loop updates the model, draws the view, and waits for a specified period of time. You would use a separate thread for the animation loop, so that the GUI on the Event Dispatch thread stays responsive. If your GUI is not responsive, you’re probably doing too much work on the Event Dispatch thread.
[ "math.stackexchange", "0003418629.txt" ]
Q: Pigeon Hole Principle (most probably) Prove that any set of 46 distinct 2-digit numbers contains two distinct numbers which are relatively prime. This is what I am trying to prove. I have a feeling that it would be using the pigeon hole principle but I just cannot figure it out. This is what I found interesting so far: There are 90 2-digits numbers ([10,99]), which means that there are exactly 45 even numbers, which means that in a set with 46 numbers, there must be at least one odd number. Though I do not know what to make of that... Also, 46 is optimal, in the snse that there exists a set of 45 distinct 2-digit numbers so that no two distinct numbers are relatively prime. A: Suppose by contradiction that $S$ is a set of $46$ integers in $\{10, \ldots, 99\}$ such that no two distinct elements $a, b \in S$ are relatively prime; i.e., for all $a, b \in S$ such that $a \ne b$, $\gcd(a,b) > 1$. A few key observations are needed. First is that if $b = a+1$, then $\gcd(a,b) = 1$. So $S$ cannot contain any consecutive elements. Second, what is the maximal size of the set $S$ under this condition? Since there are $99 - 10 + 1 = 90$ two-digit numbers, one can choose at most half, or $45$ of these numbers in such a way that there are no two consecutive elements. But this contradicts the assumption that $|S| = 46$; therefore, no such $S$ exists. In short, the proof such a set doesn't exist merely relies on the fact that any two consecutive integers are relatively prime.
[ "stackoverflow", "0033523736.txt" ]
Q: ReactJS - Can't import component I'm brand new to ReactJS. I'm developing a little single page app and I'm just trying to create my components to import within my main component. TestComponent.jsx import React from 'react' export class TestComponent extends React.Component { render() { return ( <div className="content">Test Component</div> ) } } Inside my main.jsx I've imported this component calling import TestComponent from './components/TestComponent.jsx' Then I've tried to call my component for a specific route: render( (<Router history={history}> <Route path="/" component={NavMenu}> <IndexRoute component={Index}/> <Route path="test" component={TestComponent}></Route> </Route> </Router>), document.getElementById('main') ) I've not got any errors from the console, but I don't see my component. What am I doing wrong? A: The import syntax without curly braces is for importing default exports, not for importing named exports. Make your component the default export: TestComponent.jsx import React from 'react' export default class TestComponent extends React.Component { render() { return ( <div className="content">Test Component</div> ) } } Alternatively you should be able to import it as it is with the following import statement: import { TestComponent } from './components/TestComponent.jsx' You might want to read up on ES6 modules (e.g. in Exploring ES6) if you want to use ES6 in your React code.
[ "stackoverflow", "0004273712.txt" ]
Q: setOnClickListener throws NullPointerException ONLY inside for loop. Why? private final Button[] BUTTONS = { btn1, btn2, btn3,btn4 }; ... btn1 = (Button) this.findViewById(R.id.btn_1); btn2 = (Button) this.findViewById(R.id.btn_2); btn3 = (Button) this.findViewById(R.id.btn_3); btn4 = (Button) this.findViewById(R.id.btn_4); ... int n = BUTTONS.length; for(int i=0; i<n; i++) { if(DEBUG) Log.d(TAG, String.valueOf(i)); BUTTONS[i].setOnClickListener(this); } throws NullPointerException, whereas btn1.setOnClickListener(this); btn2.setOnClickListener(this); btn3.setOnClickListener(this); btn4.setOnClickListener(this); works fine. Doesn't make any sense to me. A: I think it's because your Buttons array is created when btn1,... are still null. So when you call BUTTONS[i].setOnClickListener in the loop you are really saying null.setOnClickListener which will give an exception. Try setting up the array as a variable and sey AFTER you've assigned btn1, etc. Haven't tested it but something like this might work better... private ArrayList mBtns = new ArrayList(); private void initButton(int id) { button = (Button) findViewById(id); button.setOnClickListener(this); mBtns.add(button); } ... initButton(R.id.btn_1); initButton(R.id.btn_2); initButton(R.id.btn_3); initButton(R.id.btn_4); Also unless the buttons do very similar things you may find it better to simply define the onClick attribute on each in the layout and save yourself A LOT of coding (only available in Android 1.6 and higher).
[ "stackoverflow", "0045721694.txt" ]
Q: i am getting exception while starting coding Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases at com.google.common.base.Preconditions.checkState(Preconditions.java:750) at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124) at org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41) at org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:115) at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:329) at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:207) at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:103) at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:99) at test_cases.Login_procedure.main(Login_procedure.java:10) A: Please follow this steps: Download gecko driver from GitHub. It will be in form of zip file. Extract the file and place as per your convenience. Now in code use setProperty(String key, String path) method to set the browser.
[ "stackoverflow", "0025210365.txt" ]
Q: Error Handling mechanism Why errors are not handled? Since Error class is derived from Throwable class(JAVA) it can also be handled.But why it is not a good practice to handle the error? A: Compilers are not predictive to get the result exactly in the format humans want. They obviously work on the limited syntax and semantics rule and as per some grammar (or rules you can say). Errors are also Exceptions in Java that define exceptions which aren't expected to be caught under normal circumstances. So basically, an error is that problem which requires human handling for getting the correct result. Also, your assumption that errors aren't handled is incorrect, as errors are reported like errors occurring during runtime. But, they don't specifically correct the error and also they don't provide much detail about the error.
[ "stackoverflow", "0001377782.txt" ]
Q: Javascript: How to determine the screen height visible (i.e., removing the space occupied by the address bar etc) As asked in the question, how do I find out the screen space available for the webpage through javascript? A: window.innerHeight
[ "pt.stackoverflow", "0000049167.txt" ]
Q: Update dinâmico em componente Primefaces através do autocomplete Uma dúvida simples, existe alguma maneira fácil de utilizar o componente autocomplete do primefaces, e assim que ao selecionar alguma opção fazer com que um componente (por exemplo um dataScroller) seja atualizado??? Tentei algo através de um f:ajax adicionando um listener para o evento itemSelect como mostrado no showcase, mas não consigo prosseguir para fazer com que o outro componente seja atualizado dinamicamente, alguma luz? A: Já usei o autocomplete, para atualizar outro componente usei: <p:ajax event="itemSelect" update="componenteID"/>
[ "stackoverflow", "0047733208.txt" ]
Q: Add separator when fetching values from XML in SQL I have following XML code snippet and I am trying to read it in tabular format using SQL Server. declare @ProductXML varchar(max); set @ProductXML = '<hashtable> <entry> <string>host</string> <string-array> <string>csdfs</string> </string-array> </entry> <entry> <string>dom</string><map-array> <map> <entry> <string>thirdlevelentrey</string> <vector> <string>1in</string> <string>2in</string> <string>3in</string> <string>4in</string> <string>5in</string> </vector> </entry> </map> </map-array></entry> </hashtable>' DECLARE @xml xml SELECT @xml = CAST(CAST(@ProductXML AS VARBINARY(MAX)) AS XML) SELECT x.Rec.query('./string').value('.', 'nvarchar(50)') AS 'Product Name', x.Rec.query('./vector/string').value('.', 'nvarchar(50)') AS 'Product TLDs' FROM @xml.nodes('/hashtable/entry/map-array/map/entry') AS x(Rec) I am facing the issue with second column Product TLDs. In under the vector multiple rows value merged in single text. I want them with separator or delimited text so I could recognize them later when I use. If someone can help me to place a separator or deliminator such as 1in|2in|3in and so on... or can it be possible to in a child table considering thirdlevelentry as a table. A: You could use SUBSTRING( x.Rec.query('for $string in ./vector/string/text() return concat("|", $string) ').value('.', 'nvarchar(50)'), 2,50) AS [Product TLDs] This returns 1in |2in |3in |4in |5in So injects some additional spaces. If the values you are concatenating won't contain any spaces you could use REPLACE( x.Rec.query('for $string in ./vector/string/text() return string($string) ').value('.', 'nvarchar(50)'), ' ','|') AS [Product TLDs] Which returns 1in|2in|3in|4in|5in
[ "stackoverflow", "0000362038.txt" ]
Q: Curved corner border for a div I need to build a div with curved corner border, with out using any images in the corner. Is it possible? I dont want to insert curved images in the corner, Please help me regarding this. A: If you want to rely on webkit and mozilla browsers, you can use the following css commands: .radius { -moz-border-radius: 6px; -webkit-border-radius:6px; border-radius: 6px; } Details can be viewed here. info on the CSS2 spec border-radius can be found here These unfortunately do not work for ie. you could go a javascript route for IE only by using niftycube which has the added benefit of supporting column height leveling without problems. A: http://www.curvycorners.net/ Try this library out, it did wonders for me! It is a tested cross browser solution. A: You can use CSS to achieve rounded corners in modern browsers... border-radius: 10px; Handy Generator This is known as progressive enhancement. IMO, this is better than images and or CSS tricks with margins and borders. Unless you absolutely must have rounded corners.
[ "stackoverflow", "0026068637.txt" ]
Q: jQuery / JavaScript find and replace with RegEx I have a number of pages that contain phone number in this format xxx-xxx-xxxx. These phone numbers are not links, what I need to do it write some script that first finds these phone numbers. This is what I have got for that: $(document).ready(function(){ var content = $(".main").text(); var phoneNumber = content.match(/\d{3}-\d{3}-\d{4}/) alert(phoneNumber); }); This works in so much that is captures the number, what I need to do now is replace that phone number on the page with '<a href=" onclick=" ... "' + 'tel:' + phoneNumber + '">' + 'originalPhoneNumber' + '</a>' However I am totally lost at this point. Can I use .replaceWith() in jQuery? EDIT: Okay I tried to modify the code to include the second attribute i wanted: $(document).ready(function () { var content = $(".main").html(); content = content.replace(/\d{3}-\d{3}-\d{4}/g, function(v){ return $('<a>').attr({ href: "tel:"+v, onclick: "ga('send', 'event', 'lead', 'phone call', 'call');" }).html(v)[0].outerHTML; }); $('.main').html(content); }); It is still adding the href but it is ignoring the onclick. A: This will replace all matching strings in an element with a tel: link <div class = "main">333-333-3333 444-444-4444</div> <script type="text/javascript"> var content = $(".main").text(); content = content.replace(/\d{3}-\d{3}-\d{4}/g, function(v){ return $('<a>').attr('class', set.classname).attr('href', 'tel:'+v).html(v).wrap('<a>').parent().html(); }); $('.main').html(content); </script> Or more neatly implemented as : $.fn.extend({ tel : function(def) { var set = { regex : /\d{3}-\d{3}-\d{4}/g, classname : "" } $.extend(true, set, def); var c = $(this).html(); c = c.replace(set.regex, function(v){ return $('<a>').attr('class', set.classname).attr('href', 'tel:'+v).html(v).wrap('<a>').parent().html(); }); $(this).html(c); return this; } }); // default regex: 000-000-0000 $('.main').tel(); // default regex: 000-000-0000 <a> class of tel-link applied $('.main').tel({ classname : "tel-link" }); // override regex: 0000-0000-000 $('.main').tel({ regex: /\d{4}-\d{4}-\d{3}/g });
[ "stackoverflow", "0020066516.txt" ]
Q: issue with change function on select option in Jquery I have a little select form. When I change options using JQUERY, new suitable price appears inside .prices. AN old price is 100 $. if user is student or pupil, I want make him discount -10 $. So when user choose option student or pupil price is changed from 100 to 90$. But when user choose option again to pupil it must not be change the price, but it changes it to 80 $. Again when choose option student, price was changed to 70. I exactly want that if user choose option: student or pupil, there will be -10 $ discount. you can ask why I used each function? The option: other is selected and first time page shows price 110$. each function fixed this problem. I have also JS fiddle, you can check it. Sorry for my English Language. DEMO HTML <select name="status" id="status"> <option value="1">Student</option> <option value="2">Pupil</option> <option value="3" selected>Other</option> </select> <div class="price"> <span class="prices">100</span> $ </div> JQUERY $( "#status" ).change(function () { var price2 = ($(".prices").text()); $('.prices').text(''); var value = $( "#status option:selected" ).val(); if(value=="3") { new_price2 = +price2 + +10; $('.prices').append(new_price2); } else { new_price2 = price2 - 10; $('.prices').append(new_price2); } }) .change(); $('#status option').each(function() { if(this.selected) { var price2 = ($(".prices").html()); $('.prices').html(''); new_price2 = price2 - 10; $('.prices').append(new_price2); } }); A: You only need the change handler in your jQuery code. Also, you need to keep a static base price value so that you can do all calculations on that instead of keeping a running total of all changes. Try this: $("#status").change(function () { var price2 = $(this).data('base-price'); if ($("option:selected", this).val() == "3") { new_price2 = price2; } else { new_price2 = price2 - 10; } $('.prices').text(new_price2); }).change(); Example fiddle
[ "stackoverflow", "0041543536.txt" ]
Q: How to modify content with CSS? WARNING: I do not recommend anyone to do this. It's an ugly hack. I've got the code (minimized for the example) <div id="somecontent"> <a name="content"></a> Content to be changed </div> JSFiddle: https://jsfiddle.net/zalun/o733uyvs/ I'd like to change the "Content to be changed" with CSS. Is this even possible (all ugly hacks included)? It's easy when HTML is modified (<span> added) as in second block in mentioned fiddle. A: Note: What you are trying to do is not recommended. I am providing you a solution because I think you do not have access to source HTML or your content is generated dynamically. I would still suggest you too either change the source file or modify the DOM node using JavaScript. I would say No and Yes. Why No? That's a text node. You cannot manipulate DOM nodes using CSS. You need to use JavaScript for that. Why Yes? (Using ugly hacks), How? Using content property as you are already using, but you cannot change the DOM, so you can make it super ugly like Demo #somecontent { color: transparent; position: relative; } #somecontent a:before { content: "My new content"; color: #000; position: absolute; } JavaScript Solution : Demo // You'll see text flicker var t = document.getElementById('somecontent'); t.textContent = 'New Text';
[ "stackoverflow", "0030989259.txt" ]
Q: counting special characters with recursion I'm trying to code this one up,but I don't get an expected result: Given a string, compute recursively (no loops) the number of lowercase 'x' chars in the string. countX("xxhixx") → 4 countX("xhixhix") → 3 countX("hi") → 0 Here is my method: public int countX(String str) { int count = 0; if(str.length() >= 1 ) { if(str.substring(0, 1).equals("x")) { str = str.substring(1, str.length()); count = count + 1 + countX(str); } } else { str = str.substring(1, str.length()); count = count + countX(str); } return count; } A: You had the right idea, but I think you over complicated things. Just check explicitly if the first character is x (as you have), and only increment count in that case. Regardless of whether it was or wasn't, continue recursing on: public static int countX(String str) { int count = 0; if (str.length() > 0) { if (str.substring(0, 1).equals("x")) { ++count; } str = str.substring(1, str.length()); count += countX(str); } return count; }
[ "mathoverflow", "0000066709.txt" ]
Q: Generator of translation for the hyperbolic plane? What is the generator of translation in the Beltrami-Klein model of the hyperbolic plane? A: Hyperbolic plane is a homogeneous space $G/H$ where $G$ acts by isometries and so any reasonable defined `translation' is given by the natural left action of $G$. Decide what elements of $G$ will you call translations and then for any abstract generator $X\in\mathfrak{g}$ such that $\exp{tX}$ is translation, compose the natural left action with diffeomorphism of $G/H$ to your favorite model. Differentiate the resulting map at zero and you are done. If I am not mistaken, this question is more suitable for math.SE.
[ "stackoverflow", "0004631192.txt" ]
Q: SQL Server trigger execution Say I have an UPDATE trigger on tableA that inserts a new record into tableB. CREATE TRIGGER insertIntoTableB ON tableA FOR UPDATE AS INSERT INTO tableB (...) VALUES (...) GO I then run these statements sequentially. Will the second UPDATE statement (UPDATE tableB) work OK? (i.e. wait for the trigger on table A to fully execute) UPDATE tableA SET ... WHERE key = 'some key' UPDATE tableB SET ... WHERE key = 'newly inserted key from trigger' A: The behavior is subject to the nested triggers server configuration, see Using Nested Triggers: Both DML and DDL triggers are nested when a trigger performs an action that initiates another trigger. These actions can initiate other triggers, and so on. DML and DDL triggers can be nested up to 32 levels. You can control whether AFTER triggers can be nested through the nested triggers server configuration option. INSTEAD OF triggers (only DML triggers can be INSTEAD OF triggers) can be nested regardless of this setting. When a trigger on table A fires and inside the trigger table B is updated, the trigger on table B runs immediately. The Table A trigger did not finish, it is blocked in waiting for the UPDATE statement to finish, which in turn waits for the Table B trigger to finish. However, the updates to table A have already occurred (assuming a normal AFTER trigger) and querying the Table A from the table B's trigger will see the updates.
[ "stackoverflow", "0014953720.txt" ]
Q: rails 2 undefined method I use rails v 2.3.14 I add route in routes.rb map.with_options :controller => 'consumer_profile' do |m| ... m.consumer_profile_show_coupons 'consumer/:id/coupons', :action => 'show_coupons', :requirements => {:id => /c-[0-9a-zA-Z]+/} ... end I add def in consumer_profile_controller.rb def show_coupons .. end I add file consumer_profile/show_coupons.html.erb rake routes: consumer_profile_show_coupons /consumer/:id/coupons {:action=>"show_coupons", :controller=>"consumer_profile"} but when I use seo_consumer_profile_coupons_url(current_user.consumer_profile) that rails says: undefined method `seo_consumer_profile_coupons_url' Have any ideas? A: I pointed out the direct :controller=>'consumer_profile',:action=>'show_coupons' in link_to, it works...
[ "stackoverflow", "0022766165.txt" ]
Q: Typo3 C# interface (SOAP or REST) I've got the task to connect a platform based on .net via a plugin to Typo3. I'm not very familiar with Typo3, but with the .net stack (actually using C#). The requirements include writing data to Typo3 and retrieving data from Typo3. Looking at the Typo3 API documentation (http://api.typo3.org/), I don't find any information on the interfaces I could use, or even how to stuff data into the system. I used all my favorite search engines, but ended up here. (Or I just searched for the wrong terms?!) Following requirements have been provided additionally: No writing/reading to/from the database (we don't get access to it for multiple reasons) Use of a general solution (which could be re-used for different entities) Synchronous process (so we get an error when inserting data has failed, etc.) No batch import/export solution Authentication must be used What I search for is a simple interface which I can consume from my plugin. Something like SOAP, REST or any variant which I can call via http/https - including authentication. Do you have an idea? A: There is no external API built in TYPO3 out of the box. Quick search for REST or SOAP based extensions (http://typo3.org/extensions/repository/) to provide e.g. page structure and contents from TYPO3 doesn't provide any results either. The only solution is to write an own extension providing a SOAP or REST API to access TYPO3 data.
[ "stackoverflow", "0062987548.txt" ]
Q: Nodejs Express - Is there any way to reduce the following code to something simpler? I have the following code that I would like to reduce. This question might be very lame, so sorry about it. I wanted to replace the meal1..10 with a variable in a for loop, but I'm not sure if that can be done in node js. function hasPortion(meals) { const portions = ["4", "3", "2", "1", "1/8", "1/4", "1/2"]; if (meals.meal1 != undefined && meals.meal1.activado == "on" && portions.indexOf(meals.meal1.porcion) < 0) { return false; } if (meals.meal2 != undefined && meals.meal2.activado == "on" && portions.indexOf(meals.meal2.porcion) < 0) { return false; } if (meals.meal3 != undefined && meals.meal3.activado == "on" && portions.indexOf(meals.meal3.porcion) < 0) { return false; } if (meals.meal4 != undefined && meals.meal4.activado == "on" && portions.indexOf(meals.meal4.porcion) < 0) { return false; } if (meals.meal5 != undefined && meals.meal5.activado == "on" && portions.indexOf(meals.meal5.porcion) < 0) { return false; } if (meals.meal6 != undefined && meals.meal6.activado == "on" && portions.indexOf(meals.meal6.porcion) < 0) { return false; } if (meals.meal7 != undefined && meals.meal7.activado == "on" && portions.indexOf(meals.meal7.porcion) < 0) { return false; } if (meals.meal8 != undefined && meals.meal8.activado == "on" && portions.indexOf(meals.meal8.porcion) < 0) { return false; } if (meals.meal9 != undefined && meals.meal9.activado == "on" && portions.indexOf(meals.meal9.porcion) < 0) { return false; } if (meals.meal10 != undefined && meals.meal10.activado == "on" && portions.indexOf(meals.meal10.porcion) < 0) { return false; } return true; } A: If meals only have these 10 properties, you may like this, function hasPortion(meals) { const portions = ["4", "3", "2", "1", "1/8", "1/4", "1/2"]; for (const prop in meals) { const meal = meals[prop]; if (meal != undefined && meal.activado == "on" && portions.indexOf(meal.porcion) < 0) { return false; } } return true; } If you have more properties, but only want to check these 10 properties, you may like this, function hasPortion(meals) { const portions = ["4", "3", "2", "1", "1/8", "1/4", "1/2"]; for (let i = 1; i <= 10; i++) { const prop = `meal${i}`; const meal = meals[prop]; if (meal != undefined && meal.activado == "on" && portions.indexOf(meal.porcion) < 0) { return false; } } return true; } Append: new solution As we mentioned, you should use an Array to store all meal items, also you may use a Set to store portions because searching in Set is faster than Array. const meals = [ { activado: "on", porcion: "4" }, { activado: "on", porcion: "1/8" }, { activado: "on", porcion: "3" }, { activado: "on", porcion: "1/2" }, ]; function hasPortion(meals) { const portions = new Set(["4", "3", "2", "1", "1/8", "1/4", "1/2"]); return !meals.some((meal) => meal.activado === "on" && !portions.has(meal.porcion)); } // Good case console.log(hasPortion(meals)); // Output: true // Add bad item meals.push({ activado: "on", porcion: "1/3" }) console.log(hasPortion(meals)); // Output: false
[ "stackoverflow", "0007458000.txt" ]
Q: Submit Button, Execute PHP in CodeIgniter I am developing a web app but running into a few small snags. I'm using CodeIgniter. I want to have 2 buttons that will do execute 2 different functions that do different things to the database. I have these functions made in the proper Controller file. What is the best way to go about making the buttons execute their respective functions? If it requires javascript, I have no problem making it, just need some pointers as I'm a little bit confused here! A: If they're making changes to records in the database, you should probably implement them as part of a form (or two). Potentially destructive actions should not be executable just using a simple GET request. The form(s) can contain a hidden input type to specify what you want to in the controller. HTML page: <form action="controller/myfunction" method="POST"> <input type="hidden" name="action" value="one"> <input type="submit" value="Do action one"> </form> <form action="controller/myfunction"> <input type="hidden" name="action" value="two"> <input type="submit" value="Do action two"> </form> Controller: function myfunction() { // Your form would be submitted to this method... // Get action from submitted form ('one' or 'two') $action = $this->input->post('action'); // Decide what to do switch ($action) { case 'one': $this->my_first_action(); break; case 'two': $this->my_second_action(); break; } } function my_first_action() { // Do stuff... } It would be good practise to redirect to another page once the form has been submitted - use the 'Post/Redirect/Get' pattern.
[ "woodworking.stackexchange", "0000004810.txt" ]
Q: Picture frame using L angle brackets I see picture frames held together with glue, but I'm wondering if equally robust and aesthetic results could be obtained using flat L-shape angle brackets? What problems am I going to run into using this method? A: A little glue is less expensive than the brackets and screws. Metal has a greater coefficient of linear expansion than wood, by something like a factor of two, so you may run the risk of gaps appearing if assembly temperature is significantly lower than temperature where displayed. Not only do the frame pieces need to be held tightly together when applying the brackets, but you will also need to drill precisely centered and sized pilot holes so that splitting, stress AND looseness are avoided.
[ "stackoverflow", "0011124700.txt" ]
Q: Get all clientID from MCC adwords account by adwordsAPI I want to retrieve all clientID from my MCC account. I'm using this code AdWordsUser user = new AdWordsUser(adwordsPropertyService.getEmail(), adwordsPropertyService.getPassword(), null, adwordsPropertyService.getUseragent(), adwordsPropertyService.getDeveloperToken(), adwordsPropertyService.getUseSandbox()); InfoServiceInterface infoService = user.getService(AdWordsService.V201109.INFO_SERVICE); InfoSelector selector = new InfoSelector(); selector.setApiUsageType(ApiUsageType.UNIT_COUNT_FOR_CLIENTS); String today = new SimpleDateFormat("yyyyMMdd").format(new Date()); selector.setDateRange(new DateRange(today, today)); selector.setIncludeSubAccounts(true); ApiUsageInfo apiUsageInfo = infoService.get(selector); for (ApiUsageRecord record : apiUsageInfo.getApiUsageRecords()) { ...... But apiUsageInfo.getApiUsageRecords return my only some clientId. Have you any suggests? A: My Answer will be helpful for PHP Developers I am using v201502(php), You will get all account details from ManagedCustomerService api. Please refer the following URL https://developers.google.com/adwords/api/docs/reference/v201502/ManagedCustomerService This is the sample code i used, function DisplayAccountTree($account, $link, $accounts, $links, $depth) { print str_repeat('-', $depth * 2); printf("%s, %s\n", $account->customerId, $account->name); if (array_key_exists($account->customerId, $links)) { foreach ($links[$account->customerId] as $childLink) { $childAccount = $accounts[$childLink->clientCustomerId]; DisplayAccountTree($childAccount, $childLink, $accounts, $links, $depth +1); } } } function GetAccountHierarchyExample(AdWordsUser $user) { // Get the service, which loads the required classes. $user->SetClientCustomerId('xxx-xxx-xxxx'); $managedCustomerService = $user->GetService('ManagedCustomerService'); // Create selector. $selector = new Selector(); // Specify the fields to retrieve. $selector->fields = array('CustomerId', 'Name'); // Make the get request. $graph = $managedCustomerService->get($selector); // Display serviced account graph. if (isset($graph->entries)) { // Create map from customerId to parent and child links. $childLinks = array(); $parentLinks = array(); if (isset($graph->links)) { foreach ($graph->links as $link) { $childLinks[$link->managerCustomerId][] = $link; $parentLinks[$link->clientCustomerId][] = $link; } } // Create map from customerID to account, and find root account. $accounts = array(); $rootAccount = NULL; foreach ($graph->entries as $account) { $accounts[$account->customerId] = $account; if (!array_key_exists($account->customerId, $parentLinks)) { $rootAccount = $account; } } // The root account may not be returned in the sandbox. if (!isset($rootAccount)) { $rootAccount = new Account(); $rootAccount->customerId = 0; } // Display account tree. print "(Customer Id, Account Name)\n"; DisplayAccountTree($rootAccount, NULL, $accounts, $childLinks, 0); } else { print "No serviced accounts were found.\n"; } } GetAccountHierarchyExample($user); SetClientCustomerId will be the parent ID of your all accounts, It will be appeared near the Sign Out button of you google AdWords account, Please see the attached image I hope this answer will be helpful, Please add your comments below if you want any further help A: If you need just the list of clientCustomerIds, try ServicedAccountService. Here is a code example that shows how this may be done. Next time, you might also want to consider asking the question on the official forum for AdWords API: https://groups.google.com/forum/?fromgroups#!forum/adwords-api
[ "electronics.stackexchange", "0000408409.txt" ]
Q: VHDL ieee.numeric_std: Division by zero defined? As the title says, I'd like to know if the behavior of a zero division in ieee.numeric_std is somehow defined. If one does signal a, b : unsigned (width1_g-1 downto 0); signal c : unsigned (width2_g-1 downto 0); div_proc : process (clk_i) begin if rising_edge(clk_i) then c <= a / b; end if; end process; for example, what will be the outcome of c? A: In your example a and b are not initialized, but I assume you want a division with b := 0 somewhere, this answer is for FPGAs only: From the numeric_std.vhd package: -- NOTE: If second argument is zero for "/" operator, a severity level -- of ERROR is issued. -- Id: A.21 function "/" (L,R: UNSIGNED ) return UNSIGNED; So in simulation this should crash. If it doesn't crash, you should find a better simulator. In synthesis: Vivado only supports division by powers of 2 in older versions and will try to infer a Divider LogiCORE unit for others, which doesn't support division by a constant 0 (so that's a synthesis error) and allows for optional error detection when trying to divide by a variable that might be 0. I haven't tried what happens if you turn this inference off in current editions, but I'd suspect it again only accepts powers of 2. Current Quartus products try to infer a DSP divisor with extremely similar limitations as the Xilinx Divider. No idea what happens when you try to synthesize it in pure LUTs. I know division can be infered for non-binary powers and it's horrible. Don't try to divide by zero.
[ "stackoverflow", "0029364167.txt" ]
Q: Get current page of pagination in view and manually set count of page I need to manually set count of page for pagination in view.py I need to get number of current page for processing it in function. I next view.py: class VideoListView(ListView): template_name = "video/list.html" context_object_name = 'videos' paginate_by = 12 request = requests.get(settings.YOUTUBE_VIDEO_COUNT_URL) count = simplejson.loads(request.text)['data']['totalItems'] def get_queryset(self, **kwargs): request = requests.get(settings.YOUTUBE_VIDEO_URL) data_about = simplejson.loads(request.text) video_list = [] for item in data_about['data']['items']: video_list.append(item) return video_list Count of pages must be: count/paginate_by, and on every page request json will be different. A: The Django pagination is stored via GET, so in your ListView you need to access: # This will assume, if no page selected, it is on the first page actual_page = request.GET.get('page', 1) if actual_page: print actual_page so in your list view code, depends on where you need it, but if you need it in your get_queryset function, you can access the request using self: class VideoListView(ListView): # ..... your fields def get_queryset(self, **kwargs): # ... Your code ... actual_page = self.request.GET.get('page', 1) if actual_page: print actual_page # ... Your code ... Custom pagination object using Django Pagination: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def CreatePagination(request, obj_list): # Create the pagination RESULTS_PER_PAGE = 10 paginator = Paginator(obj_list, RESULTS_PER_PAGE) page = request.GET.get('page') # Actual page try: page_list = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. page_list = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. page_list = paginator.page(paginator.num_pages) return page_list To use this CreatePagination function you need to pass it the request and the object list. The request is used to get the actual page, and the object list is used to generate the pagination. This function will return a pagination that you can manage in the template the same way you're managing the automatic generated pagination from the ListView
[ "stackoverflow", "0048148830.txt" ]
Q: Multiple test in vert.x application Hello and happy new year I am working with Vert.x & Scala on API application. I am using the code example from this page to create a first basic API application. My problem is, that I have two tests on the same address & port, but not on the same route, but only one is ran. For the other, the IDE return VerticleSpec *** ABORTED *** [info] java.net.BindException: Address already in use [info] at sun.nio.ch.Net.bind0(Native Method) [info] at sun.nio.ch.Net.bind(Net.java:433) [info] at sun.nio.ch.Net.bind(Net.java:425) [info] at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223) [info] at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:128) [info] at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:558) [info] at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1283) [info] at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:501) [info] at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:486) [info] at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:989) So, how could I make all my tests running ? EDIT Under is one file coming from the official repo. It deploy and undeploy route of the API. So, that means the port should be taken then released after one test, right ? import io.vertx.lang.scala.json.{Json, JsonObject} import io.vertx.lang.scala.{ScalaVerticle, VertxExecutionContext} import io.vertx.scala.core.{DeploymentOptions, Vertx} import org.scalatest.{AsyncFlatSpec, BeforeAndAfter} import scala.concurrent.Await import scala.concurrent.duration._ import scala.reflect.runtime.universe._ import scala.util.{Failure, Success} abstract class VerticleTesting[A <: ScalaVerticle: TypeTag] extends AsyncFlatSpec with BeforeAndAfter{ val vertx = Vertx.vertx implicit val vertxExecutionContext = VertxExecutionContext( vertx.getOrCreateContext() ) private var deploymentId = "" def config(): JsonObject = Json.emptyObj() before { deploymentId = Await.result( vertx .deployVerticleFuture("scala:" + implicitly[TypeTag[A]].tpe.typeSymbol.fullName, DeploymentOptions().setConfig(config())) .andThen { case Success(d) => d case Failure(t) => throw new RuntimeException(t) }, 10000 millis ) } after { Await.result( vertx.undeployFuture(deploymentId) .andThen { case Success(d) => d case Failure(t) => throw new RuntimeException(t) }, 10000 millis ) } } A: Well, I found how do it. In the build.sbt, I just added this line, and it worked fine parallelExecution in Test := false So, if somebody got this problem, it could help :)
[ "stackoverflow", "0056789602.txt" ]
Q: How to get HTML data that is stored on JavaScript variable I have some HTML data stored on JavaScript variable and I want to fetch the data from that variable I'm trying to get it by getElementById() method. Please also keep it in mind that I have used same id in every div. I know it's not good way but there is some restriction. So I need the data from 2nd Div. var complexArray = "<div id=" post ">First content<\/div><div id=" post ">Second Content<\/div><div id=" post ">Third Content<\/div>"; var data = document.getElementById('post').innerHTML; alert(data); A: You can't query in the document for something that only exists in a string variable. Put that html string into a temporary element and query for it within that element Change the repeating ID's to classes instead since ID's must be unique var complexArray = '<div class="post">First content<\/div><div class="post">Second Content<\/div><div class="post">Third Content<\/div>'; // create element to insert the html string into var tempDiv = document.createElement('div'); tempDiv.innerHTML = complexArray; // query within that element var posts = tempDiv.querySelectorAll('.post'); var data = posts[1].innerHTML; console.log(data);
[ "stackoverflow", "0037422780.txt" ]
Q: Ordered JSON conversion in Java, Reading a JSONArray of JSONObjects I'm sending the following JSON to a Java Program. I put in this configuration so that my order would be preserved. I'm using the org.json library. "Ordered JSON" var obj = { "params": [ {"base_s" : robot.base.length}, {"base_k" : robot.base.k}, {"base_phi" : robot.base.phi}, {"mid_s" : robot.mid.length}, {"mid_k" : robot.mid.k}, {"mid_phi" : robot.mid.phi}, {"tip_s" : robot.tip.length}, {"tip_k" : robot.tip.k}, {"tip_phi" : robot.tip.phi} ] }; Before I had the JSON formatted as such: Original JSON var obj = { base_s : robot.base.length, base_k : robot.base.k, base_phi : robot.base.phi, mid_s : robot.mid.length, mid_k : robot.mid.k, mid_phi : robot.mid.phi, tip_s : robot.tip.length, tip_k : robot.tip.k, tip_phi : robot.tip.phi }; The following Java code interpreted the original JSON fine, but has issues with the "Ordered" JSON. JSONArray nameArray = jsonData.names(); JSONArray valArray = jsonData.toJSONArray(nameArray); The nameArray is ["items"] and the valArray is [[{"base_s":0.314},{"base_k":0.0012},{"base_phi":0.436},{"mid_s":0.314},{"mid_k":0.0012},{"mid_phi":0.436},{"tip_s":0.3139},{"tip_k":0.0012},{"tip_phi":0.436}]] I'm curious as to how I "do this one more time" in order to extract the nine numbers out of the array. So that I get something like this vals = [0.314, 0.0012, 0.436, 0.314, 0.0012, 0.436, 0.3139, 0.0012, 0.436] that I can then turn into an array of floats. A: For the ordered JSON you can try something like the following JSONArray results = obj.getJsonArray("params"); for (int i = 0, size = results.length(); i < size; i++){ JSONObject objectInArray = results.getJSONObject(i); String[] elementNames = JSONObject.getNames(objectInArray); for (String elementName : elementNames) { String value = objectInArray.getString(elementName); // in value you have your double } }
[ "stackoverflow", "0027140573.txt" ]
Q: Simulating Touch Event in Windows 8 I'm creating an application (C#) using finger tracking via camera, and need to simulate a touch even where the user's finger is located. How do I simulate a touch event within Windows 8? This is a Windows 8 only application, so don't worry about compatibility. Thank you guys! A: Windows have InjectTouchInput function for simulating touch input. There is .NET-wrapper for it in TCD.System.TouchInjection NuGet package. Also you can try to pInvoke it by yourself - it's not very complicated.
[ "stackoverflow", "0035006510.txt" ]
Q: Find specific resource filtering by name - Chrome extension I'm trying to make an extension that is able to find a specific resource loaded by the page, filtering by name and downloading it. The reason I want to do this is because I usually go to the network tab in the developer tools, filter the requests/responses, for example, looking for one with the word "foobar" in its name, and open the link in a new tab so I can download it (it's an xml file). I was wondering if this could be automated with an extension, even if the word used to filter is hardcoded. I don't have any experience with chrome extensions, so I wondered if this could be done or if it's just not possible with the devtools api. In case it could be done, if you could give me some guidelines on how to make it I would really appreciate it. Thanks! A: There are several ways to access the information you need in an extension. You can write a Dev Tools extension. In that case, you have access to chrome.devtools.network API which will provide you that information. This requires you to open Dev Tools and interact with your own UI there (such as an extra tab in Dev Tools). You can go low-level and use chrome.debugger API to attach to a page like Dev Tools would. It's a complex topic, I'm just pointing you in that direction. Since you rely only on filtering by name, not response itself, you can use chrome.webRequest API to intercept network requests and log those that interest you for processing. This is probably simplest to do.
[ "stackoverflow", "0053641364.txt" ]
Q: Using JSON.stringify on object without serializer needs to be marked as experimental Using kotlin plugin 1.3.10 in Android Studio, when I try to stringify a simple class' object to JSON, it wont compile: This declaration is experimental and its usage must be marked with '@kotlinx.serialization.ImplicitReflectionSerializer' or '@UseExperimental(kotlinx.serialization.ImplicitReflectionSerializer::class)' @Serializable data class Data(val a: Int, val b: Int) val data = Data(1, 2) val x = JSON.stringify(data) However, giving a serialiser works: val x = JSON.stringify(Data.serializer(), data) I can't see anybody else having this problem, any idea what the problem is? I've set up using serialisation in gradle.build. I import with: import kotlinx.serialization.* import kotlinx.serialization.json.JSON A: The overload of StringFormat.stringify which doesn't take in a serializer (SerializationStrategy) is still experimental. If you view its definition (e.g. ctrl+click on it in the IDE) you'll see it looks as follows: @ImplicitReflectionSerializer inline fun <reified T : Any> StringFormat.stringify(obj: T): String = stringify(context.getOrDefault(T::class), obj) Where that ImplicitReflectionSerializer annotation is itself declared in that same file (SerialImplicits.kt): @Experimental annotation class ImplicitReflectionSerializer So because it's still experimental, you need to do exactly as the warning says, i.e. tell the compiler to allow the use of experimental features, by adding an annotation such as @UseExperimental... where you're using it. Note that the quick example shown on the kotlinx.serialization GitHub repo's main readme shows that you need to pass in a serializer when calling stringify.
[ "stackoverflow", "0024085292.txt" ]
Q: Way to capture part XML code in SAXParser I need to capture text within <page> tags of my XML file. Whole text, with other tags, their attributes etc. I could do this using, for example, regular expressions, but I need this to be safe, so I would like to use SAXParser. But I'm afraid that all information that ContentHandler can receive from SAXParser isn't enough to do this (cursor position at start of found XML tag, for example, would help a lot). So, is there any other, safe way? Instead of text within <page>, it could be, for example, DOM tree, but I would prefer first way, for performance. A: Okay, what I would do first is to create yourself a custom DefaultHandler something like the following; public class PrintXMLwithSAX extends DefaultHandler { private int embedded = -1; private StringBuilder sb = new StringBuilder(); private final ArrayList<String> pages = new ArrayList<String>(); @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if(qName.equals("page")){ embedded++; } if(embedded >= 0) sb.append("<"+qName+">"); } @Override public void characters(char[] ch, int start, int length) throws SAXException { if(embedded >= 0) sb.append(new String(ch, start, length)); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if(embedded >= 0) sb.append("</"+qName+">"); if(qName.equals("page")) embedded--; if(embedded == -1){ pages.add(sb.toString()); sb = new StringBuilder(); } } public ArrayList<String> getPages(){ return pages; } } The DefaultHandler (when parsed) runs through each element and calls startElement(), characters(), endElement() and a few others. The code above checks if the element in startElement() is a <page> element. If so, it increments embedded by 1. After that, each method checks if embedded is >= 0. If it is, it appends the characters inside each element, as well as their tags (excluding attributes in this particular example) to the StringBuilder object. endElement() decrements embedded when it finds the end of a </page> element. If embedded falls back down to -1, we know that we are no longer inside a series of page elements, and so we add the result of the StringBuilder to the ArrayList pages and start a fresh StringBuilder to await another <page> element. Then you'll need to run the handler and then retrieve your ArrayList of strings containing your <page> elements like so; SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); PrintXMLwithSAX handler = new PrintXMLwithSAX(); InputStream input = new FileInputStream("C:\\Users\\me\\Desktop\\xml.xml"); saxParser.parse(input, handler); ArrayList<String> myPageElements = handler.getPages(); Now myPageElements is an ArrayList containing all page elements and their contents as strings. I hope this helps.
[ "ru.stackoverflow", "0000702017.txt" ]
Q: jQuery селекторы при on click Есть таблица. После определенного события (у меня это кнопка CHECK) элементам tr присваивается class. <table border=1> <tr> <td>show 444 after CHECK</td> <td>show 444 after CHECK</td> <td>3</td> <td>4</td> <td id="check">push CHECK to enable click <input type="button" value="CHECK"></td> </tr> <tr> <td>show 444 after CHECK</td> <td>show 444 after CHECK</td> <td>3</td> <td>4</td> <td>5</td> </tr> </table> $(document).ready(function() { $('#check').click(function() { $('tr').attr('class', 'my-class'); alert('CHECK PUSHED!'); }); $('table').on('click', 'tr.my-class > td:lt(2)', function() { alert(444); }); }); Затем на строки с новым классом my-class (только на первые 2 столбца строки) становится можно кликать. Почему-то применяется только к первой строке. Хотя в селекторе указываю: для всех tr.my-class найти дочерние td, первые два Этот же пример: https://jsfiddle.net/MegaByyte/h2bpb6av/7/ Нужно применить alert(444) ко всем строкам, а не только к первой A: Используйте селектор: tr.my-class > td:nth-child(-n+2) вместо tr.my-class > td:lt(2) Ваш селектор берёт первые две ячейки, а не первые два столбца.
[ "stackoverflow", "0031249264.txt" ]
Q: How to find all matches in linq list between 2 numbers I have a list of persons where one propery is a number as string, I would like to find all matches in that list that matches 2 numbers (a range). public class car { public string Name { get; set; } public string No { get; set; } } public void test() { var myList = new List<car> { new car {Name = "Volvo", No = "10"}, new car {Name = "Volvo", No = "20"}, new car {Name = "Volvo", No = "30"}, new car {Name = "Volvo", No = "40"}, new car {Name = "Volvo", No = "50"}, new car {Name = "Volvo", No = "60"} }; var startNumber = 10; var EndNumber = 30; } How can I filter out all the matches in the myList where No is within startNumber and EndNumber ? A: This is a pretty straightforward solution: myList .Where(car => startNumber <= int.Parse(car.No) && int.Parse(car.No) <= EndNumber) .ToList(); Note: If we can't assume No will only contains Natural numbers, than using int.TryParse will be a better alternative than int.Parse. Remarks: I highly recommend you to save No as int rather than string. Also don't be cheap on Property names, If you will use Number or LicensePlate it will be a little longer, but more concise. You should follow .NET naming conventions by using class names with Capital letters. e.g: Car, Animal First letter in Local variables should be lower cased. e.g: endNumber It's a good practice to avoid var when using Primitive variables like int, double etc` A: You have to parse the number to integer and then compare the range. You can also use Int.TryParse to save yourself from the exception. To do the parsing once, make an anonymous type and then query like: int temp; var query = myList.Select(r => new { Car = r, NumericNo = int.TryParse(r.No, out temp) ? temp : 0 //or -1 for invalid values }) .Where(r => r.NumericNo >= start && r.NumericNo <= end) .Select(r => r.Car); You may also follow the General Naming Conventions
[ "stackoverflow", "0001543713.txt" ]
Q: C typedef of pointer to structure I had come across the following code: typedef struct { double x; double y; double z; } *vector; Is this a valid type definition? The code compiles and runs fine. I was just curious if this is common practice. A: Absolutely valid. Usually, you can take full advantage of this way by defining two types together: typedef struct { int a; int b; } S1, *S1PTR; Where S1 is a struct and S1PTR is the pointer to this struct. A: Yes it is. But it is imho bad style. Not the direct declaration of the struct, but the direct declaration of a pointer type. It is obfuscation, the information that a given variable or parameter is a pointer (and to a lesser extent for arrays) is extremly important when you want to read code. When reviewing code it is often difficult to see at first glance which function could have a side effect or not. If the types used hide this information, it adds a memorisation burden to the reader. int do_fancy(vector a, vector b); or int do_fancy(vector *a, vector *b); in the first case I can miss easily that that function may change the content of a or b. In the second I'm warned. And when actually writing code I also know directly to write a->x and not have the compiler tell me error: request for memberx' in something not a structure or union`. I know, it looks like a personal taste thing, but having worked with a lot of external code, I can assure you that it's extremely annoying when you do not recognize the indirection level of variables. That's one reason I also dislike C++ references (in Java it's not because all objects are passed by reference, it's consistent) and Microsoft's LPCSTR kind of types. A: Yes it is valid. If you need more "security" you can also do typedef struct vector_{ double x; double y; double z; } *vector; then you can use both struct vector_ *var; vector var; But don't forget the ending semi-colon. Using only typedef means that you name it that way. otherwise it'd be more or less anonymous.
[ "stackoverflow", "0022269483.txt" ]
Q: algorithm to search for an element in array Here is another interview question Array contains elements where next element can be either x+1 or x-1 if previous element is x. Prev element = x Next element = x+1/ x-1 Example: {2, 3, 4, 3, 2, 1, 0, -1, 0, 1, 2, 3, 2, 1} If I need to search for 0 what is best algorithm we can choose? If I sort it then it will be O(nlogn) and I can just traverse array in O(n) so O(n) is still better Creating binary search tree will be again O(n) and search in BST is O(log) so still its O(n). Its a random array and next element is +1 or -1 doesnot leads to any search pattern. If you guys can think of any search pattern that can be utilised here to perform better search then let me know. A: The obvious thing to do is: Consider the first value, let's say the value is n. Is it 0? If yes, you are done. If not, step forward abs(n) elements, and go to step 1. You can step over multiple elements because the absolute difference between two adjacent values is always 1. So, given the array in your question, you do the following: Item 0 is 2. That's not zero, and so you step to item 2. Item 2 is 4. That's not zero, step forward 4 items to item 6. Item 6 is 0. You are done.
[ "math.stackexchange", "0001740997.txt" ]
Q: Mechanics ODE Problem Particle I have a particle of mass $M$ which moves with a velocity $v$, such that; $$Mv' = -Mg - kv^2$$ where $g$ and $k$ are positive, and its initial velocity is $U$, i.e $v(0) = U$. I am then told that the particle travels until it becomes stationary, at a distance $D$ from it's original position. I am looking for an expression for this distance, but I am unable to solve non linear second order ODEs so I am wondering if there is a different approach available? A: This ODE is nonlinear, but first order (because there is only a first derivative to $t$). To solve it, use the method of separation of variables.
[ "stackoverflow", "0062550742.txt" ]
Q: Is it possible add/remove pin marker on location plan(image or vector) by using Javascript or DevExpress? There are nearly 1000 cameras in the factory where I work. What I asked for is to mark the locations of these cameras on the map(non-geographical) of the factory. And by clicking on one of the camera icons by zooming, it is necessary to connect to the camera with a IP address and instantly watch the camera in the popup. After long research, I couldn't get enough information for me. In the sources I have researched, latitude and longitude operations are made on the real map. But since I do not know the latitude and longitude values of the cameras, I cannot do this way. Which technology or which library can I use for this requirement? I searched a lot and I could not reach the necessary information. I am curious about your opinion on the subject. A: The solution I can find is like the link below. ZoomMarker
[ "stackoverflow", "0007852908.txt" ]
Q: Word wrap when using git grep I am trying to run git grep from terminal (using Titanium). The results do not wrap and get cut off at the window so I cannot read anything. I tried messing around with config but could not get anything. How can I make these grep results wrap? A: Have you set core.pager in your .gitconfig? If you are using less, you can see the extra characters by pressing the right arrow key on the keyboard. Edit: Even when I unset core.pager, git grep seems to invoke less -S by default. Edit 2: Whoops, as Keith Thompson pointed out less does wrap lines by default. From the man page: -S or --chop-long-lines Causes lines longer than the screen width to be chopped rather than folded. That is, the portion of a long line that does not fit in the screen width is not shown. The default is to fold long lines; that is, display the remainder on the next line. A: Try piping the output through cat.
[ "stackoverflow", "0053844856.txt" ]
Q: Accessing Prev State Am trying to create dynamic tabs with close button. So if a active-tab is closed, the previously-active-tab becomes active. Below is my code., closeCurrentTab = (toBeClosedTab) => { let remainingTabs = this.state.allOpenedTabs; remainingTabs.splice(remainingTabs.indexOf(toBeClosedTab), 1); this.setState(prevState => ({ allOpenedTabs: remainingTabs, activeTab: prevState.activeTab })); }; The value of 'activeTab' state is not changing to the previous value. Can someone help what am missing here. FYI., The same file has the following code and it works perfectly., alterOnUpdate = () => { this.setState(prevState => ({ aClick: !prevState.aClick })); }; A: By doing: activeTab: prevState.activeTab You are just keeping the current value of state.activeTab. This statement makes no sense and even if you remove it the result would be same. So you need to retain the value of previous active tabs in state as well, and on closing currently active tab, set activeTab to previousActiveTab.
[ "security.stackexchange", "0000044716.txt" ]
Q: Is it possible to intercept https traffic and see the links? If a site uses https and transfers the customers credit card and ID in the url. Will an attacker be able to intercept those through a MITM attack? And through Sniffing.? Can the packets be sniffed somehow to see the links? A: If the Man-in-the-Middle attack succeeds, then, by definition, the attacker sees everything: success here being that the attacker impersonates both the client and the server, so the client talks to the attacker, the server talks to the attacker, the attacker decrypts on one side and reencrypts on the other. With a successful MitM, the attacker can see the links, the page contents, the passwords... But, of course, SSL has been designed to defeat MitM attacks. The main protection is the server's certificate. To succeed at MitM, the attacker must create a fake certificate with the server's name, but containing a public key that the attacker controls. The whole point of trusted root CA and certificate validation is so that the client does not get fooled by a fake server certificate. (If the human users sees the scary warning from his browser "this server uses an untrusted certificate" and still clicks on the "I don't care, connect anyway !" button, then the MitM succeeds. Security against MitM in SSL relies on the idea that the human user does not do anything stupid such as disregarding that kind of warning.) Edit: as for what can be inferred from passive sniffing, then this does not include the requested URL per se; however, a few things can be inferred: The intended server name (the "host name" part of the URL) will be known to the attacker. Modern browsers show it in cleartext as part of the Server Name Indication extension. The name also appears in the server's certificate, which is sent as cleartext as well. Encryption hides data contents, but not data length. The attacker can then infer the length of the URL, especially if he gets to observe several encrypted requests. Since lengths leak, the attacker can more or less see how many elements are downloaded by the client and their respective lengths, e.g. linked pictures. Depending on the site structure and whether the attacker can also browse the same site (as, e.g., another user), then he may figure out with great precision what the target user is actually browsing.
[ "stackoverflow", "0047861568.txt" ]
Q: Evaluation in dplyr::case_when() Following an example given in the dplyr::case_when() documentation: x <- 1:50 case_when(x %% 35 == 0 ~ "fizz buzz", x %% 5 == 0 ~ "fizz", x %% 7 == 0 ~ "buzz", TRUE ~ as.character(x)) I expect that the number 35 will produce "buzz" but it produces "fizz buzz" My reasoning is that case_when() evaluates all statements one by one regardless if a previous one is true or not (since it does evaluate TRUE ~ as.character(x) which is the last one) and that 35 %% 7 is obviously 0. What am I missing? A: case_when() evaluates all statements one by one regardless if a previous one is true or not (since it does evaluate TRUE ~ as.character(x) which is the last one) This is misleading, the output of case_when() is based on the first statement that is true. TRUE ~ as.character(x) means that if x is not divisible by 5 or 7 then then x will be returned as a string ie for x = 5, "5" will be returned. If x is divisible by 5 or 7, casewhen() does not evaluate subsequent cases. "fizz" and "buzz" are not passed to as.character(x) and they do not have to be because they are already character strings.
[ "stackoverflow", "0056792374.txt" ]
Q: How to derive a shapeless op which acts on an HList of a specific subtype I have tried to create a shapeless op which acts on an HList of objects of a given type. However, I can't figure out how to make it work on an HList of objects which are a subtype of that object. Here is an example: trait Transform[I, O] { def f: I => O } trait Transformer[I, TH <: HList] { type Out <: HList def transform(input: I, transforms: TH): Out } object Transformer { type Aux[I, Transforms <: HList, Out0] = Transformer[I, Transforms] { type Out = Out0 } def apply[I, Transforms <: HList](implicit transformer: Transformer[I, Transforms]): Aux[I, Transforms, transformer.Out] = transformer implicit def hnilTransformer[I]: Aux[I, HNil, HNil] = new Transformer[I, HNil] { type Out = HNil override def transform(input: I, transforms: HNil): HNil = HNil } implicit def hconsTransformer[I, O, TIn <: HList, TOut <: HList] (implicit t: Transformer.Aux[I, TIn, TOut]): Aux[I, Transform[I, O] :: TIn, O :: TOut] = new Transformer[I, Transform[I, O] :: TIn] { type Out = O :: TOut override def transform(input: I, transforms: Transform[I, O] :: TIn): Out = { transforms.head.f(input) :: t.transform(input, transforms.tail) } } } def applyTransforms[I, TH <: HList](transforms: TH)(input: I) (implicit transformer: Transformer[I, TH]): transformer.Out = { transformer.transform(input, transforms) } val double = new Transform[Int, Int] { def f = _ * 2 } val int2Str = new Transform[Int, String] { def f = _.toString } applyTransforms(double :: int2Str :: HNil)(4) // shouldBe 8 :: "4" :: HNil trait SubTransform[I, O] extends Transform[I, O] val doubleSub = new SubTransform[Int, Int] { def f = _ * 2 } val int2StrSub = new SubTransform[Int, String] { def f = _.toString } applyTransforms(doubleSub :: int2StrSub :: HNil)(4) // fails to compile The first applyTransforms compiles successfully but the second fails with the error: ShapelessSpec.scala:124: could not find implicit value for parameter transformer: Transformer[Int,shapeless.::[SubTransform[Int,Int],shapeless.::[SubTransform[Int,String],shapeless.HNil]]] applyTransforms(doubleSub :: int2StrSub :: HNil)(4) I suspect the problem is with the hconsTransformer but I can't work out why this shouldn't be in scope for SubTransforms. A: Modify your recursion step if you want this to work with subtypes of Transform implicit def hconsTransformer[I, O, TIn <: HList, TOut <: HList, X] (implicit t: Transformer.Aux[I, TIn, TOut], ev: X <:< Transform[I, O]): Aux[I, X :: TIn, O :: TOut] = new Transformer[I, X :: TIn] { type Out = O :: TOut override def transform(input: I, transforms: X :: TIn): Out = { transforms.head.f(input) :: t.transform(input, transforms.tail) } } or make Transformer contravariant with respect to TH trait Transformer[I, -TH <: HList] { ...
[ "stackoverflow", "0026372847.txt" ]
Q: Any reason to not use existing NSCoding methods to implement NSCopying Is there a reason that given a class that implements NSCoding that the implementation of copyWithZone: shouldn't be implemented using this pattern: -(instancetype)copyWithZone:(NSZone *)zone{ return [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:self]]; } A: Just efficiency — the encoding/decoding cost and the total memory footprint. Suppose you had an object with four immutable instance variables. If you implement a custom copy then you'll allocate one extra instance of that object, then give it ownership of all four instance variables. If you encode and decode it then there'll be the processing cost of the two-way serialisation and you'll end up with new copies of each of the instance variables.
[ "philosophy.stackexchange", "0000051567.txt" ]
Q: Confused by Spinoza's Use of Substance as Infinite Ethics 1 Proposition 8 states that "Every substance is necessarily infinite", but in Scholium 2 he states: "there exists only one substance of the same nature. I'm confused by him saying "every" substance and then saying there exists "only one substance", those two contradict one another don't they? In what way is substance infinite according to proposition 8? A: THE PROBLEM I see the problem : 'every' = 'all' or 'each' but neither term applies if there is only one. The Latin is : Omnis substantia est necessario infinita. On the surface it would have been better, more intelligible, if Spinoza had said something like 'Substance as such is infinite', which would be perfectly consistent with there being only one substance. Something definitely needs explanation. There are two main possibilities : 1 Spinoza has simply made a logical mistake 2 Spinoza is moving from one sense of substance to another and P8 is caught in the transition. It is perfectly possible that Spinoza simply has made a logical mistake but I prefer the second explanation, which I think more likely. SUBSTANCE : SHIFT OF SENSE A plurality of substances was a perfectly standard idea in Aristotle. Very roughly a substance (ousia) was whatever qualities, quantities, and the other categories inhered in as their support. There could not, for instance, be a quality unless it was a quality of a substance; it could not exist on its own but needed to be a quality of something, namely a substance. Aristotle assumed that there were indefinitely many substances. Descartes held that there was ultimately and strictly only one substance, namely God, but granted de facto substance-status to mind and matter. This is the working idea from which Spinoza starts. There was general agreement (though Locke had his difficulties) that substances exist. Hence he is ready to talk of 'two substances' in I. P2. But the assumption of a plurality of substances is only a concession to the standard way of talking. There is a pointer to his own view of the single substance in I.P5 but he is still working with the standard view in I. P8. Then in Scholium [Note] 2 to I. P8 he reveals his hand, develops his own distinctive position : 'there exists only a unique substance of the same nature' (Spinoza, Ethics, tr. G.H.R. Parkinson, Cambridge : CUP, 2000, 80) - substantiae existentiam ... eiusdem naturae. So how do we get to this point ? We need to go back to I.P7 : 'It belongs to the nature of substance to exist' (Parkinson, 78). Its existence follows from its nature, and that nature is to be self-dependent, self-contained; to be in Spinoza's language 'that which is in itself' (I, Def, 3 : quod in se est; Parkinson, 75). It cannot be self-dependent and self-contained if there is another substance which can act as an external cause or limitation. Hence 'there exists only a unique substance of the same nature'. 'Of the same nature' : an enigmatic little addendum. I think what he means is that a substance has or supports attributes. There is, Spinoza thinks, an infinity of attributes I. Prop. 11; Parkinson, 82) of which we are acquainted with only two, namely thought and extension (II, Axiom 5; Parkinson, 114). 'Of the same nature' means that there could not be two substances having or supporting the same attributes (attributes of the same nature), else one substance could act as an external cause or limitation in regard to the other in respect of those attributes. But since Spinoza's substance has an infinity of attributes, i.e. all the attributes there are, the existence of a second - any second - substance is impossible on pain of its acting an an external cause or limitation. On the matter of substance's being infinite, I think infinity follows from the infinity of its attributes, and (more basically) from the one substance's nature as self-contained and unlimited by any other substance. This makes it all-inclusive, hence in one sense infinite. It's no easy task to make full sense of Spinoza. I have simply offered the best I can. REFERENCES Spinoza, Ethics, tr. G.H.R. Parkinson, Cambridge : CUP, 2000. See Introduction, 55-7. Joel I. Friedman, 'An Overview of Spinoza's "Ethics"', Synthese, Vol. 37, No. 1, Spinoza in Modern Dress (Jan., 1978), pp. 67-106. William Charlton, 'Spinoza's Monism', The Philosophical Review, Vol. 90, No. 4 (Oct., 1981), pp. 503-529. Stuart Hampshire, Spinoza, London : Penguin, 2007.
[ "stackoverflow", "0031356381.txt" ]
Q: how to search an Id using hibernate query by example? hi i have the following class public class Label { private Long TableId; private Long Id; private String LabelName; //getters and setters for corresponding fields } i was supposed to search on multiple fields dynamically i came across hibernate query by example construct my code looks like some thing Label bean =new Label(); if(Id!=null) { bean.setId(Id); } if(LabeName!=null) { bean.setLabelName(LabelName) } System.out.println(bean.toString()); Example exampleObject=Example.create(bean).ignoreCase(); criteria=currentSessionObj.createCriteria(Label.class).add(exampleObject); retObjects=criteria.list(); when i'm searching on LabelName field i'm getting the exact response when when i tried to search by id i'm getting unexpected results i have goggled many forums i couldn't get what i want some one please help me how to deal with this issue? A: From the documentation Version properties, identifiers and associations are ignored. By default, null valued properties are excluded.
[ "stackoverflow", "0021198123.txt" ]
Q: RVM use gemset not creating .ruby-version and .ruby-gemset Facts I created project1 and ran the following code: rvm use ruby-2.1.0@project-gemset Then I moved out of the directory and created project2, running the same rvm code. When I run rvm gemset list I see that it is using the same gemset as project1. Question Why aren't .ruby-version and .ruby-gemset being created for project2? I can't see them when I run a ls -a on project2's path. Thank you in advance. A: to create the files you need to add flag: rvm use ruby-2.1.0@project-gemset --ruby-version or explicitly create it: rvm use ruby-2.1.0@project-gemset rvm rvmrc create .ruby-version
[ "codereview.stackexchange", "0000078325.txt" ]
Q: Creating a TCP Listener and receiving data I am very new to network programming and I'm thinking I have probably misconstrued the creation of an appropriate TCP listener. The code I have below works perfectly, but I have a feeling it's a "hack and slash" miracle and could come apart easily when set into my production environment. What can I do to improve this receive message? Objective The application should be able to receive a string and parse it into an xml string. Later, after a set of validation and data collection is completed, a response will be sent back to the client. Receive Message private static void ReceivePortMessages() { int requestCount = 0; tcpListener.Start(); Debug.Print(" >> Server Started"); tcpClient = tcpListener.AcceptTcpClient(); Debug.Print(" >> Accept connection from client"); while (true) { try { requestCount = requestCount++; NetworkStream networkStream = tcpClient.GetStream(); byte[] bytesFrom = new byte[10025]; networkStream.Read(bytesFrom, 0, (int)tcpClient.ReceiveBufferSize); Stopwatch sw = new Stopwatch(); sw.Start(); string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom); dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0")); XmlDocument xm = new XmlDocument(); xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient)); XmlElement root = xm.DocumentElement; string rootName = root.FirstChild.Name; RouteInboundXML(rootName, dataFromClient, sw); } catch (ArgumentOutOfRangeException ex) { Debug.Print("ReceivePortMessages: Remote client disconnected. " + ex.ToString()); tcpClient.Close(); tcpListener.Stop(); ReceivePortMessages(); return; } catch (Exception ex) { Debug.Print("ReceivePortMessages: " + ex.ToString()); tcpClient.Close(); tcpListener.Stop(); ReceivePortMessages(); return; } Debug.Print(" >> exit"); } } Send Message private void SendReply(string reply) { try { NetworkStream networkStream = _TcpClient.GetStream(); string serverResponse = reply; Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse); networkStream.Write(sendBytes, 0, sendBytes.Length); networkStream.Flush(); Debug.Print(" >> " + serverResponse); } catch (ArgumentOutOfRangeException ex) { Debug.Print("SendReply: Remote client disconnected. " + ex.ToString()); _TcpClient.Close(); _TcpListener.Stop(); ReceivePortMessages(); return; } } A: A common convention is to prefix class members with _ so it's easier to see what a local variable is and what's a class member. In your case it would be _tcpClient or even _TcpClient. This is a static method which indicates that it's possibly part of a static class. This is almost always a bad idea. static means it's global and global state is bad because it can get you into all kinds of trouble once your program grows in complexity. You have a StopWatch but you're not actually using it. I assume you use the Substring because the buffer is larger than the actual data received so you find the end by looking for the first \0. GetString() provides an overload which allows you to specify offset and length so this becomes unnecessary. MSDN stipulates that you must close the NetworkStream once you are done with it because the client will not release it. Given that streams are IDisposable it would be best wrapped in a using block. TcpClient is IDisposable as well so should be wrapped in a using block to make sure it gets cleaned up properly. The method is recursive and there is no way to bail out because in case of error it calls itself again. This means your call stack is growing indefinitely and will fall over at some point. Each call will also allocate a new receive buffer every time. A while loop with a break condition would probably be the better choice. So in total the refactored code could look like this: private static void ReceivePortMessages() { byte[] receiveBuffer = new byte[10025]; while (!_QuitProcessing) { int requestCount = 0; _TcpListener.Start(); Debug.Print(" >> Listener Started"); using (var tcpClient = _TcpListener.AcceptTcpClient()) { Debug.Print(" >> Accepted connection from client"); using (var networkStream = tcpClient.GetStream()) { while (!_QuitProcessing) { try { requestCount = requestCount++; var bytesRead = networkStream.Read(receiveBuffer, 0, (int)tcpClient.ReceiveBufferSize); if (bytesRead == 0) { // Read returns 0 if the client closes the connection break; } string dataFromClient = System.Text.Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead); XmlDocument xm = new XmlDocument(); xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient)); XmlElement root = xm.DocumentElement; string rootName = root.FirstChild.Name; RouteInboundXML(rootName, dataFromClient, sw); } catch (Exception ex) { Debug.Print("ReceivePortMessages: " + ex.ToString()); break; } } } Debug.Print(" >> stopped read loop"); } _TcpListener.Stop(); } } It's still not ideal because the Read will block unless data is there to be received or the connection is closed. So if the other side stops sending data but keeps the connection alive you still have no nice way to bail out.
[ "worldbuilding.stackexchange", "0000080796.txt" ]
Q: Create a disease that can easily be cured by adopting a custom from another culture I have a world with nations with culture/magic tied to each element. The Fire Nation was in the middle of invading the Earth nation when a disease starts to spread rapidly through their nation weakening it's people and indirectly putting a halt to their invasion. The disease doesn't seem to affect the other nations nearly as badly, despite originating in Earth, leading to the commonly claim that it is a punishment from god sent to stop the invasion and only able to affect Fire and 'unworthy' citizens. My intent is for the disease to be a normal non-magical disease, and to be eventually cured by a protagonist, call him Bob. The disease affects Fire so much worse because the other nations have protections against the disease that Fire lacks. Water has healing magic to cure the disease and Air is too well isolated to have every been exposed to it. More importantly I would like Earth citizens to have some aspect of their lifestyle or culture that coincidentally protects them from the disease. I'm looking for a believable disease that can be thwarted by something Earth citizens usually do, and which Fire can adopt quickly to stop the spread of the disease and ideally help those already sick to recover from it. Bob is trained in medicine, herbs, and mundane healing, plus having a bit more scientific view to medicine in a world where people tend to believe more in magic and mysticism. He also has learned Water's magical healing. Few know both healing styles and previous hostilities mean there are no other Water healers willing to help Fire. Water magic also helps him 'sense' illness, which he can use to identify what mundane treatments to use when medicine will work better then magic. He has spent some weeks/months traveling & healing individuals using his Water magic already and has a good familiarity with the disease when he ends up in a Earth city currently occupied by Fire where the disease is currently spreading to Fire, but few Earth, citizens. He also notices that the few Fire citizens who have started to adopt Earth customs also seem less affected by the disease Curious why this is tries to figure out what is protecting Earth in hopes of discovering a non-magical cure. I want him to be able to figure out something that would work within a relatively short time (say few months at max, sooner the better). To help justify why he can do it so quickly when other's haven't I thought he would be aided by the combination of scientific medicine with Water magic allowing him to more thoroughly 'sense' differences between Earth/Fire/Sick/Healthy citizens to identify what is different, along with most citizens accepting the divine explanation and thus not looking for a mundane cure. The disease is also only been a problem for a little while, say 5-8 months by the time he cures it, so there hasn't been that much time to discover a cure. Still, justifying why he is able to find a solution so fast without someone else stumbling upon it would be great! While I doubt I'll get everything Ideally I'd like a disease and cure that fit as many criteria as possible: Scientifically believable to exist the disease doesn't kill very fast, but renders one so weak they struggle to do daily tasks and is not quickly recovered from The cure can help those already infected recover, not just prevent new infections. cure can be discovered fast by Bob but not be so obvious someone else should have guessed it. Fire can adopt the cure quickly such that they can be back up to something close to fighting strength in a reasonable quick time, again a few months, The common peasants of Fire can benefit from this cure even if Fire's government puts little effort into helping them, ie not a large logistical overhead to enacting it. Doesn't draw the attention of Fire's leaders to Bob, who he's hiding from, Fire citizens often are willing not to report the guy helping them. My original idea was that there is a staple food item of Earth that happens to provide some nutrient or even bacteria that helps fight off the disease (think a yogurt grown from a bacteria with some antibacterial property particularly effective against the disease?). My biggest issue with the idea is the logistics of it, It's likely the food would have to be stolen from Earth to get enough to treat Fire's citizens, and with limited supplies of food this means starving Earth and Fire likely only bothering to get the cure to the rich and military and not to the peasants that Bob is actually most interested in curing. I don't think Bob would reveal the secret if he knew it wouldn't help the common man and would lead to more war and starvation for Earth citizens. If the food stuffs was something that wasn't hard to get hold of in sufficient quantity to cure folks without Fire's stealing the food that would work, but why would Fire have enough in it's own borders to treat everyone but not have poor citizens already eating it? A: Smoking. This was the plot of a science fiction story back in one of the pulps during (I estimate) the early 60s. In this case, the organism is a slow-multiplying pneumococcus bacterium which itself is essentially a minute partly-magical parasite which is stimulated by excess levels of fire magic, which obviously appear in the bodies of the Fire nation. Smoking works because smoke is the byproduct of fire, and so tends to absorb Fire energy, essentially smothering the parasite. Tobacco exists in the Fire nation, but smoking has never taken hold since in the long run it is extremely injurious to the Fire nation inhabitants. But it works more quickly on the parasite than on people, so smoking kills it and then the patient stops smoking. The whole process is similar to chemotherapy, whose agents are themselves toxic, only more to cancer cells than to others. The effect was noted when earth POWs were allowed to smoke, and in the process some of their guards were seen to come down with the disease but then, in defiance of all experience, recovered. Even better, the guards were assigned to be guards because they were in early stages of the disease's debilitation and not suited for more strenuous duties. Guard duty is not physically demanding, so affected soldiers could perform the duty for a while. Then, of course, they started recovering. Bob was part of the guard unit, but was the only one to make the connection. With the collapse of the invasion, the influx of earth POWs has ceased. With no new POWs bringing cigarettes the POW population has had to quit cold-turkey. So the cures were only a transient phenomenon, and the government is in the dark about what smoking can do. This gives Bob the position of being the only one who has figured it out. A: Necator americanus (Hookworm) and latrines. Up until the early 1900s, people in the Southern United States would just go #2 by going out to the field and squatting. The problem is that there are parasites, namely hookworm, that can crawl out of old poo and reinfect people by burrowing into their feet when they go out to the same area, to poop again or maybe do some farm work. This is why using "night-soil" as fertilizer is an extremely bad idea. While a few hookworms aren't that bad, too many can cause: severe lethargy nausea loss of appetite diarrhea abdominal pain Enter the solution: a pit latrine. Dig a hole deep enough so the hookworms can't find another foot to invade before they die, and problem solved. There's a Radiolab piece on it. For your point where you want the disease to clear quickly, hookworms have a months-to-years-long residency in the body, but there are other soil-transmitted diseases. Or your hookworm could just have quicker turnover. Also, in your Fire Nation, maybe they could burn/boil/heat (sterilize/pasteurize) their poop if they really wanted to use it as fertilizer. Maybe there's a zoonotic parasite present in other animals' poo that could cause a more transient infection and where there's more of a reason to reuse the manure as fertilizer. Maybe just in an animal that the Fire Nation uses as a beast of burden/livestock? A: Scurvy from Lind's A treatise on the scurvy. The following relation is no less curious. A sailor in the Greenland ships was so over- run and disabled with the scurvy, that his companions put him into a boat, and sent him on shore ; leaving him there to perish, without the least expediation of a recovery. The poor wretch had quite lost the use of his limbs -, he could only crawl about on the ground. This he found covered with a plant, which he, continually grasing like a beast of the field, plucked up with his teeth. In a short time he was by this means perfedtly re- covered 'y and, upon his returning home, it was found to be the herb scurvygrass. This is a disease that meets all your criteria. The question: why did Fire people not suffer from scurvy before this event? The answer: they did, but it got worse. Mild scurvy was probably endemic in winter months in Northern Europe. Your fire people could be indifferent to vegetables most of the time but then during the war got away from greens and vegetables entirely, and so came down with the scurvy. You can die of scurvy but you can also bounce back fast. Nutritional diseases were hard for people back in those days. They were mixed in with lots of other diseases. Pellagra is another great example: maize is a wonderful crop but once the Italians began living on it they developed rampant pellagra. I read an account of a mid 19th century Mexican scientist who attending a meeting on pellagra. He pointed out that the Italians were preparing their maize incorrectly: it should be mixed with lime. Of course he was roundly ignored. But that is why the Mexicans did not get pellagra over the centuries they lived on maize - lime releases the niacin.
[ "math.stackexchange", "0002126842.txt" ]
Q: Find the joint density of $Z$ and $R$ where $R^2=X^2+Y^2+Z^2$ A point $(x,y,z)$ is picked uniformly at random inside the unit ball. Find the joint density function of $Z$ and $R$, where $R^2=X^2+Y^2+Z^2$. First, I find the joint density of $Y$ and $Z$, that is $f_{Y,Z}(y,z)=\frac{3}{2\pi}\sqrt{1-y^2-z^2}$ with $Y^2+Z^2\leq R^2$. Let $Y=\pm\sqrt{R^2-Z^2}$ and $W=Z$. The Jacobin determinant is $$J=\begin{vmatrix}1&0\\\frac{R}{\sqrt{R^2-Z^2}}&\frac{Z}{\sqrt{R^2-Z^2}}\end{vmatrix}=R/\sqrt{R^2-Z^2}$$ Then, $$f_{R,Z}(r,z)=f_{Y,Z}(\sqrt{1-z^2},z)|J|=\frac{3\sqrt{1-(1-z^2)-z^2}}{4\pi}\left(\frac{r}{\sqrt{r^2-z^2}}\right)$$ I think I miss something. Can someone give me a hint or suggestion to work on this problem? Thanks A: Let $|z|\le r$. The probability that $R\in[r,r+dr]$, $Z\in [z,z+dz]$ is $\frac{3}{4\pi}$ (total volume$^{-1}$) times the volume of the corresponding set. The latter is a belt cut from the sphere of radius $r$ and thickness $dr$ by the plane $Z=z$ of thickness $dz$. The volume is equal to the area of the corresponding spherical belt, i.e. $2\pi \sqrt{r^2-z^2} \cdot dz$ times the "height" of this belt, which, by simple geometry, is equal to $\frac{r\, dr}{\sqrt{r^2-z^2}}$ (I hope the picture explains it well); so the volume is $2\pi r\cdot dr\,dz$. Thus, the probability is $\frac{3r}{2}dr\,dz$, which confirms your formula for density.
[ "stackoverflow", "0017504570.txt" ]
Q: Creating simply image gallery in Python, Tkinter & PIL So, I'm on simple project for a online course to make an image gallery using python. The thing is to create 3 buttons one Next, Previous and Quit. So far the quit button works and the next loads a new image but in a different window, I'm quite new to python and GUI-programming with Tkinter so this is a big part of the begineers course. So far my code looks like this and everything works. But I need help in HOW to make a previous and a next button, I've used the NEW statement so far but it opens in a different window. I simply want to display 1 image then click next image with some simple text. import Image import ImageTk import Tkinter root = Tkinter.Tk(); text = Tkinter.Text(root, width=50, height=15); myImage = ImageTk.PhotoImage(file='nesta.png'); def new(): wind = Tkinter.Toplevel() wind.geometry('600x600') imageFile2 = Image.open("signori.png") image2 = ImageTk.PhotoImage(imageFile2) panel2 = Tkinter.Label(wind , image=image2) panel2.place(relx=0.0, rely=0.0) wind.mainloop() master = Tkinter.Tk() master.geometry('600x600') B = Tkinter.Button(master, text = 'Previous picture', command = new).pack() B = Tkinter.Button(master, text = 'Quit', command = quit).pack() B = Tkinter.Button(master, text = 'Next picture', command = new).pack() master.mainloop() A: Change image by setting image item: Label['image'] = photoimage_obj import Image import ImageTk import Tkinter image_list = ['1.jpg', '2.jpg', '5.jpg'] text_list = ['apple', 'bird', 'cat'] current = 0 def move(delta): global current, image_list if not (0 <= current + delta < len(image_list)): tkMessageBox.showinfo('End', 'No more image.') return current += delta image = Image.open(image_list[current]) photo = ImageTk.PhotoImage(image) label['text'] = text_list[current] label['image'] = photo label.photo = photo root = Tkinter.Tk() label = Tkinter.Label(root, compound=Tkinter.TOP) label.pack() frame = Tkinter.Frame(root) frame.pack() Tkinter.Button(frame, text='Previous picture', command=lambda: move(-1)).pack(side=Tkinter.LEFT) Tkinter.Button(frame, text='Next picture', command=lambda: move(+1)).pack(side=Tkinter.LEFT) Tkinter.Button(frame, text='Quit', command=root.quit).pack(side=Tkinter.LEFT) move(0) root.mainloop()
[ "stackoverflow", "0046072283.txt" ]
Q: Methods, destroy and fetch of backbone.js are not supported in Adobe aem cq6.3 These backbone.js methods (fetch and destroy) were working fine in adobe aem CQ5.6, now I have updated to CQ6.3. Functionalities are not working now. fetch method - fetch({ url: contextPath+"/bin/servletpath/updatemessage", data: data, add: true, cache: false, success: (successCallback ? successCallback : function(){ self.allowRequests = true; }), error: (errorCallback ? errorCallback : function(){ self.allowRequests = true; }) }); A: Working fine by adding complete as below. complete: function(response){ self.allowRequests = true; }
[ "stackoverflow", "0060538477.txt" ]
Q: How to show style="display:none" div element permanently? I want to show a display:none element on a click of anchor tag using jQuery show() function. But it's showing the div element for a moment and then vanished I used return false and preventDefault functions but it stops the redirection of anchor tag to a certain page. How I can solve this? <div id="assetlist" style="display:none"> @{ Html.RenderPartial("~/Views/Asset/_Asset_List.cshtml"); } <!-- /.sidebar-menu --> </div> <script> $(document).ready(function () { $(".asset_managment").click(function(){ $("#assetlist").show(); }); }); </script> <li class="nav-link" > <a href="@Url.Action("Index", "Asset")" class="asset_managment"> <img class="img_position" src="@Url.Content("~/admin-lte/img/asset_managment_icon.png")" width="50" height="50" /> Asset Managment </a> </li> A: Could you just try: $(document).ready(function () { $(".asset_managment").click(function(){ $("#assetlist").attr('style', 'display:block !important'); }); }); this is just gonna overwrite the display property of your div's inline style. hope this helps
[ "stackoverflow", "0046385291.txt" ]
Q: Trying to load a file into main activity's onCreate What I'm trying to do is test if the file "turma.dat" already exists, if it exists I just open it, if it does not exist, I create a new file and save it. When I start the app the first time it creates the file, but every time I start it again the file is created in white. MainActivity: override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) var turma : Turma var file = File("turma.dat") if(file.exists()) { turma = this.abrirArquivo() }else{ turma = Turma() ArquivoUtils(turma, this.applicationContext) } Method abrirArquivo: @Throws(IOException::class, ClassNotFoundException::class) fun abrirArquivo(): Turma { val fis = this.applicationContext.openFileInput("turma.dat") val ois = ObjectInputStream(fis) return ois.readObject() as Turma } Class ArquivoUtils: (Responsible for receiving a Turma object add to a file and save) class ArquivoUtils internal constructor( var turminha: Turma, var context : Context) { internal val fos = this.context.openFileOutput("turma.dat", Context.MODE_PRIVATE) internal val oos = ObjectOutputStream(fos) init { this.salvarArquivo() this.closeFile() } @Throws(IOException::class) private fun salvarArquivo() { oos.writeObject(turminha) this.closeFile() } @Throws(IOException::class) fun closeFile() { oos.close() } A: file.exists() is probalby not looking where you would expect. Methods openFileInput and openFileOutput work on files in an application private location. When you declare file you say... var file = File("turma.dat") Instead use something like... var file = File(this.filesDir, "turma.dat") See if that helps. Read Saving Files to get a better grasp of how to work with files in Androidl By the way, use a debugger and step through and verify that file.exists returns what you expect. (If you don't know how to use the debugger, then start by learning how).
[ "stackoverflow", "0010621009.txt" ]
Q: Struts2 prepare method can not be handled When I use implements Preparable and override prepare() method and if I get any problem in preparation I set an action error with com.opensymphony.xwork2.ActionSupport addActionError. After prepare method sets the error message I want to process this message in the real initialize method. public class TestClass implements Preparable { public void prepare() { // ... if (error) { addActionError("error"); } } public String initializeAndDo() { String target = ERROR; // ... return target; } } When I debug it, it never reaches initiliazeAndDo method and returns INPUT automatically. struts.xml : no intercepter in action block. <action name="action_name" method="initializAndDo" class="TestClass"> <result name="input">/pages/input.jsp</result> <result name="error">/pages/error.jsp</result> </action> Is there any idea? A: Sure; this is normal behavior. If there are errors, the "workflow" interceptor will see that, and forward to the "input" result. If you don't want to have your (non-standard) workflow interrupted, don't set an error in the prepare() method. One alternative would be to set a flag in prepare() that could be checked in initializeAndDo method--this would keep "workflow" from short-circuiting the requst.
[ "stackoverflow", "0012154567.txt" ]
Q: struts2: display result jsp in the main/calling jsp I have a one main jsp (file upload jsp screen) which has form elements. User will select the file to upload, also set some other elements (such as checkboxes, radios, etc.) as per the requirement and then finally submit the form. After uploading the result of the process is formulated into a table of a different JSP (say result.jsp). Right now the result.jsp is displayed independently on the screen. What I want is to display the result.jsp in the same parent.jsp (having form elements) and not on a separate independent page. Can anyone help me with this? struts.xml: <action name="commonDataImportAction_*" class="commonDataImportAction"> <result name="VIEW"> /jsp/CommonDataImportLog.jsp (result.jsp) </result> <result name="input">/jsp/CommonDataImport.jsp (parent.jsp) </result> </action> Update: Screenshot of the screen, how I want it: http://img802.imageshack.us/img802/7141/screenzgk.jpg A: If you are submitting the page in simple manner the way Struts2 submit button works than one simple solution is to create only a single page which also contains the layout of your result.jsp, but you can hide that part initially (before the page submit). On successful page submission you can set a value (say a Boolean) in your action class and based on this can show that section,since your are already done with file upload so you can set those values in your action class which are needed to show the values in result.jsp. For me that is a simple yet efficient approach. Alternatively if you are going with the Ajax based file upload than there are many ways to do this like Send back HTML section from the Action. You can even send the name of JSP file and can include it in to the current JSP at runt time. Send JSON data from action and parse the JSON using Jquery to build view
[ "stackoverflow", "0050590373.txt" ]
Q: How to select from a list of columns? SQL Server I have a list of columns attained through a SQL query. SELECT t.name AS table_name, SCHEMA_NAME(schema_id) AS schema_name, c.name AS column_name FROM sys.tables AS t INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID ORDER BY table_name Now for each column, I want to query some information about the column and put them together in a table. Here is the query I would run for a single column, for example. Select Substring(col1, 1, 1) letter, Count(Substring(col1, 1, 1)) cnt From tbl Group By Substring(col1, 1, 1) What this subquery does is that it attains the count of the first character of records in a column. So for example, there may be 6 records in col1 that start with the letter 'a', 15 records in col1 that start with the letter 'b', etc. How do I combine these two queries together into one table so I get something like... Table_Name, Column_Name, letter, cnt tbl, col1, a, 6 tbl, col1, b, 15 tbl, col2, a, 5 ... A: is this useful? DECLARE @query VARCHAR(Max) SELECT @query=COALESCE(@query + ' union all ', '') + CAST('SELECT ''' +TABLE_SCHEMA+''' As [Schema],'''+TABLE_NAME+''' As TableName,'''+COLUMN_NAME+''' As ColumnName, Substring(['+COLUMN_NAME+'],1,1) letter,COUNT(Substring(['+COLUMN_NAME+'],1,1)) cnt FROM '+TABLE_SCHEMA+'.'+TABLE_NAME+ ' Group by Substring(['+COLUMN_NAME+'],1,1)' AS VARCHAR(MAX)) FROM INFORMATION_SCHEMA.COLUMNS WHERE DATA_TYPE IN('varchar','char','nvarchar') --SELECT @query Exec(@query)
[ "stackoverflow", "0042291581.txt" ]
Q: Downgrade my react-native-cli version from 2.0.1 to 1.2.0 I wanted to downgrade my react-native-cli version from 2.0.1 to 1.2.0. This is because I have a react-native project which is my colleague running react-native-cli 1.2.0 without having any issue. So to do the debugging, i need to downgrade the version to check if this cause the error. A: If you have to install an older version of a package, just specify it npm install <package>@<version> For your case: npm install [email protected] EDIT If you have installed a version of it already uninstall by npm uninstall -g react-native-cli and do the above
[ "stackoverflow", "0012837134.txt" ]
Q: What is the difference between STATUS_STACK_BUFFER_OVERRUN and STATUS_STACK_OVERFLOW? I just found out that there is a STATUS_STACK_BUFFER_OVERRUN and a STATUS_STACK_OVERFLOW. What's the difference between those 2? I just found Stack overflow (stack exhaustion) not the same as stack buffer overflow but either it doesn't explain it or I don't understand it. Can you help me out? Regards Tobias A: Consider the following stack which grows downward in memory: +----------------+ | some data | | +----------------+ | growth of stack | 20-byte string | V +----------------+ limit of stack A buffer overrun occurs when you write 30 bytes to your 20-byte string. This corrupts entries further up the stack ('some data'). A stack overflow is when you try to push something else on to the stack when it's already full (where it says 'limit of stack'). Stacks are typically limited in their maximum size.
[ "ell.stackexchange", "0000190571.txt" ]
Q: I can't understand " do it in '', "come across", and " get something from" in this context Rumour has it that Smith and Wyatt aren't the best of friends. In fact, on the set they barely spoke to each other, though, this doesn't COME ACROSS in the film and they look like a great couple. Happy as Larry is a move away from the usual films Sonya makes - She is better known for roles in action films - but she has shown herself to be a capable comedy actress. However, I'm not sure this is the finest film to DO IT IN. Both men and women alike can GET SOMETHING FROM this film, but the romance angle is overplayed and the laughs are few and far between. A: In fact, on the set they barely spoke to each other, though, this doesn't COME ACROSS in the film and they look like a great couple "Come across" refers to the act of the couple barely speaking to each other. The article states that even though they barely spoke to each other on the set, the same couldn't be inferred if one watched the film itself. However, I'm not sure this is the finest film to DO IT IN "Do it in" refers to the actress being capable of doing comedy roles. The author of the article says that even though she has shown herself to be a capable comedy actress, Happy as Larry isn't the kind of film that reflects that talent of the actress. Both men and women alike can GET SOMETHING FROM this film, but the romance angle is overplayed and the laughs are few and far between. "Get something from" refers to the lessons/messages the viewers can take away from the film. The article states that the film has elements that will appeal to both the men and the women viewers alike.
[ "stackoverflow", "0016660012.txt" ]
Q: Mixing C with Objective C I'm a little confused as to whats going on in this snippet of example code. I am creating a property called 'processingGraph' of C struct 'AUGraph'. I then pass this struct to the Objective C method with [self createAUGraph:_processingGraph]; I then take this argument... - (void) createAUGraph:(AUGraph) graph { NewAUGraph (&graph); ... and create the struct. However this does not seem to create the struct at the property name '_processingGraph' as I think it should. Why is this? By passing in a struct to an objective C method, does it just create a copy? Which case, how would I pass a reference to a struct in a method? Full code: @interface AudioStepper () @property (readwrite) AUGraph processingGraph; @end @implementation AudioStepper - (id) init{ if (self = [super init]) { [self createAUGraph:_processingGraph]; } return (self); } - (void) createAUGraph:(AUGraph) graph { NewAUGraph (&graph); CAShow (_processingGraph); //no struct? } @end A: graph is not a pointer in your method, so it is getting copied to a new memory location, apart from the original variable. It is like passing in an int or float. This is what is called passing by value. The C method, however, is using pass by reference. It takes the pointer to graph rather than copying the value. Since this is an ivar, you can access the pointer to _processingGraph directly: - (void) createAUGraph { NewAUGraph (&_processingGraph); CAShow (_processingGraph); } Or, if you need to pass in different graphs at different times, you want the method to take a pointer to an AUGraph, use pass by reference: - (void) createAUGraph:(AUGraph*) graph { NewAUGraph (graph); // Since graph is now a pointer, there is no // need to get a pointer to it. CAShow (_processingGraph); } And call the method like so: [self createAUGraph:&_processingGraph]; While that fixes the arguments, be sure to read danh's answer below for a better way to create structs.
[ "bicycles.stackexchange", "0000054598.txt" ]
Q: Surly Trucker Disc Compatibility with Ryde Taurus Rims Is it possible to put these Rims (Ryde Taurus 21 Disc: 26', 21-559) on this frame (Surly Trucker Disc)? I just cannot find any hint at the Surly Trucker description, but since I am not a native and new to bikes I might have missed something. By the way, I want to use a Shutter Precision PD-8 hub but I think if the Ryde Taurus fits and I know the Shutter fits into the Ryde I can use it as long as the Ryde Taurus can be used. A: EDIT the wheel size for this bike model depends on the frame size! 26˝ wheels for frames 42, 46, 50–62 cm 700c (a.k.a. 28") wheels for frames 56–64 cm So you need first to make sure that your bike runs wheel size 26", as Ryde Taurus rims are 26". Having smaller wheels on a frame designed for bigger wheels is possible for disk brake systems, but it is not recommended unless you are certain (i.e. you have already tried it) you will be fine with changed (worsened) bike handling. The same web page, "Complete bike parts kit" tab lists both 29" and 26" wheels as options, depending on frame size: Tires (26˝) Continental Tour Ride, 26 x 1.75" Tires (700c) Continental Contact, 700c x 37mm The rims you mention have 19 mm inner width: These rims should be compatible with the original 26" × 1.75" tires. Note that you asked about frame vs wheel rims compatibility. You also mention hubs that you want to use; frame/hub, fork/hub and hub/rim compatibility issues are different question. In particular, the chosen rim should have the same number of spoke holes as the hub has, and that hub comes with hole counts varying from 28 to 36.
[ "gaming.stackexchange", "0000361689.txt" ]
Q: What is the name of this music from the Grand Theft Auto Online Christmas tree? The bunker Christmas tree in Grand Theft Auto Online plays music. I can recognize Deck the Halls and Jingle Bells, but I don't recognize the third one. It's instrumental music only, which you can hear at 27 seconds in this YouTube Video: A: It is The Boar’s Head Carol, a 15th century English Christmas carol. Wikipedia has samples here: A Carol Brynging in the Bore's Heed The Boar's Head Carol
[ "stackoverflow", "0013048506.txt" ]
Q: Determine time required to start a program in GNU/Linux? In GNU/Linux, is it possible to determine the time required to start a program? Where "start" is defined as having executed load_elf_binary() (or some other applicable function). In particular I want to write a program that can do this. I.e. a program, given another program as input, and then determine that time, with as high accuracy as possible. Edit: Forgot to specify the hardware is x86-64. A: NASA uses 386 and older hardware because they are deterministic, caches and super-scalar technologies make 486s and newer processors non-deterministic. It is thus non-trivial to determine the startup time. Articles of interest: http://science.slashdot.org/story/10/09/27/1333204/the-ancient-computers-powering-the-space-race http://drum.lib.umd.edu/bitstream/1903/891/2/CS-TR-3768.pdf http://pages.cs.wisc.edu/~markhill/racey.html http://en.wikipedia.org/wiki/Nondeterministic_algorithm http://homes.cs.washington.edu/~tbergan/papers/wodet11-hammer.pdf
[ "tex.stackexchange", "0000503558.txt" ]
Q: Shrinking a cell including citation and using bullet points in tables I have the following table and I want to modify two things: 1) Shrink the first column by possibly using two or more lines for the citation 2) Using bullet points for the last column content. \begin{table*}[th!] \center \scriptsize \caption{Systematic literature review.\label{tab:lit_rev}} \begin{tabularx}{\textwidth}{lllllX} Article & Methodology & Model objective & Decision phase & Vehicle Types & Features\\ \hline \cite{ma2017designing} & \begin{tabular}[c]{@{}l@{}}Linear\\ programming\end{tabular} & \begin{tabular}[c]{@{}l@{}}Minimize traffic\\ on arcs\end{tabular} & \begin{tabular}[c]{@{}l@{}}Operational,\\ rolling horizon\end{tabular} & SAV & \begin{tabular}[c]{@{}l@{}}No carpooling\\ Parking at any node\\ Simulated traffic congestion\\ Flexible departure times\end{tabular} \\ \hline \cite{hyland2018dynamic} & \begin{tabular}[c]{@{}l@{}}Agent-based\\ simulation\end{tabular} & \begin{tabular}[c]{@{}l@{}}Minimize miles\\ driven and\\ client wait times\end{tabular} & \begin{tabular}[c]{@{}l@{}}Operational,\\ rolling horizon,\\ real-time\end{tabular} & SAV & \begin{tabular}[c]{@{}l@{}}No carpooling\\ No info on parking\\ No traffic congestion\\ Flexible pick up time\\ Fixed number of AVs per day\end{tabular} \\ \hline \end{tabularx} \end{table*} Below is a screenshot to see how it currently looks like. For my modification 1, I couldn't find a proper way. If I used a numbered in-text citation, I would not have such an issue but it is not an option. For the second one, I found some useful links such as this and that but they require using tabular instead of tabularx. A: Here is a suggestion based on assumptions and gesses about the documentclass and citations used. I have used a left aligned p type column for the first column as well as for the last column. To get the bullet points in the last column, I have defined a new environment tabitem with the help of the enumitem package. Lastly, I have removed teh nested tabulars in columns 2-4 and used left aligned X txpe columns for them. As you can see from the following screenshots and example, you could even increase teh font size from \scriptsize fo \footnotesize of even \small and still fit the table nicely into the textwidth. If your table should becoome too long for a single page, you might want to have a look at the xltabular package. \documentclass{article} \usepackage{geometry} \usepackage{tabularx} \usepackage{tabulary} \usepackage{booktabs} \usepackage{enumitem} \newlist{tabitem}{itemize}{1} \setlist[tabitem]{wide=0pt, nosep, leftmargin= * ,label=\textbullet,after=\vspace{-\baselineskip},before=\vspace{-0.6\baselineskip}} \usepackage[style=authoryear-comp]{biblatex} \addbibresource{\jobname.bib} \usepackage{filecontents} \begin{filecontents}{\jobname.bib} @book{ma2017designing, author = {Ma, A.}, year = {2007}, title = {Title}, publisher = {Publisher}, } @book{hyland2018dynamic, author = {Hyland, A. and Mahmassani}, year = {2018}, title = {Title}, publisher = {Publisher}, } \end{filecontents} \begin{document} \begin{table*}[th!] \center \scriptsize \caption{Systematic literature review.\label{tab:lit_rev}} \begin{tabularx}{\textwidth}{>{\raggedright\arraybackslash}p{1.5cm}*{3}{>{\raggedright\arraybackslash}X}lp{4cm}} Article & Methodology & Model\newline objective & Decision phase & Vehicle Types & Features\\ \toprule \cite{ma2017designing} & Linear programming & Minimize traffic on arcs & Operational, rolling horizon & SAV & \begin{tabitem} \item No carpooling \item Parking at any node \item Simulated traffic congestion \item Flexible departure times\end{tabitem} \\ \midrule \cite{hyland2018dynamic} & Agent-based simulation & Minimize miles driven and client wait times & Operational, rolling horizon, real-time & SAV & \begin{tabitem}\item No carpooling \item No info on parking \item No traffic congestion \item Flexible pick up time \item Fixed number of AVs per day\end{tabitem} \\ \bottomrule \end{tabularx} \end{table*} \begin{table*}[th!] \center \footnotesize \caption{Systematic literature review.\label{tab:lit_rev}} \begin{tabularx}{\textwidth}{>{\raggedright\arraybackslash}p{1.5cm}*{3}{>{\raggedright\arraybackslash}X}lp{4.2cm}} Article & Methodology & Model\newline objective & Decision phase & Vehicle Types & Features\\ \toprule \cite{ma2017designing} & Linear programming & Minimize traffic on arcs & Operational, rolling horizon & SAV & \begin{tabitem} \item No carpooling \item Parking at any node \item Simulated traffic congestion \item Flexible departure times\end{tabitem} \\ \midrule \cite{hyland2018dynamic} & Agent-based simulation & Minimize miles driven and client wait times & Operational, rolling horizon, real-time & SAV & \begin{tabitem}\item No carpooling \item No info on parking \item No traffic congestion \item Flexible pick up time \item Fixed number of AVs per day\end{tabitem} \\ \bottomrule \end{tabularx} \end{table*} \begin{table*}[th!] \center \small \setlength{\tabcolsep}{4pt} \caption{Systematic literature review.\label{tab:lit_rev}} \begin{tabularx}{\textwidth}{>{\raggedright\arraybackslash}p{2cm}*{3}{>{\raggedright\arraybackslash}X}lp{4.4cm}} Article & Methodology & Model\newline objective & Decision phase & Vehicle Types & Features\\ \toprule \cite{ma2017designing} & Linear programming & Minimize traffic on arcs & Operational, rolling horizon & SAV & \begin{tabitem} \item No carpooling \item Parking at any node \item Simulated traffic congestion \item Flexible departure times\end{tabitem} \\ \midrule \cite{hyland2018dynamic} & Agent-based simulation & Minimize miles driven and client wait times & Operational, rolling horizon, real-time & SAV & \begin{tabitem}\item No carpooling \item No info on parking \item No traffic congestion \item Flexible pick up time \item Fixed number of AVs per day\end{tabitem} \\ \bottomrule \end{tabularx} \end{table*} \end{document}
[ "stackoverflow", "0051667038.txt" ]
Q: python - pandas dataframe print column if value = 1 Have this data in panda dataframe: animal tall swim jump frog 0 1 1 toad 1 0 0 tadpole 0 0 1 Would like this output: frog swim frog jump toad tall tadpole jump Any builtin function for this? A: Use set_index with stack, filter 1 and create DataFrame by contructor: df1 = df.set_index('animal').stack() s = df1[df1==1] df2 = pd.DataFrame({'a':s.index.get_level_values(0), 'b':s.index.get_level_values(1)}) print (df2) a b 0 frog swim 1 frog jump 2 toad tall 3 tadpole jump Another solution is use MultiIndex.to_frame: df2 = s.index.to_frame(index=False) df2.columns = ['a','b'] print (df2) a b 0 frog swim 1 frog jump 2 toad tall 3 tadpole jump Different solution with melt and filtering by query: df2 = (df.melt('animal', var_name='val') .query('value == 1') .sort_values('animal') .reset_index(drop=True) .drop('value', axis=1))
[ "unix.stackexchange", "0000405527.txt" ]
Q: I get message "File name too long" when running for..in and touch I want to touch each file in a directory: files=$(ls -a "node_modules/suman-types/dts") echo "files $files"; for file in "$files"; do echo "touching file $file"; touch "node_modules/suman-types/dts/$file"; done but after running that, I get: inject.d.ts injection.d.ts integrant-value-container.d.ts it.d.ts reporters.d.ts runner.d.ts suman-utils.d.ts suman.d.ts table-data.d.ts test-suite-maker.d.ts test-suite.d.ts: File name too long What is that "File name too long" message about? Update #1 I changed my script to this: files=$(find "node_modules/suman-types/dts" -name "*.d.ts") for file in "$files"; do echo "touching file $file"; touch "$file"; done touch "node_modules/suman-types" But then I get this: $ ./types-touch.sh touching file node_modules/suman-types/dts/after-each.d.ts node_modules/suman-types/dts/after.d.ts node_modules/suman-types/dts/before-each.d.ts node_modules/suman-types/dts/before.d.ts node_modules/suman-types/dts/describe.d.ts node_modules/suman-types/dts/global.d.ts node_modules/suman-types/dts/index-init.d.ts node_modules/suman-types/dts/inject.d.ts node_modules/suman-types/dts/injection.d.ts node_modules/suman-types/dts/integrant-value-container.d.ts node_modules/suman-types/dts/it.d.ts node_modules/suman-types/dts/reporters.d.ts node_modules/suman-types/dts/runner.d.ts node_modules/suman-types/dts/suman-utils.d.ts node_modules/suman-types/dts/suman.d.ts node_modules/suman-types/dts/table-data.d.ts node_modules/suman-types/dts/test-suite-maker.d.ts node_modules/suman-types/dts/test-suite.d.ts touch: node_modules/suman-types/dts/after-each.d.ts node_modules/suman-types/dts/after.d.ts node_modules/suman-types/dts/before-each.d.ts node_modules/suman-types/dts/before.d.ts node_modules/suman-types/dts/describe.d.ts node_modules/suman-types/dts/global.d.ts node_modules/suman-types/dts/index-init.d.ts node_modules/suman-types/dts/inject.d.ts node_modules/suman-types/dts/injection.d.ts node_modules/suman-types/dts/integrant-value-container.d.ts node_modules/suman-types/dts/it.d.ts node_modules/suman-types/dts/reporters.d.ts node_modules/suman-types/dts/runner.d.ts node_modules/suman-types/dts/suman-utils.d.ts node_modules/suman-types/dts/suman.d.ts node_modules/suman-types/dts/table-data.d.ts node_modules/suman-types/dts/test-suite-maker.d.ts node_modules/suman-types/dts/test-suite.d.ts: No such file or directory A: Your problem stems from capturing all of the ls output into a single (string) variable named files. The variable looks something like: filename1\nfilename2\nfilename3\n... See for yourself with: echo "$files" | od -c What you're really doing is looping once over a really long string that corresponds to a file that doesn't exist. The error you got was slightly informative -- it's telling you that this long string-of-a-filename doesn't exist. To touch every file in a directory, just use shell globbing and run touch: touch node_modules/suman-types/dts/* or touch them one by one: for file in node_modules/suman-types/dts/*; do touch "$file"; done or find them and touch them: find node_modules/suman-types/dts -type f -exec touch -- {} \;
[ "stackoverflow", "0012234292.txt" ]
Q: Static method over the class itself? I have a question that was in an older test and I need to know the answer for practicing. We have the following Class: public class First{ private int num1 = 0; private int num2 = 0; private static int count = 0; public First(int num){ this(num,num); count++; System.out.println("First constructor1"); } public First(int num1, int num2){ this.num1 = num1; this.num2 = num2; count++; System.out.println("First constructor2"); } public int sum(){ return num1 + num2; } public static int getCount(){ return count; } } Now we are operating the following orders: 1. First f1 = new First(10); 2. First f2 = new First(4,7); 3. System.out.println("sum1 = " + f1.sum()); 4. System.out.println("count = " + First.getCount()); 5. System.out.println("sum2 = " + f2.sum()); 6. System.out.println("count = " + First.getCount()); I need to write down the lines that will be printed on screen after those 6 lines. I know that after the first 3 lines it should be like this: First constructor2 First constructor1 First constructor2 sum1 = 20 The only thing that disturb me is, what's the meaning of a line like line #4? is it a method that operate on the class itself instead on an object? Another question is that in part B we need to re-define the method equals inside the 'First' class (same method that extends Object) so she will be able to compare between the object that the method operates on and another 'First' type object. The method returns true if both num1, num2 are equals. I thought about something like this: public class First { ... ... . . . public boolean equals (First anotherObj){ if ((First.num1 == anotherObj.num1) && (First.num2 == anotherObj.num2)) return true; return false; } // equals } // 'First' class Am I right? A: Yes, getCount() is a static method of your class First which can be called without instantiating any concrete objects. So in your example by using this method you can read the static variable count, which gets increased by 1 whenever the constructor gets called. So if once you created f1 and f2 count will be 2. "count" is a variable shared by all your First instances. Your equals() method doesn't work since first of all you need to override public boolean equals(Object obj) Secondly, num1 and num2 are private so you need a Getter to make them available. Something like: public boolean equals(Object obj) { return num1 == (First)obj.getNum1() && num2 == (First)obj.getNum2(); } If you override equals you should also override public int hashCode() Example for hashCode(): public int hashCode() { int result = 5; result = 31 * result + num1; result = 31 * result + num2; return result; } (5 and 31 are primes, you can also use e.g. Eclipse to automatically generate this methods).
[ "stackoverflow", "0012423224.txt" ]
Q: How to merge some keys into *args and then call another method with those args? I have the following method: def item(*args, &block) options = args.extract_options! options.reverse_update({ brand: false, icon: false, }) # Do some stuff end And this method: def brand(*args, &block) options = args.extract_options! options[:brand] = true self.item(???, &block) # How does this call have to look? end The 2nd last line is of interest. I want to call the item with exact the same parameters like the brand method was called (except I added another parameter, brand). A: I'd write: def brand(*args, &block) options = args.extract_options! options[:brand] = true self.item(*(args+[options]), &block) end
[ "stackoverflow", "0050825249.txt" ]
Q: Change size of section titles in R Markdown PDF Is there a way to change the font size of text of headings in R Markdown? I know how to number the sections of the article; however, in terms of formatting, the font size of the sections that are numbered 1., 2., 3... is too large. As a workaround, I have been using lower-level headers ### Introduction, but these have the wrong numbering. Here is a basic example: --- output: bookdown::pdf_document2 --- # This is too big ### This is the right size but are labelled as 1.0.1 A: You can place \usepackage[medium]{titlesec} % or small in preamble.tex (or where ever you have special LaTeX commands) together with subparagraph: yes in th e YAML headers (c.f. this question). For a more detailed answer we will need a minimal working example.
[ "stackoverflow", "0002975551.txt" ]
Q: grails scaffolding broken Grails scaffoldin does not work in my grails application. When I go from the main page to the specific controller page it output something like this: Error 500: Servlet: default URI: /myapp/myDomain/list Exception Message: Tag [sortableColumn] is missing required attribute [title] or [titleKey] at /webTestDummyDomain/list:25 Caused by: Error processing GroovyPageView: Tag [sortableColumn] is missing required attribute [title] or [titleKey] at /myDomain/list:25 Class: /myDomain/list At Line: [25] Code Snippet: Code snippet empty. If I try to create a new app scaffold works perfectly. Additional data: Application Status * App version: 0.1 * Grails version: 1.2.2 * JVM version: 1.6.0_20 * Controllers: 11 * Domains: 10 * Services: 19 * Tag Libraries: 26 Installed Plugins * i18n - 1.2.2 * filters - 1.2.2 * logging - 1.2.2 * core - 1.2.2 * tomcat - 1.2.2 * webtest - 2.0.4 * functionalTest - 1.2.7 * yui - 2.7.0.1 * rest - 0.3 * jquery - 1.4.2.1 * bubbling - 2.1.2 * urlMappings - 1.2.2 * groovyPages - 1.2.2 * servlets - 1.2.2 * dataSource - 1.2.2 * controllers - 1.2.2 * codecs - 1.2.2 * jqueryUi - 1.8-SNAPSHOT * grailsUi - 1.2-SNAPSHOT * domainClass - 1.2.2 * mimeTypes - 1.2.2 * scaffolding - 1.2.2 * converters - 1.2.2 * hibernate - 1.2.2 * validation - 1.2.2 * services - 1.2.2 Can you give me any pointer? A: I found out what happened. I had a taglib without namespace redefinition and with a closure named "message". And that closure was running instead i18n function "message" so it didn't output nothing. And the tag generated by grails scaffolding named "sortable" it need a attribute that need the output of the i18n function. For the next time I have to try to name my functions with names that doesn't appear in the grails reference. Thanks @Steven for your answer though.
[ "stackoverflow", "0023837800.txt" ]
Q: how to put my java web application in a server? I made a Java Web Application with Netbeans. I used JSF, PrimeFaces and the Glassfish Server. Now I want to put my application in a server but i just dont have idea of how to do that. I think fist of all have to install Glassfish in the server. How do I do that? The server i will be using has Windows Server 2008 Enterprise. Do I have to look for a .exe to install Glassfish? The same to do with Java? I have already done the connection to the SQL Server database so that part must work. So please explain me step by step what i have to have, how to install and configure everything and how to try if everything worked please. Thanks for Your answers! :) A: Depending on what your web application requires you will need to install more than just the glassfish server. You need to install: -Java jdk (required) -Glassfish server (required) -Database (if using one) -Apache (if needed) After you install everything, you need to deploy the war file of the application to the glassfish server. To do this you must first create a war file by 'cleaning and building' the app (option in netbeans). The war file will be located in one of the folders in the project. Then you must log in to your glassfish admin console (located at http://localhost:4848 if run on localhost) and click on one of the options in the left menu that lets you manage the applications on the server. There will then be an option that lets you add war files to the server.