source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0014157236.txt" ]
Q: Not Getting Event Data for Google Analytics I have set up GA event tracking on a test site I have. I use the asynch call in the page and then send events on click. the code I use is here: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXX-1']); // This is where my real Analytics Account number would be _gaq.push(['_trackPageview']); _gaq.push(['_trackEvent', 'AdvertImpression', 'MEA','logged In']); _gaq.push(['_trackEvent', 'AdvertImpression', 'AN Other Advert','not logged in']); (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); })(); I also have an onclick event. <A href="http://www.xxxyyy.com/ad/click/taHR"><IMG src="http://img.xxxyyy.com/banners/OPFME-20121211.jpg" width=468 height=60 border=0 alt="MEA" onclick="_gaq.push(['_trackEvent', 'AdvertClicked', 'MEA','Logged In'])")></A> I see the site visits appear and my account says that events are being generated. When I select "Unique Events" I even see quantities but I cannot see any of the specific category information in the drill down. I have remove all filters on the account and have waited for 48 hrs. Is there something I'm missing. A: Google Analytics records data by making tracking image requests. If you're loading a new page in the same window before the tracking request has completed, no data will be recorded. I've had good luck with a slight delay before following the link. Try the following code: <script type="text/javascript"> function trackLink(link, category, action, value) { _gaq.push(['_trackEvent', category , action, value ]); if (link.target == "_blank") return true; setTimeout(function(){ location.href = link.href; }, 150) return false; } </script> Add it the link as follows -- the return in the onlick is required. <a href="http://www.xxxyyy.com/ad/click/taHR" onclick="return trackLink('AdvertClicked', 'MEA','Logged In')">...
[ "stackoverflow", "0050578790.txt" ]
Q: Dynamic field validation in codeigniter I have a form built with my own form builder, my form builder is similar to Gravity form for WordPress. Everything is working fine except the validation. Every time I submit the form it returns true. Especially, I'm validating the select field, because the user can edit the value from web inspector and submit the value, that's why I'm checking the value against saved values in DB where the dynamic form is saved. Here is my try where $post is $_POST[] array, $postKey is fieldName, & $postValue is submitted value by user. public function validate() { $post = $this->ci->input->post(); //check form tempering if(empty($post)) return false; $formId = $post['form_id']; //get form from db $data=[]; $this->ci->db->select('formData'); $this->ci->db->where('formId', $formId); $query = $this->ci->db->get(TBL_FORM_DATA); if($query->num_rows() > 0) { $data = $query->row(); } if(empty($data) ) return false; //unset submit button and 0 if occurs unset($post['submit']); unset($post['0']); //decode json $data = json_decode($data->formData,true); $fields = $data['field']; //debug($fields); //iterate post values and keys foreach ($post as $postKey => $postValue) { //echo '<br>'.$postKey; if(strpos($postKey, '@')) { list($fieldName,$field_id) = explode('@', $postKey); $field_display_name = ucwords(str_replace('_', ' ', $fieldName)); if(strpos($field_id,'|')) { list($field_id,$price) = explode('|', $field_id); } $field = $fields[$field_id]; //debug($field['choice'],false); if(isset($field['choice']) && (isset($field['choice']['label']) && isset($field['choice']['value'])) ) { /*if(!in_array($postValue, $field['choice']['value'])) {*/ //$list = implode(',', $field['choice']['value']); $this->ci->form_validation->set_rules($postKey,$field_display_name,'callback_check_field['.$list.']'); /*$this->ci->form_validation->set_rules($postKey, $field_display_name,"in_list[".$list."]", array('in_list' => 'Invalid Selection. Please Select from available choices.') );*/ /*}*/ } if(isset($field['required']) && $field['required']=='on'){ $this->ci->form_validation->set_rules($postKey, $field_display_name,'required|trim'); } //$duplicate = isset($field['no_duplicate']) ? true : false; //$this->ci->form_validation->set_rules('form_id',' ','required'); //$this->ci->form_validation->set_rules('inkform_total',' ','required'); } $this->ci->form_validation->set_error_delimiters('<div class="clearfix"></div><p class="alert alert-danger">','</p>'); return $this->ci->form_validation->run(); } //echo validation_errors(); } The callback function to check the select field values function check_field($field,$list) { if(!is_array($list)) { $list = explode(',', $list); } if(!in_array($field, $list)){ $this->ci->form_validation->set_message('check_field','Invalid Post'); return false; }else{ return true; } } And later i just want to access validate() function for validating. A: Move $this->ci->form_validation->set_error_delimiters('<div class="clearfix"></div><p class="alert alert-danger">','</p>'); return $this->ci->form_validation->run(); outside the foreach
[ "stackoverflow", "0025749552.txt" ]
Q: Retrieve a line structure from the multi-layered ObjectNode I have an ObjectNode as input parameter, and I don't know exact structure of this node. I mean that it can have any amount of layers inside, from very simple array of NameValuePair<String,String> to complex structure like HashMap<String,Object>. How can I parse it to simple flat structure like an array of NameValuePair<String,String>? I did it before for the ObjectNodes with the known structure, but now I have no idea. I appreciate any help and any ideas. Adding details: for example, if I know, that inside the ObjectNode I will always find just HashMap<String,String>, and that's all, I can just do: ObjectNode parametersNode = (ObjectNode) request.get("parameters"); Iterator fieldNames = parametersNode.getFieldNames(); HashMap<String,String> oldParams = new HashMap<String,String>(); while (fieldNames.hasNext()) { String name = (String) fieldNames.next(); oldParams.put(name, parametersNode.get(name).asText()); } But what if the structure of this ObjectNode is kind of a black box? I don't know is there a Map, or an Array, or a bunch of Maps inside a Map. It can be from different sources, and I don't know what structure I will get in any moment. it can be: { "name":"value", "name1":"value1" } or { "name":"value", "arg1": [ "name1":"value1", "name1":"value1" ] } or { "name":"value", "arg1": [ {"name1":"value1"}, {"name1":"value1"} ] } or any more complex structure. And I have no information beforehand, what I get. How can I convert such a black box ObjectNode to the flat array of name-value pairs? Is there any universal algorithm? At the end I should get simple structure like that regardless complexity of the initial structure: { "name":"value", "name1":"value1", "name2":"value2" } A: As I got no answers, I did it myself. For those who will face the same problem I post it here. It is without any recursion and I used HashMap where I shouldn't, but it's as a proof of concept and intended to be refactored. Please note, that it was tested as a webservice on Switchyard via Postman, so no main method. public ArrayList<HashMap<String, String>> convertToFlatFormat( JsonNode request) { Stack<Pair> stack = new Stack<Pair>(); ArrayList<HashMap<String, String>> parametersList = new ArrayList<HashMap<String, String>>(); stack.push(new Pair("", request)); HashMap<String, Integer> counts = new HashMap<String, Integer>(); while (!stack.isEmpty()) { Pair higherNodePair = stack.pop(); String nodeName = higherNodePair.name; JsonNode higherNode = (JsonNode) higherNodePair.object; String newNamePrefix = ""; if (higherNode.isArray()) { ArrayNode higherArrayNode = (ArrayNode) higherNode; for (int i = 0; i < higherNode.size(); i++) { JsonNode node = higherArrayNode.get(i); String key = new Integer(i).toString(); if (node.isObject()) { if (nodeName.equals("")) { stack.push(new Pair(newNamePrefix, node)); } else { stack.push(new Pair(nodeName + "_" + newNamePrefix , node)); } } else if (node.isArray()) { if (nodeName.equals("")) { stack.push(new Pair(newNamePrefix, node)); } else { stack.push(new Pair(nodeName + "_" + newNamePrefix , node)); } } else if (node.isValueNode()) { ValueNode valueNode = (ValueNode) node; String value = valueNode.getTextValue(); HashMap<String, String> pair = null; if (nodeName.equals("")) { pair = new HashMap<String, String>(); pair.put(newNamePrefix + key, value); } else { pair = new HashMap<String, String>(); pair.put(nodeName + "_" + newNamePrefix + key, value); } parametersList.add(pair); } } } else { Iterator<String> iterate = higherNode.getFieldNames(); while (iterate.hasNext()) { String key = iterate.next(); JsonNode node = higherNode.get(key); if (node.isObject()) { if (nodeName.equals("")) { stack.push(new Pair(newNamePrefix + key, node)); } else { stack.push(new Pair(nodeName + "_" + newNamePrefix + key, node)); } } else if (node.isArray()) { if (nodeName.equals("")) { stack.push(new Pair(newNamePrefix + key, node)); } else { stack.push(new Pair(nodeName + "_" + newNamePrefix + key, node)); } } else if (node.isValueNode()) { ValueNode valueNode = (ValueNode) node; String value = valueNode.getTextValue(); HashMap<String, String> pair = null; if (nodeName.equals("")) { pair = new HashMap<String, String>(); pair.put(newNamePrefix + key, value); } else { pair = new HashMap<String, String>(); pair.put(nodeName + "_" + newNamePrefix + key, value); } parametersList.add(pair); } } } } return parametersList; } private class Pair { public String name; public Object object; public Pair(String name, Object object) { this.name = name; this.object = object; } } The input is: { "name1":"value1", "name2":"value2", "name3":[ { "ComponentId":"qwer", "InstanceId":"amba" }, { "ComponentId":"qwer", "InstanceId":"coramba" }, { "ComponentId":"dsa", "InstanceId":"badar" }, { "ComponentId":"dsa", "InstanceId":"fdarr" }, { "ComponentId":"dsa", "InstanceId":"sdddd" } ] } The output is: [ { "name1": "value1" }, { "name2": "value2" }, { "name3__dsa_1_ComponentId": "dsa" }, { "name3__dsa_1_InstanceId": "sdddd" }, { "name3__dsa_2_ComponentId": "dsa" }, { "name3__dsa_2_InstanceId": "fdarr" }, { "name3__dsa_3_ComponentId": "dsa" }, { "name3__dsa_3_InstanceId": "badar" }, { "name3__qwer_1_ComponentId": "qwer" }, { "name3__qwer_1_InstanceId": "coramba" }, { "name3__qwer_2_ComponentId": "qwer" }, { "name3__qwer_2_InstanceId": "amba" } ]
[ "stackoverflow", "0048595878.txt" ]
Q: SQL query to display each horse that has been added in the same event as its father(sire) These are the following tables I have created: CREATE TABLE Horse (horse_id INTEGER PRIMARY KEY, horse_name CHAR(30), horse_colour CHAR(30) horse_sire INTEGER, horse_dam INTEGER, horse_born INTEGER. horse_died INTEGER, horse_gender CHAR(2) ); CREATE TABLE Event (event_id INTEGER PRIMARY KEY, event_name CHAR(30) ); CREATE TABLE Entry (event_id INTEGER, horse_id INTEGER ); Then I inserted the values for these 3 tables: INSERT INTO Horse (horse_id,horse_name,horse_colour,horse_sire,horse_dam,horse_born,horse_gender) VALUES (101,'Flash','white',201,301,1990,'S'); INSERT INTO Horse (horse_id,horse_name,horse_colour,horse_sire,horse_dam,horse_born,horse_gender) VALUES (102,'Star','brown',201,302,1991,'M'); INSERT INTO Horse (horse_id,horse_name,horse_colour,horse_sire,horse_dam,horse_born,horse_gender) VALUES (201,'Boxer','grey',401,501,1980,'S'); INSERT INTO Horse (horse_id,horse_name,horse_colour,horse_sire,horse_dam,horse_born,horse_gender) VALUES (301,'Daisy','white',401,502,1981,'M'); INSERT INTO Horse (horse_id,horse_name,horse_colour,horse_sire,horse_dam,horse_born,horse_died,horse_gender) VALUES (302,'Tinkle','brown',401,501,1981,1994,'M'); INSERT INTO Horse (horse_id,horse_name,horse_colour,horse_dam,horse_born,horse_died,horse_gender) VALUES (401,'Snowy','white',301,1976,1984,'S'); INSERT INTO Horse (horse_id,horse_name,horse_colour,horse_dam,horse_born,horse_died,horse_gender) VALUES (501,'Bluebell','grey',301,1975,1982,'M'); INSERT INTO Horse (horse_id,horse_name,horse_colour,horse_dam,horse_born,horse_died,horse_gender) VALUES (502,'Sally','white',301,1974,1987,'M'); INSERT INTO Event (event_id,event_name) VALUES (101,'Dressage'); INSERT INTO Event (event_id,event_name) VALUES (102,'Jumping'); INSERT INTO Event (event_id,event_name) VALUES (103,'Jumping'); INSERT INTO Event (event_id,event_name) VALUES (201,'Led in'); INSERT INTO Event (event_id,event_name) VALUES (301,'Led in'); INSERT INTO Event (event_id,event_name) VALUES (401,'Dressage'); INSERT INTO Event (event_id,event_name) VALUES (501,'Dressage'); INSERT INTO Event (event_id,event_name) VALUES (502,'Flag and Pole'); INSERT INTO Entry (event_id,horse_id) VALUES (101,101); INSERT INTO Entry (event_id,horse_id) VALUES (101,102); INSERT INTO Entry (event_id,horse_id) VALUES (101,201); INSERT INTO Entry (event_id,horse_id) VALUES (101,301); INSERT INTO Entry (event_id,horse_id) VALUES (102,201); INSERT INTO Entry (event_id,horse_id) VALUES (103,102); INSERT INTO Entry (event_id,horse_id) VALUES (201,101); INSERT INTO Entry (event_id,horse_id) VALUES (301,301); INSERT INTO Entry (event_id,horse_id) VALUES (401,102); INSERT INTO Entry (event_id,horse_id) VALUES (501,102); INSERT INTO Entry (event_id,horse_id) VALUES (501,301); This is the following question: For each horse that has been entered in the same event as its sire (father), list the names of the two horses and of the event. The output of this query should be as shown below: Horse Sire Event Flash Boxer Dressage Star Boxer Dressage This is what I have tried: SELECT TOP 2 H1.horse_name AS Horse, H2.horse_name AS Sire, event_name AS Event FROM Horse AS H1, Horse AS H2, Event, Entry WHERE H1.horse_sire = H2.horse_id AND H1.horse_sire = Entry.horse_id AND H2.horse_id = Entry.horse_id AND Event.event_id = Entry.event_id AND (H1.horse_sire IS NOT NULL AND H1.horse_dam is NOT NULL ); And this is the output I am getting after executing the query: Horse Sire Event Flash Boxer Dressage Flash Boxer Jumping I almost got the desired output based on what the question wanted but the only problem is that I am getting 'Flash' instead of 'Star' in the first column (Horse) of the 2nd row. In other words, my code just needs a small fix. It would be really helpful if my code can be corrected and re-written. So where is the mistake am I making? A: You need a separate join to Entry for the sire because its entry is not the same as its offspring's entry. SELECT H1.horse_name AS Horse, H2.horse_name AS Sire, event_name AS Event FROM Horse AS H1, Horse AS H2, Event, Entry, Entry As SireEntry WHERE H1.horse_sire = H2.horse_id AND H1.horse_id = Entry.horse_id AND H2.horse_id = SireEntry.horse_id AND Event.event_id = Entry.event_id AND Event.event_id = SireEntry.event_id; http://sqlfiddle.com/#!18/16c06/2
[ "stackoverflow", "0022428853.txt" ]
Q: How to actually center (vertical and horizontal) text inside a nested div I Know there are several questions about this topic, however I think they depend a bit on another CSS properties given before. I have a nested <div id="tituloParametros>" and I need its text/contain to be centred on vertical and horizontal position. This is my markup: <div id="outer"> <div id="parametros"> <div id="tituloParametros">Ingresa los puntos conocidos x,f(x)</div> </div> <div id="resultados"> <div id="graficos"> <div id="bars"></div> <div id="fx"></div> <div id="pinchetabla">Tabla inútil</div> </div> <div id="loquerealmenteimporta"></div> </div> </div> And this is the applied CSS: #outer{ padding-left: 15px; padding-top: 15px; width: 1350px; height: 640px; } #parametros { float:left; width: 20%; height: 100%; } #tituloParametros { height: 9%; width: 100%; background-color: red; text-align:center; vertical-align:middle } #resultados { float:right; width: 80%; height: 100%; } #graficos { height: 75%; width: 100%; } #bars { float: left; height: 100%; width: 30%; } #fx { float: left; height: 100%; width: 30%; } #pinchetabla { float: left; height: 100%; width: 40%; } #loquerealmenteimporta { height: 25%; width: 100%; } I thought that: text-align:center; vertical-align:middle both will make it but it didn't. Adding display: table-cell; doesn't solve it neither, it actually crops the background to the text limits. This is how it looks like A: You're right - the table/table-cell approach doesn't work here. As an alternative, you could resort to the absolute positioning method. An element will be vertically centered when the top value is 50% subtracted by half the element's height. In this instance, it shouldn't be a problem because the height is already set with the % unit. 100% - 50% - 9%*.5 = 45.5% If this weren't the case, you could use calc() or negative margins to subtract the px unit from the % unit. In this case, it's worth noting that the child element is absolutely positioned relative to the parent element. Updated CSS -- UPDATED EXAMPLE HERE #parametros { float:left; width: 20%; height: 100%; outline : 1px solid black; position:relative; } #tituloParametros { background-color: red; width: 100%; height: 9%; text-align:center; position:absolute; top:45.5% } The element #tituloParametros is now centered within the parent element. If you want to center the text within it, you could wrap the text with a span element and then use the table/table-cell vertical centering approach: UPDATED EXAMPLE HERE #tituloParametros { /* other styling.. */ display:table; } #tituloParametros > span { display:table-cell; vertical-align:middle; }
[ "stackoverflow", "0058893349.txt" ]
Q: Why LibGDX sound pitch doesn't work with GWT? I use the instance of class Sound. To get the desired pitch I use the method: public long loop (float volume, float pitch, float pan); It works as expected on desktop build but on GWT pitch isn't working. My gwtVersion is 2.8.2, gdxVersion is 1.9.10 and I use de.richsource.gradle.plugins:gwt-gradle-plugin:0.6. I have been stuck on this problem for a couple of days now and would be very thankful for any input. A: "Why LibGDX sound pitch doesn't work with GWT?" Because the official libGDX GWT backend uses SoundManager for playing sounds within the browser, and SoundManager does not support pitching. To get it run, you must change to another solution: the WebAudio API. Lucky as you are, others already implemented it for libGDX, but it is not pulled into the repository for unknown reasons. See PR 5659. As told in the PR, you can switch to my forked GWT backend to get it to work. Simply change your gradle.build file implementation 'com.github.MrStahlfelge.gdx-backends:gdx-backend-gwt:1.910.0' You also need to declare the Jitpack repo if you don't already have.
[ "math.stackexchange", "0000365486.txt" ]
Q: Is $\phi(x)=\frac{\operatorname{d}(x,A)}{\operatorname{d}(x,A)+\operatorname{d}(x,B)}$ locally Lipschitz? Let $X$ be a metric space and $A,B\subset X$ satifying $\overline{A}\cap\overline{B}=\emptyset$. Define $\phi :X\to\mathbb{R}$ by $$\phi(x)=\frac{\operatorname{d}(x,A)}{\operatorname{d}(x,A)+\operatorname{d}(x,B)}$$ where $\operatorname{d}$ denotes distance. Is true that $\phi$ is Locally Lipschitz? I am trying to use the fact that $\operatorname{d}$ is Lipschitz, but I could not achieve a good inequality for this. Thanks. A: You have $$|\phi(x)-\phi(y)|= \frac{ |d(x,A)d(y,B)-d(y,A)d(x,B)|}{(d(x,A)+d(x,B))(d(y,A)+d(y,B))}$$ Eventually, permute $x$ and $y$ so that: $$|\phi(x)-\phi(y)|= \frac{ d(x,A)d(y,B)-d(y,A)d(x,B)}{(d(x,A)+d(x,B))(d(y,A)+d(y,B))}$$ But $d(x,A) \leq d(x,y)+d(y,A)$ so $$ \begin{array}{ll} d(x,A)d(y,B)-d(y,A)d(x,B) & \leq d(x,y)d(y,B)+d(y,A)(d(y,B)-d(x,B)) \\ & \leq d(x,y)(d(y,A)+d(y,B)) \end{array}$$ Finally, $$|\phi(x)-\phi(y)| \leq \frac{d(x,y)}{d(x,A)+d(x,B)}$$ To show that $\phi$ is locally lipschitz, it is sufficient to notice that $x \mapsto d(x,A)+d(x,B)$ is locally bounded below. Because $\overline{A} \cap \overline{B}=\emptyset$, for any point $x$ there exists an open ball $B(r)$ such that either $B(r) \cap \overline{A}= \emptyset$ or $B(r) \cap \overline{B}= \emptyset$; without loss of generality, suppose $B(r) \cap \overline{A}= \emptyset$. Then $$d(x,A)+d(x,B) \geq d(x,A) \geq r$$ Remark: If $\delta:=d(A,B)>0$, then $\phi$ is $1/\delta$-lipschitz.
[ "stackoverflow", "0035740940.txt" ]
Q: Polymer 1.x: paper-fab elevation not working? In this jsBin, I'm trying to add a paper-fab to my element. I expect to see a shadow corresponding to the elevation property. But instead I see no shadow. All the elevations seem to have the same shadow (implied z-depth). Is the problem with my code or the element? http://jsbin.com/corisahoqi/edit?html,output <!doctype html> <head> <meta charset="utf-8"> <!---- > <base href="https://polygit.org/components/"> <!---- > Toggle below/above as backup when server is down <!----> <base href="https://polygit2.appspot.com/components/"> <!----> <script src="webcomponentsjs/webcomponents-lite.min.js"></script> <link href="polymer/polymer.html" rel="import"> <link href="paper-fab/paper-fab.html" rel="import"> <link href="iron-icons/iron-icons.html" rel="import"> </head> <body> <dom-module id="x-element"> <template> <style> paper-fab { margin: 15px; } </style> <paper-fab icon="add" elevation="5"></paper-fab> <paper-fab icon="add" elevation="4"></paper-fab> <paper-fab icon="add" elevation="3"></paper-fab> <paper-fab icon="add" elevation="2"></paper-fab> <paper-fab icon="add" elevation="1"></paper-fab> </template> <script> (function(){ Polymer({ is: "x-element", }); })(); </script> </dom-module> <x-element></x-element> </body> A: Looks to me like a problem with the element. In the documentation, it sounds as if it could be used the way you intend. The z-depth of this element, from 0-5. Setting to 0 will remove the shadow, and each increasing number greater than 0 will be "deeper" than the last But then elevation property is read-only, so setting it has no effect.
[ "stackoverflow", "0012448840.txt" ]
Q: Parse XML with JSTL I am trying to get only first record from loop, Or how can I stop this loop after first record? <x:parse var="taggedData" xml="${taggedLoad}"/> <x:forEach var="item" select="$taggedData//item" varStatus="status"> <h4> <a href="/go/video/index.jsp?videoId=<str:substring start="5"><x:out select="$item/guid"/></str:substring>" onclick="javascript:loadBCvideo(<str:substring start="5"><x:out select="$item/guid"/></str:substring>); return false;"><x:out select="$item/title" /></a> </h4> <p> <x:out select="$item/description" escapeXml="false" /> </p> A: You could use: <xsl:for-each select="(//*[local-name()='item'])[position() &lt;= 1]"> or: def result = records.children().find { domain -> domain.@domain_name == targetDomain } result.children().each { // do stuff }
[ "stackoverflow", "0035637968.txt" ]
Q: Force classifer to select a fixed number of targets If I have a dataset with events where each event has data with 1000 possible items with only 100 being correct for each event. How do I force my classifier to select only 100 for each event? After I run it through my training model (with 18 features and always has 100 targets/event flagged as 1) the classifier selects anywhere between 60-80 items instead of 100. Even if I give each event an event number that doesn't help. I'm using python sklearn gradient boosting and random forest method. A: Just do it yourself. Each classifier in scikit-learn gives you access to decision_function or predict_proba, both of which are support for predict operation (predict is just argmax of these). Thus - just select 100 with the highest support.
[ "stackoverflow", "0026612410.txt" ]
Q: Scatterplot with trajectory across datasets I am using ggplot2 in R to create scatterplots. I have (x,y) datasets for two different conditions as follows: x1 y1 x2 y2 1 1.00000000 150.36247 0.50000000 133.27397 2 1.00000000 129.62707 0.50000000 120.79893 3 1.00000000 79.94730 0.62500000 78.98120 4 1.00000000 79.78723 0.62500000 81.93014 5 1.00000000 133.47697 0.72727273 192.86557 I would like to plot (x1,y1) and (x2, y2) on the same plot, and draw a trajectory line connecting the two points, for each row in the dataset. For example, in the sample data above, there would be a line connecting (1,150) to (0.5, 133) (the data from row 1) and a separate line connecting (1,129) and (0.5, 120) (the data from row 2) and so on. Ideally, I would also like to make each line a different color. I tried following the instructions below to create the trajectories but the grouping in my dataset is by columns rather than by rows: Scatterplot with developmental trajectories, and Making a trajectory plot using R Currently, my script just generates two scatterplots on the same graph but there is no connection between data points of the same row: scatter2<-ggplot(data = df, aes(x=x1, y=y1)) + geom_point(aes(x=x1, y=y1), color="red") + geom_point(aes(x=x2, y=y2), color="blue") Any help you can provide would be greatly appreciated! Thank you! A: This can be achieved by using geom_segment(). You can find more information here: http://docs.ggplot2.org/current/geom_segment.html. I suppose here, you would do something like scatter2<-ggplot(data = df, aes(x=x1, y=y1)) + geom_point(aes(x=x1, y=y1), color="red") + geom_point(aes(x=x2, y=y2), color="blue") + geom_segment(aes(x=x1, y=y1, xend=x2, yend=y2))
[ "stackoverflow", "0041024024.txt" ]
Q: UI-Grid 3.0 how to show/hide button in a column cell for first row I know it's bad to reference other questions but since I cannot comment on this guys page, the best I can do is post his question here and ask, here is his link: ng-grid how to show/hide button in a column cell for last row Now the question I have is how would I apply this concept but instead only hide the action button on the first row. I have a delete button on all my rows but I cannot hide the delete button on the first row only. I've even tried ng-hide="row.rowIndex==0" assuming the index value of zero would hide the delete button but it doesn't. UPDATE: I have answer below. I figured out that ui grid 3.0 doesn't really have index values but if you apply what I have below into cellTemplate you can render index values for the rows and manipulate the rows to hide/show what you want. cellTemplate: '<div ng-hide{{grid.renderContainers.body.visibleRowCache.indexOf(row)}}==0"><a class="sidePadding" title="Delete"><span class="glyphicon glyphicon-trash text-danger cursorHover"></span></a></div>' A: Figured it out ng-hide="{{grid.renderContainers.body.visibleRowCache.indexO‌​f(row)}}==0", it works perfectly now! :)
[ "stackoverflow", "0049778708.txt" ]
Q: DjangoAdmin form with 1:N selection wont save object I was looking for a way to assign one, or more, already existing objects to the current one, while creating in the add section. Something like InLine but I do not want to create them, only select and assign. Two example models: class Location(models.Model): name = models.CharField(max_length=30) class Device(models.Model): name = models.CharField(max_length=20) location = models.ForeignKey(Location, null=True, blank=True, on_delete=models.DO_NOTHING) So while creating Location in Django Admin, I want to be able to assign 1-N existing Devices. I found a way to do so, with a custom Form Here is my custom Form inside admin.py class LocationForm(forms.ModelForm): class Meta: model = Location fields = '__all__' devices = forms.ModelMultipleChoiceField(queryset=Device.objects.all()) def __init__(self, *args, **kwargs): super(LocationForm, self).__init__(*args, **kwargs) if self.instance: self.fields['devices'].initial = self.instance.device_set.all() def save(self, *args, **kwargs): instance = super(LocationForm, self).save(commit=False) self.fields['devices'].initial.update(location=None) self.cleaned_data['devices'].update(location=instance) return instance @admin.register(Location) class LocationAdmin(admin.ModelAdmin): form = LocationForm That works fine as long as I dont save the Location object. Here is a picture of how it looks in django admin. However when I try to save the Location, I got the following error: File "admin.py", line 21, in save api | self.cleaned_data['devices'].update(location=instance) api | File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 692, in update api | rows = query.get_compiler(self.db).execute_sql(CURSOR) api | File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1378, in execute_sql api | cursor = super().execute_sql(result_type) api | File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql api | sql, params = self.as_sql() api | File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1334, in as_sql api | val.prepare_database_save(field), api | File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 932, in prepare_database_save api | raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self) api | ValueError: Unsaved model instance <Location: Test Project> cannot be used in an ORM query. I've tried manually saving the object in the save method but that didn't work either, I'm running out of ideas since I don't really know why it is not saving at all. I though the save method from the superclass would be enough but apparently that is not the case. A: Just found it, after reading my question for like seven times. At first line of the log it says self.cleaned_data['devices'].update(location=instance) so clearly the instance is the thing that is not saved and thus cannot be used as a query parameter, so I edited my Form's save method like this. def save(self, *args, **kwargs): instance = super(LocationForm, self).save(commit=False) self.fields['devices'].initial.update(location=None) instance.save() self.cleaned_data['devices'].update(location=instance) return instance And it is working.
[ "stackoverflow", "0028285274.txt" ]
Q: Replacing foldr with foldl I have this function to sum the odd numbers on a list: idOdd xs = foldr (\x acc -> if odd x then x+acc else acc) 0 xs if i want to do it with foldl, how would it change? A: In your case it's very easy, you can just swap the order of the arguments to get it to work correctly: idOdd2 = foldl (\acc x -> if odd x then x + acc else acc) 0 This is primarily because your accumulator type is the same as your list element type, and because + is commutative and associative. This is important due to how foldl and foldr reduce a list: isOdd [1, 2, 3, 4, 5] = 1 + (3 + (5 + 0)) = 9 isOdd2 [1, 2, 3, 4, 5] = ((0 + 1) + 3) + 5 = 9 In this case 1 + (3 + (5 + 0)) == ((0 + 1) + 3) + 5, but this isn't true of all operators, such as : or ++.
[ "stackoverflow", "0029482487.txt" ]
Q: Why isn't display inline working? I am having a really odd situation here. I have spent the last 7 hours researching why I cannot get display: inline; to work at all, unless it's on my main page. Nothing seems to be helping. Here is the relevant coding. <!DOCTYPE html> <html> <head> <title>Contact Info</title> <link rel="stylesheet" type="text/css" href="style.css"/> </head> <body> <div class="name"> <p>*****<p> <a href="index.html">Go Back</a> </div> <div class="contact"> <p> <span style="color:#000000">By Phone:</span> <a href="tel:*******">**********</a> </p> <p> <span style="color:#000000">By Email:</span> <a href="mailto:****@***.ca">****@****.ca</a> </p> <p> <span style="color:#000000">By Mail:</span> <span style="color:#3300cc">***************</span> </p> </div> </body> And here is the CSS. .name { display: inline; } The result is the two items, (The name "****" and the "Go Back" link), appear one on top of each other. I have tried making it a list, but that had no effect. I tried making them both links, but that had no effect. display: inline-block; also has no effect. Nothing I do has any effect on the div class name. I tried changing the name of the div class several times no effect. A: The problem here is the the <p> tag is also a block level element. One solution would be to add a style such that a <p> within the .name div is also inline .name, .name p {display: inline;} See https://jsfiddle.net/t0z2p9bn/ It would be better to change your html such that the stars are not contained within a <p> tag <div class ="name"> ***** <a href="index.html">Go Back</a> </div> See https://jsfiddle.net/t0z2p9bn/1/
[ "puzzling.stackexchange", "0000052114.txt" ]
Q: What is this useless thing? We do this , but won't have a clue we did it , Sometimes it leads to fantasy , sometimes just nothing , Sometimes long , sometimes short , It is most useless thing humans are doing from generations , What is this useless thing ..? A: Is that A dream ? We do this , but won't have a clue we did it , We dream , but in morning we forget it Sometimes it leads to fantasy , sometimes just nothing , self explanatory, sometimes its just a blank dream Sometimes long , sometimes short , dream's is long and short at times It is most useless thing humans are doing from generations , Dreams doesnt help us anyway
[ "stackoverflow", "0010052023.txt" ]
Q: Getting xml data where attribute equals number I am trying to implement the Expedia API and I have run into an issue. I need to get the description tag of a parent tag with a certain attribute number. This is what I have tried and it is not working: $data->RoomTypes->RoomType['roomCode="17918"']->description; I do not know if this is the right syntax. If I were going to look for it in mysql it would look something like this: mysql_query("SELECT description FROM RoomType WHERE roomCode = '17918'"); How would I go about doing this in xml with php?? Any help would be greatly appreciated!! Thank you in advance! A: Generally speaking, for XML queries, node attributes must be prefaced with a @ for matching. You haven't specified what XML library you're using but if it's following conventions/standards, you'd probably want $data->RoomTypes->RoomType['@roomCode="17918"']->description; ^--- instead.
[ "stackoverflow", "0055171150.txt" ]
Q: Buttons in nav instead of anchor? I've been reading up on web accessibility and read that anchor tags should only be used when the user will be taken to another URL without JavaScript. But buttons should be used whenever some other behavior should happen, such as opening a modal. So I'm wondering if it's okay or expected to have both buttons and anchors in a nav. Something like this: <nav> <a href="/">Home Page</a> <a href="/about">About Page</a> <button>Sign Up</button> </nav> Say in this situation the signup button launches a modal or does some other behavior that doesn't take the user to a different URL. Is it okay to have both in the nav? I'm not concerned about styling, I'll make these look consistent, but I'm wondering what's the most correct way to handle something like this? A: From an accessibility perspective, using both links and buttons is the semantically correct way to go. The links take you to another page (or somewhere else on the current page) and buttons perform an action. A screen reader user will understand when they hear "link" or "button" in the same <nav> that different actions will happen.
[ "stackoverflow", "0003219879.txt" ]
Q: coding standards in yii framework is there any coding standard which follows yii framework, and where it is specified A: You can find them in Yii basic Documents Yii Basic Convention A: The following code style is used for Yii 1.x development: https://github.com/yiisoft/yii/wiki/Core-framework-code-style CodeSniffer Coding Standard Repo: https://github.com/Ardem/yii-coding-standard
[ "stackoverflow", "0042092218.txt" ]
Q: How to add a label to Seaborn Heatmap color bar? If I have the following data and Seaborn Heatmap: import pandas as pd data = pd.DataFrame({'x':(1,2,3,4),'y':(1,2,3,4),'z':(14,15,23,2)}) sns.heatmap(data.pivot_table(index='y', columns='x', values='z')) How do I add a label to the colour bar? A: You could set it afterwards after collecting it from an ax, or simply pass a label in cbar_kws like so. import seaborn as sns import pandas as pd data = pd.DataFrame({'x':(1,2,3,4),'y':(1,2,3,4),'z':(14,15,23,2)}) sns.heatmap(data.pivot_table(index='y', columns='x', values='z'), cbar_kws={'label': 'colorbar title'}) It is worth noting that cbar_kws can be handy for setting other attributes on the colorbar such as tick frequency or formatting. A: You can use: ax = sns.heatmap(data.pivot_table(index='y', columns='x', values='z')) ax.collections[0].colorbar.set_label("Hello")
[ "stackoverflow", "0015938584.txt" ]
Q: Java Main Method Magic Numbers So im trying to get rid of two magic numbers that i have in my main method. I tried making them static fields but i just get a different checkstyle error. I'm looking for a way to make my main method check out completely with checkstyle. These are the checkstyle errors i get: '2000' is a magic number '262' is a magic number These are the checkstyle errors when i make them static fields: Name 'twothou' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'. Name 'twosixtytwo' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'. P.S. if i try to make the variables non static it wont let me compile. Thanks for the help. A: The "Magic Number" warnings are telling you that you should use a numeric constant instead of a hard-coded number in your code. The other errors just mean that you should use standard naming practices for your identifiers. A: I believe you need only change your field variable names to all CAPS. Try TWO_THOU and TWO_SIXTY_TWO.
[ "salesforce.stackexchange", "0000088321.txt" ]
Q: LiveAgent.startChat(): wrong redirecting <apex:page docType="html-5.0" showHeader="false" cache="true" > <head> Redirecting to the Liveagent chat Page </head> <div id="liveagent_invite_button_5732500000XXXXX" style='margin:0px; padding: 0px; width:400px; border-radius:8px; display: none;' > <!-- DEPLOYMENT --> <script type='text/javascript' src='https://c.la1-c1cs-lon.salesforceliveagent.com/content/g/js/34.0/deployment.js'></script> <script> //------------------------------------------------------- // In this part I insert informations that I will need when I will // open the chat with the Agent. //------------------------------------------------------- liveagent.addCustomDetail("IdAOL", new Date().getTime()); liveagent.findOrCreate("Info__c").map("ID_AOL__c", "IdAOL", false, false,true); liveagent.findOrCreate("Info__c").showOnCreate(); liveagent.findOrCreate("Info__c").saveToTranscript("Info__c","Info__c"); liveagent.findOrCreate("Survey_Operatore__c").map("ID_AOL__c", "IdAOL", false, false,true); liveagent.findOrCreate("Survey_Operatore__c").showOnCreate(); liveagent.findOrCreate("Survey_Operatore__c").saveToTranscript("Survey_Operatore__c","Survey_Operatore__c"); liveagent.init('https://d.la1-c1cs-lon.salesforceliveagent.com/chat', '5722500000XXXXX', '00D25000000XXXX'); //---------------------------------------------- // start of the chat giving us the problem!!! liveagent.startChat('5732500000XXXXX', true); </script> // URL-hacking I am NOT using anymore // <body onload="window.location.href = 'https://1c3.la1-c1cs-lon.salesforceliveagent.com/content/s/chat?language=it#deployment_id=57225000000XXXX&org_id=00D25000000XXXX&button_id=5732500000XXXXX';"> </body> <!-- FINE DEPLOYMENT --> </div> </apex:page> XXX nb= I don't want solve through URL-hacking. XXX The page redirects to a PreChat that is NOT on the invitation. I think it could be a Salesforce issue, but I cannot find it on the web. A: At the end we have opened a case to Salesforce and there was a solution not yet documented by Salesforce (but I think they will do it as soon as possible). It is necessary to change the liveagent.startchat() with the following timeout: setTimeout(function(){ liveagent.startChatWithWindow('573250000008OLT', 'window'); },2000);
[ "stackoverflow", "0059001222.txt" ]
Q: Fild all xls files in subdirectories and move them to a folder based on file creation date I have a folder that contains subfolders each with many excel spreadsheet. I am trying to get powershell to search through the subdirectories then move all the xls file with the same creation date into a new folder of that creation date. I am close I think here is my code. What is happening is that it only looks at file in "reporting" and not the subfolders of "reporting". Get-ChildItem "c:\users\username\documents\reporting\*.xls" -Recurse | foreach { $x = $_.LastWriteTime.ToShortDateString() $new_folder_name = Get-Date $x -Format yyyy.MM.dd $des_path = "c:\users\username\documents\$new_folder_name" if (test-path $des_path){ move-item $_.fullname $des_path } else { new-item -ItemType directory -Path $des_path move-item $_.fullname $des_path } } A: There is no need to first use ToShortDateString() on the LastWriteTime property and then use that to recreate the date in order to format it. Because you are using the -Recurse switch to search subfolders aswell, the code can be adjusted to also the -Include parameter like: $sourcePath = 'c:\users\username\documents\reporting' $targetPath = 'c:\users\username\documents' Get-ChildItem $sourcePath -Include '*.xls', '*.xlsx' -File -Recurse | ForEach-Object { $des_path = Join-Path -Path $targetPath -ChildPath ('{0:yyyy.MM.dd}' -f $_.LastWriteTime) if (!(Test-Path -Path $des_path -PathType Container)) { # if the destination folder does not exist, create it $null = New-Item -Path $des_path -ItemType Directory } $_ | Move-Item -Destination $des_path -Force -WhatIf } The -WhatIf switch at the end of the Move-Item is for testing. Once you are satisfied with the text shown in the consoe, remove that switch to actually start moving the files.
[ "stackoverflow", "0035790113.txt" ]
Q: unable to commit a file, accidentally renamed with mv I've accidentally used mv to rename a file which was under git. I renamed the file from lower case to uppercase keeping the name same. mv abc.java ABC.java I've also made changes and committed the file after that . How do I now make an actual git rename of this file? Git bash doesn't seem to understand the difference between ABC.java and abc.java. I'm not sure what changed on master(by others) but after moving to a branch, I'm no more able to commit my changes to the file. It says the old file index still exists. $ git commit -m "renamed to uppercase" ABC.java fatal: Will not add file alias 'dir1/ABC.java' ('dir1/abc.java' already exists in index) When I do git status, it shows the renamed files but doesn't let me commit the renamed files. If I try to do a delete abc.java(which is actually not present at least locally), again (I think because of case insensitivity) git deletes the new one. If I clone a new repo out of this, the repo still pulls out the files with old name(abc.java) but all my changes until the recently failing ones are there in it. A: A simple git commit -m "message" without any file path parameter did the trick for me. It updated the index I think or atleast finally it was able to recognize abc is to be updated to ABC.. Thank you all..
[ "stackoverflow", "0063714593.txt" ]
Q: Apply shift function group of rows in pandas I am trying to create new column feature from curr_value feature. Here, I want get the value from previous current value, using df.curr_value.shift(fill_value=-1) I can get the previous value. How do apply shift to only unique 'uid' columns. For example, In below example, I want to apply shift to uniqie ID values. df[df['uid']==1].curr_value.shift(fill_value=-1) Is there any other way in pandas so that I dont need to iterate unique uid values ? import pandas as pd import numpy as np events = np.array([[1, 1, 1], [1, 2, 4], [1, 3, 3], [1, 3, 4], [2, 1, 4], [2, 2, 3]]) df=pd.DataFrame(data=events, columns=["uid", "eid", "curr_value"]) A: Yes we can do it with groupby df['pre'] = df.groupby('uid')['curr_value'].shift(fill_value=-1) Out[5]: 0 -1 1 1 2 4 3 3 4 -1 5 4 Name: curr_value, dtype: int32
[ "diy.stackexchange", "0000171193.txt" ]
Q: How might one trip a breaker from a GFCI outlet? Somewhat derivative of How can I trip a breaker from the outlet, how could someone relatively safely and quickly, with basic tools, trip a breaker at a GFCI outlet (relatively safely meaning not getting electrocuted or starting a fire)? If something conductive and grounded is touched to the line or a drop of water falls on it, it's just going to trip the outlet, but there will still be power to it, right? That's the point of the GFCI. Thanks for answering the question, as well as all advice to not and never do such a thing. A: You want to trip the overcurrent detector (breaker) serving a GFCI outlet. No. Don't do it. What you're looking for is so similar to the other question that it really is a duplicate. It is wrong for all the reasons that one is wrong (and not insane in a certain industrial setting for the reasons I describe in my answer there). The presence of GFCI is irrelevant. (though of course if you use the hare-brained scheme in the other question, you have a good chance of frying the GFCI's innards; it will cheerfully allow the overcurrent if balanced, but its detection circuit will fail before the breaker will). Your parameters for "safety" are too narrow You are ignoring the likelihood of failing a circuit due to the overload opening a wire connection, or worse, setting the stage for a future arc-fault problem that could burn down the house the next time you load the circuit within reason. Then there's the matter of arc flash right there in your face. Plug in a radio, and snap breakers The way you solve this is by plugging in a radio and snapping breakers off until the radio stops. Pretty simple. If you don't have a radio, a vacuum cleaner will also do. You could also plug in two 1500W heater-fans and wait 20 minutes. That will trip any 15A or 20A circuit eventually. But again you are risking the same kind of wiring failures discussed in "too narrow" above.
[ "stackoverflow", "0054464875.txt" ]
Q: How to sort dates if these are strings in custom field? I have a series of posts, with dates in a custom fields like: 02/12/1978 01/11/1987 These are actual strings and not dates. Then I run the following, where I try to sort by dates, and I also attach each dates post id, in order them to run the posts ordered: $dateOrdered = []; while ( $queryPosts->have_posts() ) : $queryPosts->the_post(); $id = $post->ID; $date = usp_get_meta(false, 'usp-custom-80'); array_push($postOrdered, $id); $dateOrdered[] = array("date"=>$date, "id"=>$id); endwhile; endif; function custom_sort_dt($b, $a) { return strtotime($a['date']) - strtotime($b['date']); } usort($dateOrdered, "custom_sort_dt"); $dateOrdered = implode(',', array_column($dateOrdered, 'id')); But that is showing dates not ordered. A: assuming you have some type of "Post" class like class Post { public $date; } and you save them in an array named $posts, you can execute following code: $dates = array_map(function($p) { return DateTime::createFromFormat('d/m/yy', $p->date)->getTimestamp(); }, $posts); asort($dates); and have a sorted $dates array. the values are unix-timestamps. Edit: the dates are in the format dd-mm-yyyy, so we need to use 'd-m-yy'. We also need to fully qualify DateTime by adding a \ in front of it. $postOrdered[] = []; while ($queryPosts->have_posts()) { $queryPosts->the_post(); $id = get_the_ID(); $postOrdered[$id] = \DateTime::createFromFormat('d-m-yy', usp_get_meta(false,'usp-custom-80'))->getTimestamp(); } asort($postOrdered); $ids = array_keys($postOrdered) to echo the post content then use foreach($postOrdered as $id=>$date) { echo get_post($id)->post_content . '<br />'; }
[ "hinduism.stackexchange", "0000008824.txt" ]
Q: What happened to Pandavas in future lives? Did the Pandavas eventually take rebirth? If they did, who were they and what happened to them? A: Arjuna was reborn as Kannappa Nayanar, one of the 63 great Shiva-bhaktas in South India. When Arjuna fought with Lord Shiva as a Kirata to obtain the Pasupatastra, he had at first insulted him based on his caste (although later he admired the hunter). And after realising who He really was, Arjuna fell at Mahadeva's feet and repeatedly asked for his grace. Therefore, as a combined result of this, Mahadeva told Arjuna that he will have to take another birth, but will live only for sixteen years. He would perform Shiva-bhakti for six days, and return back to His abode. Thus, Arjuna was born as Kannappa Nayanar. http://www.sacred-texts.com/hin/m03/m03039.htm https://en.wikipedia.org/wiki/Kannappa_Nayanar http://www.shaivam.org/nakannap.html http://www.shaivam.org/nakanna1.html A: No Arjun didn't take rebirth. In fact he attained Vaikunta , the highest of all positions . The Mahabharata itself clearly mentions it. In Gita Krishna himself describes that no one is dearer to him as Arjuna. In fact Krishna-Arjun were Nara-Narayana. There is no question of rebirth for Arjuna. The story of Kannappa is different . As per original Mahabharata, Arjuna attained Vishnu Loka He beheld Govinda endued with his Brahma-form. It resembled that form of his which had been seen before and which, therefore, helped the recognition. Blazing forth in that form of his, he was adorned with celestial weapons, such as the terrible discus and others in their respective embodied forms. He was being adored by the heroic Phalguna, who also was endued with a blazing effulgence. The son of Kunti beheld the slayer of Madhu also in his own form. Those two foremost of Beings, adored by all the gods, beholding Yudhishthira, received him with proper honours. From Section 4 Swargarohanika Parva.
[ "stackoverflow", "0036482747.txt" ]
Q: Multiple instances of same variable I'm using an AJAX call to pull filenames from a database which are then used to populate a carousel with images of the same name. My web app makes use of tabs which when tapped, reload the AJAX and pull from the database a different set of filenames which then repopulate the carousel. What I'm finding is when the web app initially loads, the carousel works fine, but if I tap any of the tabs, the carousel begins to function incorrectly, i.e. the first time I tap and then use the carousel the carousel moves by two images at at time, a second tap and the images move three at a time, so on and so forth. If I check console I can see that following the call, when I click either the left or right arrow in the carousel, it's as if there are two instances of the same variable, or as if both AJAX calls are being called in some way. Image attached to show what I mean. As you can see, following initial load everything is fine, however once any subsequent calls are made it's as if the count from the previous call continues, and a secondary count also starts associated with the new data, or a third or fourth or fifth, dependent on how many calls have been made. $('.tabs-nav li').on('click', function() { tabName = $(this).html(); place = 0; products = getProductDetails(selected); //AJAX call data = dealWithData(products, place); //Deferred object that works data }); A: Sounds like you are having a scoping issue. The easiest way is to have your logic in a closure so your variables get scoped to the particular tab. So instead of something like this: var place,count $(".tabs").on('click',function(){/*shares same place & count */}); it would look like this: $(".tabs").each(function(){ var place,count $(this).on('click',function(){/*each has their own place,count*/}); });
[ "stackoverflow", "0022855638.txt" ]
Q: Alternative to Cucumber? When doing BDD, it seems that Cucumber is the default tool to specify behaviors, however the Cucumber website and articles look a bit out of date and not very active. What are the alternatives ? A: Cucumber is active, functionally, stable and very easy and productive to use. Serenity BDD is a bundle of Cucumber with WebDriver, but it is clunky and badly over-engineered. JBehave is an alternative, it is more complex and a much steeper learning curve than Cucumber. A: A very nice library with advanced tooling for Eclipse: Jnario http://jnario.org A: One that I have found in the past year since I posted the question: Robot Framework
[ "computergraphics.stackexchange", "0000004062.txt" ]
Q: Why do GPUs still have rasterizers? Despite advancements modern GPUs still have fixed rasterizers. Highly customizable, with programmable shaders but nevertheless not fully programmable. Why is that? Why can't GPUs be simply massively parallel devices with universal computing units where rasterizer is just a software for that device provided by the user? Is having fixed function hardware so beneficial performance-wise that such approach is unfeasible? A: In short, performance reasons are why they aren't programmable. History and Market In the past, there used to be separate cores for vertex and fragment processors to avoid bloated FPU designs. There were some mathematical operations you could only do in fragment shader code for instance (because they were mostly only relevant for fragment shaders). This would produce severe hardware bottlenecks for applications that didn't max out the potential of each type of core. As programmable shaders became more popular, universal units were introduced. More and more stages of the graphics pipeline were implemented in hardware to help with scaling. During this time, GPGPU also became more popular, so vendors had to incorporate some of this functionality. It's still important to note though that the majority of the income from GPUs were still video games, so this couldn't interfere with performance. Eventually a big player, Intel, decided to invest in programmable rasterizers with their Larrabee architecture. This project was supposed to be groundbreaking, but the performance was apparently less than desired. It was shut down, and parts of it were salvaged for Xeon Phi processors. It's worth noting though that the other vendors haven't implemented this. Attempts at Software Rasterizers There have been some attempts at rasterization through software, but they all seem to have issues with performance. One notable effort was an attempt by Nvidia in 2011 in this paper. This was released close to when Larrabee was terminated, so it's very possible that this was a response to that. Regardless, there are some performance figures in this, and most of them show performance multiple times slower than hardware rasterizers. Technical Issues with Software Rasterization There are many issues that were faced in the Nvidia paper. Here are some of the most important issues with software rasterizers though: Major Issues Interpolation: The hardware implementation generates interpolation equations in specialized hardware. This is slow for the software renderer since it had to be done in the fragment shader. Anti-aliasing: There were also performance issues with anti-aliasing (specifically with memory). Information regarding the sub-pixel samples must be stored on-chip memory, which isn't enough to hold this. Julien Guertault pointed out that the texture cache/cache may be slower with software. MSAA certainly has issues here because it overflows the cache (the non-texture caches) and goes into memory off of the chip. Rasterizers compress data that is stored in that memory, which also helps with performance here. Power Consumption: Simon F pointed out that power consumption would be lower. The paper did mention that custom ALUs are in rasterizers (which would reduce power consumption), and this would make sense since fragment and vertex processing units in the past used to have custom instruction sets (so likely custom ALUs as well). It certainly would be a bottleneck in many systems (e.g., mobile), although this has implications beyond performance. Summary TL;DR: there are too many inefficiencies that software rendering can't past, and these things add up. There are also many larger limitations, especially when you are dealing with VRAM bandwidth, synchronization problems, and extra computations.
[ "stackoverflow", "0029619539.txt" ]
Q: How to update a production server without overwriting user files? I'm new to web development, and I can't find the answer to this simple question. I'm at my wits end here and any help would be greatly appreciated! I need to regularly update files on my live website, but I feel the workflow I follow is highly inefficient: I manually keep track of whether a directory/file has been modified on my localhost vis-a-vis the production server For directories/files which have been modified, I replace the server files with the updated ones using FTP There are user-uploaded files (e.g. photos) in some directories, and I have to be extra careful to ensure I don't overwrite these "live" directories with the test directories used on my localhost. (This feels so wrong!) Clearly, I'm missing a best practice here - but I can't find the answer despite days of searching on the net: I've considered using Git/SVN - but it doesn't seem to make sense for me since I'm a lone developer and don't have multiple people working on the same files Filezilla has this useful feature which helps mark modified directories/file - but this doesn't seem to be an ideal solution What am I missing? PS - I'm using the PHP, MySQL, Apache stack on a shared hosting server. A: I would suggest you still go for Git / Tortoise SVN The best part is feature based branching. When each branch is a new feature, you can always experiment there without disturbing the features that are already working. Once the new feature is functional, and merged to your main branch, then you can delete the feature branch Apart from branching and forking, there are so many features in GIT and Tortoise SVN. It shows nice comparison changes between codes (+ and green) for added, (- and red ) for removed. I found extremely handy when working on CSS in RWD Merging also becomes easier and frictionless. Resolving conflicts is also a good knowledge to have It can prove worthy even for lone developer. Separate branch is not only for multiple users. You can create a branch for experimenting. In a branch even if you are ahead of many steps you can always switch back to where you branched from. For reference http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-preface-features.html http://www.hongkiat.com/blog/github-overlooked-features/
[ "stackoverflow", "0006687065.txt" ]
Q: Android webview settings, disable some things I am using myWebview.getSettings().setBuiltInZoomControls(true); to set zoom controls on my webview. I realize this enables a variety of zoom controls that are different on every phone/device. For aesthetic purposes I would like to specifically turn on and turn off some features, for instance, the +/- zoom buttons that appear in the corner These don't fit in my layout. Pinch to zoom? OK Double tap to zoom? OK actual zoom buttons? No thanks A: I'm not sure that this is possible with the provided methods. There's a setDisplayZoomControls(), but that only works for API11+. A previous question here suggests a possible approach, though it looks somewhat cumbersome.
[ "rus.stackexchange", "0000422194.txt" ]
Q: Нужны ли запятые в оборотах со словом "как"? Скоро будет 15 лет() как я возглавляю компанию. Как практикующий врач()я стараюсь уделять достаточно внимания каждому пациенту. A: 1) Скоро будет 15 лет, как я возглавляю компанию. Здесь запятая ставится, это СПП. Но запятая не ставится при инверсии: Я скоро 15 лет как возглавляю компанию. Другие примеры: Я скоро пять лет как живу в Москве. Занятия вот уже месяц как начались. Тебе есть в мире что забыть. 2) Как практикующий врач, я стараюсь уделять достаточно внимания каждому пациенту. Оборот со значением причины обособляется. Для сравнения: Я интересуюсь этой проблемой (именно) как практикующий врач. Оборот со значением "в качестве" не обособляется. Здесь по смыслу должно подразумеваться какое-либо противопоставление, например как практикующий врач и как научный работник. Паузы нет, логическое ударение делается на обороте.
[ "tex.stackexchange", "0000374506.txt" ]
Q: Tikz, put part of text into boxes Good morning. I try to get the following figure using Tikz environment. I was thinking of using \node but the problems are the labels (Box A and Box B) and the numbers outside of boxes. A: You need a matrix node and two fit nodes. \documentclass[tikz,border=2mm]{standalone} \usetikzlibrary{positioning, matrix, fit} \begin{document} \begin{tikzpicture} \matrix (A) [matrix of nodes] {1 & 2 & 3 & 4 & 5\\ 1 & 1 & 2 & 1 & 2\\ 1 & 2 & 3 & 4 & 5\\ 1 & 1 & 2 & 1 & 2\\ 1 & 2 & 3 & 4 & 5\\ 1 & 1 & 2 & 1 & 2\\ 1 & 2 & 3 & 4 & 5\\ 1 & 1 & 2 & 1 & 2\\ 1 & 2 & 3 & 4 & 5\\ }; \node[draw=blue, thick, inner sep=2pt, fit=(A-6-3.north west) (A-9-5.south east)] (BB) {}; \node[draw=red, thick, inner sep=2pt, fit=(A-4-2.north west) (BB.south east)] (BA) {}; \node[red, right= 0mm of BA.north east] (LA) {Box A}; \node[blue] at (BB-|LA) {Box B}; \end{tikzpicture} \end{document}
[ "stackoverflow", "0010219302.txt" ]
Q: Yet unknown variables inside array Is there a way to add some kind of parameters to array (yet unknown variables)? As you can see here, i dont know the userID in advance (before the mysql fetch), so i cant properly form a link leading to edit page. <?php $box = array ('1'=>"<a href='edit.php?id=/PROBLEM??/'>edit</a>",'2'=>'Cannot edit'); while ($row = mysql_fetch_array($something)) { ?> <tr> <td><?php echo $row["Name"]; ?></td> <td><?php echo $box[$row["editable"]]; ?></td> </tr> <?php } ?> $row["editable"] returns 1 or 2, depends on database record which returns if user is editable or not. A: You can use sprintf(): $box = array ('1'=>"<a href='edit.php?id=%d'>edit</a>",'2'=>'Cannot edit'); echo sprintf($box[$row["editable"]], ID_HERE)
[ "cooking.stackexchange", "0000052105.txt" ]
Q: What is the easiest way to remove the papery covers from the peanuts? Intention is to make peanut butter. What is the easiest way to achieve the said aim? A: Here's someone with a lot of experience doing it! video Dropping the peanuts into boiling water for a couple of minutes, then draining and rinsing in cold water is supposed to make them easier and quicker to peel. I've heard freezing them overnight helps. One method method that I have actually done is to peel them by rubbing them with a towel while they are still warm from being roasted. The trick there is to only roast small batches at a time so you can get to them all before they cool.
[ "stackoverflow", "0049722785.txt" ]
Q: How can I delete an instance of a class within that class? I want to know how you can delete a instance within the class. I am trying del self, but it doesn't seem to work. Here's my code: class Thing: def __init__(self): self.alive = True self.age = 0 def update(self): self.age += 1 def kill(self): if self.age >= 10: del self def all(self): self.update() self.kill() things = [] for i in range(0, 10): thing.append(Thing()) while True: for thing in things: thing.all() I specifically want to delete the instance inside the class. I have also replaced del self with self = None, but this statement doesn't seem to have any effect. How can I do this? A: You can't do quite what you're asking for. Python's del statement doesn't work like that. What you can do however, is mark your instance as dead (you already have an attribute for this!), and then later, filter the list of objects to drop the dead ones: class Thing: def __init__(self): self.alive = True # use this attribute! self.age = 0 def update(self): self.age += 1 def kill(self): if self.age >= 10: self.alive = False # change it's value here rather than messing around with del def all(self): self.update() self.kill() things = [] for i in range(0, 10): thing.append(Thing()) while True: for thing in things: thing.all() # you had a typo on this line things = [thing for thing in things if thing.alive] # filter the list Note that the loops at the end of this code run forever with no output, even after all the Thing instances are dead. You might want to modify that so you can tell what's going on, or even change the while loop to check if there's are any objects left in things. Using while things instead of while True might be a reasonable approach!
[ "stackoverflow", "0053519328.txt" ]
Q: How to display selected contact using pickContact() - ionic-v3 i want display selected contact detail in input, in alert showing contact details. so i want display that contact detail in my form. any idea how to do…please help! home.ts import { Contact, ContactField, ContactName, Contacts } from '@ionic-native/contacts'; : constructor(public navCtrl: NavController, public navParams: NavParams, private contacts: Contacts) { this.contacts.pickContact().then((contact)=>{ alert("contacts:-->"+ JSON.stringify(contact)); }); } home.html <ion-content padding> <form (ngSubmit)="saveItem()" ng-controller="AppCtrl"> <ion-item> <ion-label>Name</ion-label> <ion-input type="text" [(ngModel)]="contact.displayName" name="displayName"></ion-input> </ion-item> <ion-item> <ion-label>Phone</ion-label> <ion-input type="tel" [(ngModel)]="contact.phoneNumbers" name="phoneNumbers"></ion-input> </ion-item> <ion-item> <ion-label>Birth</ion-label> <ion-datetime displayFormat="DD/MM/YYYY" [(ngModel)]="contact.birthday" name="birthday"></ion-datetime> </ion-item> </form> </ion-content> A: Try contact = { displayName:null, phoneNumbers:null, birthday:null }; selectContact(){ this.contacts.pickContact().then((contact)=>{ alert("contacts:-->"+ JSON.stringify(contact)); this.contact.displayName = contact.displayName; this.contact.phoneNumbers = contact.phoneNumbers[0].value; contact.birthday = contact.birthday; }); } Note : property name check and assign from response.
[ "stackoverflow", "0004322494.txt" ]
Q: How to calculate/profile percentage of parallelized C# Code Greeting, I'm working on performance improvement for my application by enabling the multi-thread. I learned from the "Amdahl's law", it requires >50% of parallelized code to achieve 2x speedup in 8 cores processor. Hence I just wondering is there any tool in the market provides parallelized code coverage or profiling that can help me to improve the performance? A: If you're using vs 2010, you can use the concurrency visualizer for profiling multi-threaded apps.
[ "stackoverflow", "0014308527.txt" ]
Q: Interface-sensitive operations in Java This is my overall workflow. First create an interface: public interface foo { void bar(Baz b); } Then make, for example, a vector with different objects that all implement said interface: myVector.add(new Ex); //both Ex and Why implement foo. myVector.add(new Why); And finally, use the interface: for(int i=0; i<myVector.size(); i++) { myVector.get(i).bar(b); } However, for obvious reasons, this produces a compile time error: The method bar() is undefined for the type Object Casting won't work because Ex and Why aren't related. Try-catch casting to Ex and then Why is a horrible work-around. Making both Ex and Why extend Bar_doers also doesn't sound succinct either, as that would be doing away with interfaces. How can I perform operations that care about whether an Object implements a given interface, not whether an object is of a given class? A: You need to read about generics. Assuming you were using a standard Java container, then the solution in your case is to define myVector thus: List<foo> myVector = new ArrayList<foo>();
[ "stackoverflow", "0025365378.txt" ]
Q: Push json data to existing array in angular js I'm having issues with pushing data to an existing array. You can see I'm posting the data to a table, however, when a user enters an 8 digit barcode, I like to push the data to the table. Factory angular.module('app.pickUpServ', []).factory('pickUpServ', ['$rootScope', '$http', function($rootScope, $http) { return { getPickUpList: function(data) { $http({ method: 'POST', url: 'app/Service/CourierService.asmx/BarcodeList', data: { "bardcodeVal": "", "courierType": "PICKUP", "userName": "aspuser" }, contentType: 'application/json; charset=utf-8', dataType: 'json', }).success(data).error(function(error) { console.log('Error - getPickUpList'); }); }, items: [{ "bardcodeVal": "", "courierType": "PICKUP", "userName": "aspuser" }], add: function(item) { this.items.push(item); console.log(item); } }; } ]); Controller angular.module('app.scanListCtrl', []).controller('ScanListCtrl', ['$scope', 'pickUpServ', function ($scope, pickUpServ) { //Get Pick Up Data if ($scope.title == 'Pick Up') { pickUpServ.getPickUpList(function (data) { $scope.items = data.d }); $scope.autoAddItem = function () { if (($scope.BarcodeValue + '').length == 8) { pickUpServ.add({ "barcodeVal": $scope.BarcodeValue, "courierType": "PICKUP", "userName": "aspuser" }); $scope.BarcodeValue = ""; } }; } } ]); HTML <div ng-controller="ScanListCtrl"> <div class="row prepend-top-md"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"> <i class="fa fa-barcode"></i>&nbspScan Item</h3> </div> <div class="panel-body"> <div class="input-group input-group-lg"> <input type="number" class="form-control" placeholder="Scan Item" ng-model="BarcodeValue" ng-change="autoAddItem()" is-focus> <span class="input-group-btn"> <button class="btn btn-info" type="button" ng-click="addRow()"> Add Barcode</button> </span></div> </div> <table class="table table-striped table-hover"> <thead> <tr> <th class="text-center" style="width: 3%"> # </th> <th> <i class="fa fa-barcode"></i>&nbspBarcode </th> <th> <i class="fa fa-medkit"></i>&nbspCSN </th> <th> <i class="fa fa-user"></i>&nbspUser </th> <th> <i class="fa fa-clock-o"></i>&nbspDate </th> </tr> </thead> <tbody> <tr ng-repeat="item in items | orderBy:'Id':true:reverse"> <td class="text-center"> [{{item.Id}}] </td> <td> {{item.BarcodeValue}} </td> <td> {{item.CSN}} </td> <td> {{item.LastName + ', ' + item.FirstName}} </td> <td> {{item.Created}} </td> </tr> </tbody> </table> </div> </div> </div> A: You are adding the new item, to other element outside the scope (inside the factory), must doing something like this: $scope.autoAddItem = function () { if (($scope.BarcodeValue + '').length == 8) { $scope.items.push({ "barcodeVal": $scope.BarcodeValue, "courierType": "PICKUP", "userName": "aspuser" }); $scope.BarcodeValue = ""; } }; If you want make all inside the factory must be something like this (and ignore the change above): angular.module('app.pickUpServ', []).factory('pickUpServ', ['$rootScope', '$http', function($rootScope, $http) { return { getPickUpList: function(callback) { var _this = this; $http({ method: 'POST', url: 'app/Service/CourierService.asmx/BarcodeList', data: { "bardcodeVal": "", "courierType": "PICKUP", "userName": "aspuser" }, contentType: 'application/json; charset=utf-8', dataType: 'json', }) .success(function(data) { _this.items = data.d; callback(_this.items) //This gonna set to $scope the items in factory and angular //link the object items to $scope.items (Code not tested but must work) }) .error(function(error) { console.log('Error - getPickUpList'); }); }, items: [{ "bardcodeVal": "", "courierType": "PICKUP", "userName": "aspuser" }], add: function(item) { this.items.push(item); console.log(item); } }; } ]); A: Figured it out... I used the $rootScope.items = data.d; to resolve my issue. Thank you everyone for helping me! Factory angular.module('app.pickUpServ', []).factory('pickUpServ', ['$rootScope', '$http', function($rootScope, $http) { return { getPickUpList: function(data) { $http({ method: 'POST', url: 'app/Service/CourierService.asmx/BarcodeList', data: { "bardcodeVal": "", "courierType": "PICKUP", "userName": "aspuser" }, contentType: 'application/json; charset=utf-8', dataType: 'json', }).success(function(data){ $rootScope.items = data.d; console.log(data.d); }).error(function(error) { console.log('Error - getPickUpList'); }); }, items: [], add: function(item) { $rootScope.items.push(item); console.log(item); } }; } ]); Controller angular.module('app.scanListCtrl', []).controller('ScanListCtrl', ['$scope', 'pickUpServ', function ($scope, pickUpServ) { //Get Pick Up Data if ($scope.title == 'Pick Up') { //$scope.items = pickUpServ.items; pickUpServ.getPickUpList(function (data) { $scope.items = data.d }); $scope.autoAddItem = function () { if (($scope.BarcodeValue + '').length == 8) { pickUpServ.add({ "barcodeVal": $scope.BarcodeValue, "courierType": "PICKUP", "userName": "aspuser" }); $scope.BarcodeValue = ""; } }; } } ]);
[ "stackoverflow", "0051029090.txt" ]
Q: How to insert for each Student Id 5 Interest Ids? I would like to be able to insert five Interest Ids in the Student_Interest table for each student Id. I tried that, but instead of getting 30 lines I get 72 (6 students in Student table and 12 interest in Interest table) : INSERT INTO Student_Interest (Id_Student, Id_Interest, Score) SELECT Id_Student ,Id_Interest ,ABS(Checksum(NewID()) % 5) + 1 FROM Student, Interest ORDER BY NEWID() Thanks for your help. A: What you need is CROSS JOIN : INSERT INTO Student_Interest (Id_Student, Id_Interest, Score) SELECT Id_Student, Id_Interest, i.Score FROM Student s CROSS JOIN (SELECT TOP (5) Score FROM Interest ORDER BY NEWID()) i;
[ "math.stackexchange", "0001284704.txt" ]
Q: Injective or one-to-one? What is the difference? What is the difference between the terms 'injective' and 'one-to-one', 'surjective' and 'onto', and 'bijective' and 'isomorphic'? A: Injective and one-to-one mean the same thing. Surjective and onto mean the same thing. Bijective means both injective and surjective. This means that there is an inverse, in the widest sense of the word (there is a function that "takes you back"). The inverse is so-called two-sided, which means that not only can you go there and back again, but you could also start at the other end, go back and then there again. Either way you end up where you started. Isomorphism is a bit different. It means that not only is there an inverse, but the inverse is "nice" (and the function itself must be "nice" too). For instance, in topology, we're mostly interested in continuous maps, so "nice" in that setting means "continuous". There are bijective, continuous maps where the inverse is not continuous. Other niceties include "linear" for vector spaces, "differentiable" for calculus / analysis and "homomorphism" in abstract algebra. Example: you have the function that takes the two intervals $(0, 1)$ and $[2, 3]$ and "glues" them together at one end to make $(0, 2]$. This is a bijection (every element in $(0, 1)$ stays put, and every element in $[2, 3]$ gets sent to $[1, 2]$ by subtracting $1$), so there is an inverse. However, this inverse is not continuous, and therefore the bijection is not an isomorphism. (In topology, isomorphisms are usually called homeomorphisms instead.) Another example: You can find a bijection from $\Bbb R$ to $\Bbb R^2$ (google "plane filling curves" to see some surjections, that you can find an injection is obvious enough, and with some mathematical mumbo-jumbo, you can combine the two to make a bijection). But you'd have to struggle to make it continuous, and it is provably impossible to make both the function and the inverse continuous. Note: the moment you start mixing in the word "morphism" in anything, there is always this "nicety" condition implied (a "morphism" is a nice function, whatever that means in your setting). This is from the part of mathematics called category theory, where you try to study functions without ever mentioning the elements of your sets. You often hear things like "there is a morphism here such that for every morphism there, there is a unique morphism..." and so on.
[ "stackoverflow", "0060505762.txt" ]
Q: Find nearest value X in ndarray in numpy, Python I have got a ndarray shaped into 2D matrix of values between 0 and 255. Let's name it img. Moreover, I have got value x between 0 and 255, for example 120. I want to create matrix dist_img which calculates distance to nearest value x or lower. So I would like to have something like this: x = 120 img = [[100, 120, 130], [110, 140, 160], [130, 150, 170]] some_function(img, x) And get something like this dist_img = [[0, 0, 1], [0, 1, 2], [1, 2, 3]] If I can be peaky, I would love to have distance in taxicab geometry, but Euclidean geometry will work. Sorry for poor English, but I hope everything is understandable. A: Make a mask of the values that match the condition and then use scipy.ndimage.morphology.distance_transform_cdt to make the distance map: import numpy as np from scipy.ndimage.morphology import distance_transform_cdt x = 120 img = np.array([[100, 120, 130], [110, 140, 160], [130, 150, 170]]) m = img <= x d = distance_transform_cdt(~m, 'taxicab') print(d) # [[0 0 1] # [0 1 2] # [1 2 3]]
[ "ja.stackoverflow", "0000032770.txt" ]
Q: ID毎の開始地点と終了地点のデータから各地点毎でIDをカウントする方法 以下のようなID毎の開始地点と終了地点のデータがあった場合、 各地点毎での有効なID数をSQLで集計する方法を考えているのですが いまいちいい方法が思いつきませんどなたかよい方法を教えていただけないでしょうか? ID毎の開始地点と終了地点のデータ ID,start,end 1,0,3 2,1,3 3,2,3 4,0,1 5,1,2 地点毎でのID集計 0地点:2人(1,4) 1地点:4人(1,2,4,5) 2地点:4人(1,2,3,5) 3地点:3人(1,2,3) ※前提としては開始地点と終了地点は時間軸等の連続性あるものとします。 A: MySQL でクロスジョインを使ってみました。 # 適当なテーブルを作成 CREATE TABLE id_tbl (ID int, start int, end int); # insert data SELECT * FROM id_tbl; +------+-------+------+ | ID | start | end | +------+-------+------+ | 1 | 0 | 3 | | 2 | 1 | 3 | | 3 | 2 | 3 | | 4 | 0 | 1 | | 5 | 1 | 2 | +------+-------+------+ # query SELECT C AS POINT, COUNT(C) AS COUNT, GROUP_CONCAT(ID) AS PERSONS FROM ( SELECT DISTINCT(C) FROM ( SELECT start AS C FROM id_tbl UNION ALL SELECT end AS C FROM id_tbl ) AS _ ORDER BY C ) AS _ CROSS JOIN id_tbl AS B ON C >= B.start and C <= B.end GROUP BY C; => +-------+-------+---------+ | POINT | COUNT | PERSONS | +-------+-------+---------+ | 0 | 2 | 1,4 | | 1 | 4 | 1,2,4,5 | | 2 | 4 | 1,2,3,5 | | 3 | 3 | 1,2,3 | +-------+-------+---------+
[ "stackoverflow", "0014232035.txt" ]
Q: How to add a prefix to a file before upload? CMS (Modx Evolution) that I`m currently using has ability to print some informations into site (like date/username etc.). I want to use those functions to work with plupload. Is it possible to add a prefix or completely rename file after (or before uploading) to server trough plupload depending on which user is actually logged in? Example: user uploads file test.txt, on server it will look username_test.txt A: try this <?php $username = 'username'; $tmp_name = $_FILES["file"]["tmp_name"]; $name = $username.$_FILES["file"]["name"]; move_uploaded_file($tmp_name, "$uploads_dir/$name"); ?>
[ "stackoverflow", "0056673612.txt" ]
Q: How to write a file to Google Cloud Storage directly without saving it in my application? I am trying to write an HTML file into Google Cloud Storage without saving the file in my node application. I need to create a file and immediately upload to the Cloud Storage. I tried using fs.writeFileSync() method, but it creates the file in my application and I do not want that. const res = fs.writeFileSync("submission.html", fileData, "utf8"); GCS.upload(res, filePath); I expect to save an HTML file in the Cloud Storage directly. Could you please recommend the right approach to me? A: The solution I believe is to use the file.save method that wraps createWriteStream, so this should work. const storage = require('@google-cloud/storage')(); const myBucket = storage.bucket('my-bucket'); const file = myBucket.file('my-file'); const contents = 'This is the contents of the file.'; file.save(contents, function(err) { if (!err) { // File written successfully. } }); //- // If the callback is omitted, we'll return a Promise. //- file.save(contents).then(function() {});
[ "stackoverflow", "0030889860.txt" ]
Q: Spring-MVC, Hibernate : Creating DTO objects from Domain objects I am working on a Spring-MVC application in which I am trying to search for List of GroupNotes in database. The mapping in my project is GroupCanvas has one-to-many mapping with GroupSection and GroupSection has one-to-many mapping with GroupNotes. Because of these mappings, I was getting LazyInitializationException. As suggested on SO, I should be converting the objects to a DTO objects for transfer. I checked on net, but couldnt find a suitable way to translate those. I have just created a new List to avoid the error, but one field is still giving me an error. I would appreciate if anyone tells me either how to fix this error or convert the objects to a DTO objects so they can be transferred. Controller code : @RequestMapping(value = "/findgroupnotes/{days}/{canvasid}") public @ResponseBody List<GroupNotes> findGroupNotesByDays(@PathVariable("days")int days, @PathVariable("canvasid")int canvasid){ List<GroupNotes> groupNotesList = this.groupNotesService.findGroupNotesByDays(days,canvasid); List<GroupNotes> toSendList = new ArrayList<>(); for(GroupNotes groupNotes : groupNotesList){ GroupNotes toSendNotes = new GroupNotes(); toSendNotes.setMnotecolor(groupNotes.getMnotecolor()); toSendNotes.setNoteCreationTime(groupNotes.getNoteCreationTime()); toSendNotes.setMnotetag(groupNotes.getMnotetag()); toSendNotes.setMnotetext(groupNotes.getMnotetext()); toSendNotes.setAttachCount(groupNotes.getAttachCount()); toSendNotes.setNoteDate(groupNotes.getNoteDate()); toSendList.add(toSendNotes); } return toSendList; } GroupNotesDAOImpl : @Override public List<GroupNotes> searchNotesByDays(int days, int mcanvasid) { Session session = this.sessionFactory.getCurrentSession(); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, -days); long daysAgo = cal.getTimeInMillis(); Timestamp nowMinusDaysAsTimestamp = new Timestamp(daysAgo); GroupCanvas groupCanvas = (GroupCanvas) session.get(GroupCanvas.class,mcanvasid); Query query = session.createQuery("from GroupSection as n where n.currentcanvas.mcanvasid=:mcanvasid"); query.setParameter("mcanvasid", mcanvasid); List<GroupSection> sectionList = query.list(); List<GroupNotes> notesList = new ArrayList<GroupNotes>(); for (GroupSection e : sectionList) { System.out.println("Section name is "+e.getMsectionname()); GroupSection groupSection = (GroupSection) session.get(GroupSection.class,e.getMsectionid()); Query query1 = session.createQuery("from GroupNotes as gn where gn.ownednotes.msectionid=:msectionid and gn.noteCreationTime >:limit"); query1.setParameter("limit", nowMinusDaysAsTimestamp); query1.setParameter("msectionid",e.getMsectionid()); notesList.addAll(query1.list()); } // I am getting the data below, but I get JSON errors. for(GroupNotes groupNotes : notesList){ System.out.println("Group notes found are "+groupNotes.getMnotetext()); } return notesList; } GroupCanvas model : @Entity @Table(name = "membercanvas") public class GroupCanvas{ @OneToMany(mappedBy = "currentcanvas",fetch=FetchType.LAZY, cascade = CascadeType.REMOVE) @JsonIgnore private Set<GroupSection> ownedsection = new HashSet<>(); @JsonIgnore public Set<GroupSection> getOwnedsection() { return this.ownedsection; } public void setOwnedsection(Set<GroupSection> ownedsection) { this.ownedsection = ownedsection; } } GroupSection model : @Entity @Table(name = "membersection") public class GroupSection{ @OneToMany(mappedBy = "ownednotes", fetch = FetchType.EAGER,cascade = CascadeType.REMOVE) @JsonIgnore private Set<GroupNotes> sectionsnotes = new HashSet<>(); public Set<GroupNotes> getSectionsnotes(){ return this.sectionsnotes; } public void setSectionsnotes(Set<GroupNotes> sectionsnotes){ this.sectionsnotes=sectionsnotes; } } GroupNotes model : @Entity @Table(name="groupnotes") public class GroupNotes{ @Id @Column(name="mnoteid") @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "mnote_gen") @SequenceGenerator(name = "mnote_gen",sequenceName = "mnote_seq") @org.hibernate.annotations.Index(name = "mnoticesidindex") private int mnoticesid; @Column(name = "mnotetext") private String mnotetext; @Column(name = "mnoteheadline") private String mnotetag; @Column(name = "mnotecolor") private String mnotecolor; @Column(name = "mnoteorder") private double mnoteorder; @Column(name = "attachmentcount") private int attachCount; @Column(name = "notedate") private String noteDate; @Column(name = "uploader") private String uploader; @Column(name = "activeedit") private boolean activeEdit; @Column(name = "notedisabled") private boolean noteDisabled; @Column(name = "noteinactive") private boolean noteInActive; @Column(name = "notecreatoremail") private String noteCreatorEmail; @Column(name = "prefix") private String prefix; @Column(name = "timestamp") private Timestamp noteCreationTime; @Transient private boolean notRead; @Transient private String tempNote; @Transient private String canvasUrl; @ManyToOne @JoinColumn(name = "msectionid") @JsonIgnore private GroupSection ownednotes; @JsonIgnore public GroupSection getOwnednotes(){return this.ownednotes;} public void setOwnednotes(GroupSection ownednotes){this.ownednotes=ownednotes;} @JsonIgnore public int getOwnedSectionId(){ return this.ownednotes.getMsectionid(); } @OneToMany(mappedBy = "mnotedata",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE) @JsonIgnore private Set<GroupAttachments> mattachments = new HashSet<>(); public Set<GroupAttachments> getMattachments() { return this.mattachments; } public void setMattachments(Set<GroupAttachments> mattachments) { this.mattachments = mattachments; } @OneToMany(mappedBy = "mhistory",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE) @JsonIgnore private Set<GroupNoteHistory> groupNoteHistorySet = new HashSet<>(); public Set<GroupNoteHistory> getGroupNoteHistorySet(){ return this.groupNoteHistorySet; } public void setGroupNoteHistorySet(Set<GroupNoteHistory> groupNoteHistorySet){ this.groupNoteHistorySet = groupNoteHistorySet; } @OneToMany(mappedBy = "unreadNotes",fetch = FetchType.LAZY,cascade = CascadeType.REMOVE) @JsonIgnore private Set<UnreadNotes> unreadNotesSet = new HashSet<>(); public Set<UnreadNotes> getUnreadNotesSet(){ return this.unreadNotesSet; } public void setUnreadNotesSet(Set<UnreadNotes> unreadNotesSet){ this.unreadNotesSet = unreadNotesSet; } //getters and setters ignored } Error log : org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.journaldev.spring.model.GroupNotes["ownedSectionId"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->com.journaldev.spring.model.GroupNotes["ownedSectionId"]) Kindly let me know what to do, as I am stuck on that error since some time. A: What I think that happens is Jackson tries to serialize all fields in the hierarchy based on getter methods. In some situation NullPointerException is thrown in the following method: @JsonIgnore public int getOwnedSectionId(){ return this.ownednotes.getMsectionid(); } replace it with the following method: @JsonIgnore public int getOwnedSectionId(){ if(this.ownednotes != null) return this.ownednotes.getMsectionid(); return 1; } I don't have an explanation why jackson tries to serialize it when is market with @JsonIgnore but you can give a try with my proposal
[ "stackoverflow", "0057514174.txt" ]
Q: Using Node.js on StackBlitz? I am trying to handle http requests on my web app which I created using StackBlitz' online IDE (I'm new to a lot of the tools I am going to mention). I am trying to handle a request, then respond with data from my firebase storage. I learned that to handle http requests I should use Node.js, and I know I can download it to my computer. But I am using StackBlitz, so I am not sure how to get Node.js there. I tried searching online and someone else sorta asked this question before, without answer though: Using Node fs on Stackblitz? Edit: I also heard that 'Express' might work for this, and it has an npm registry that I can use to add it to StackBlitz, trying that now. A: You can use repl.it and create your node application there, then you can access the url in your stackblitz angular app. repl.it/languages/nodejs example (node + express) https://repl.it/repls/HonoredFussyPdf
[ "electronics.stackexchange", "0000303616.txt" ]
Q: STM32F103 - Starting timers at the same time I am using an STM32F103 board (Blue Pill), and I have a simple application where I need to have two pulses on different pins. I achieve this using Timer3 and Timer4 configured with PWM output on two channels (one each). The problem is that the timers do not start at the same time, and they have an offset of about 3 µs. The main clock is running at 28 MHz. In the code, changing the order of these two lines will determine what timer starts first (which one is ahead with 3 µs of the other): HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2); HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_2); Is there something I can do? To be noted that in the same program I have Timer1 set up as Capture Compare No Output, and Timer2 to generate a 1.4 MHz clock in the same manner as Timer3 and Timer4. Later Edit. The called function in the HAL driver: HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel) { /* Check the parameters */ assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); /* Enable the Capture compare channel */ TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) { /* Enable the main output */ __HAL_TIM_MOE_ENABLE(htim); } /* Enable the Peripheral */ __HAL_TIM_ENABLE(htim); /* Return function status */ return HAL_OK; } A: The best way of doing this will be by using timer synchronization. See section 15.3.15 of the STM32F1 reference manual. Set TIM3 to "Enable" master mode (MMS field of TIM3_CR2), and set TIM4 to "Trigger mode" slave mode with trigger ITR2 (TS and SMS fields of TIM4_SMCR). If you've configured everything properly, starting TIM3 will also simultaneously start TIM4. (There is probably some way of doing this using the HAL, but I'm not familiar enough with it to say what that might be.)
[ "stackoverflow", "0034167540.txt" ]
Q: Symfony directory structure on cPanel site I'm building my first Symfony site that will eventually be hosted on a shared server/cPanel site. I'd like to have my Symfony/web content separate from the server files, though the way Symfony is structured, all the Symfony files are outside the public_html folder. But with a cPanel setup, there's already a lot of files and folders outside the public_html folder (mail, logs, .bashrc, .cpanel, www alias... and a dozen others). I worry that it feels messy if I put Symfony mixed in with all these files and there could be a conflict. I would rather it be in a directory by itself. The best idea I've had so far is to make a subdomain to host Symfony where I can manually choose the web folder, and then just do redirects to the subdomain. What do others do? A: This is how I decided to do it, and it seems like it will work pretty well. I just use the regular cPanel public_html as the document root, upload the whole Symfony contents to that directory, but then add an .htaccess file with the contents: RewriteEngine on RewriteCond %{REQUEST_URI} !web/ RewriteRule (.*) /web/$1 [L] And that protects the main Symfony contents from public access while at the same time putting it all in a directory by itself. It seems to work so far. If anyone has a better idea, I'm open to it!
[ "stackoverflow", "0019567222.txt" ]
Q: How to save a file from database to server in php I have a database table to store my templates(.docx file). I am using openTbs to work on that templates.My need is that to take out the template and store it in thee server itself, and edit using openTbs. My question is that how I can retrieve .docx file from database and store that in the server side.? (The storing may be temporary but i want to edit it using openTbs.) Thanks in advance....... A: It is bad practice to save binary data in the database, mostly when this data are intend to be processed by a file server, such as pictures or your DOCX. Anyway, since OpenTBS 1.8.1, you can open an DOCX (or any Ms Office, LibreOffie or zip archive) from a PHP file handle. You can use this feature to easily merge your template from the database : // retrieve binary data of the file $rs = mysql_query($dbc, "SELECT data FROM files WHERE id=$id"); $rec= mysql_fetch_array($rs, MYSQLI_ASSOC); mysql_free($rs); // create a temporary file $temp = tmpfile(); fwrite($temp, $rec['file']); unset($rec); // free PHP memory // Open the file with OpenTBS $TBS = new clsTinyButStrong; $TBS->Plugin(TBS_INSTALL, OPENTBS_PLUGIN); $TBS->LoadTemplate($temp); ...
[ "stackoverflow", "0000078913.txt" ]
Q: Single most effective practice to prevent arithmetic overflow and underflow What is the single most effective practice to prevent arithmetic overflow and underflow? Some examples that come to mind are: testing based on valid input ranges validation using formal methods use of invariants detection at runtime using language features or libraries (this does not prevent it) A: One possibility is to use a language that has arbitrarily sized integers that never overflow / underflow. Otherwise, if this is something you're really concerned about, and if your language allows it, write a wrapper class that acts like an integer, but checks every operation for overflow. You could even have it do the check on debug builds, and leave things optimized for release builds. In a language like C++, you could do this, and it would behave almost exactly like an integer for release builds, but for debug builds you'd get full run-time checking. class CheckedInt { private: int Value; public: // Constructor CheckedInt(int src) : Value(src) {} // Conversions back to int operator int&() { return Value; } operator const int &() const { return Value; } // Operators CheckedInt operator+(CheckedInt rhs) const { if (rhs.Value < 0 && rhs.Value + Value > Value) throw OverflowException(); if (rhs.Value > 0 && rhs.Value + Value < Value) throw OverflowException(); return CheckedInt(rhs.Value + Value); } // Lots more operators... }; Edit: Turns out someone is doing this already for C++ - the current implementation is focused for Visual Studio, but it looks like they're getting support for gcc as well.
[ "apple.stackexchange", "0000098649.txt" ]
Q: Does airplane-mode disable GPS? According to http://support.apple.com/kb/ht1355 airplane-mode on the iPhone shuts off Wi-Fi, Bluetooth, ...GPS. My understanding is that GPS-devices only /receive/ GPS signals, they don't transmit anything, so I don't understand why this needs to be shut down. [Of course, if the iPhone is running at all, then /it/ is emitting some RF, but I don't see why receiving GPS signals should cause an additional problem for the airplane.] I tested on an iPhone 3GS (IOS 6.1.3): Enabled airplane-mode, then turned-off the phone. Rotated the phone 180-degrees. Turned it back on (with airplane-mode still enabled). The compass-app still seemed to find North. Would someone be willing to do an independent test of this? A: Yes, airplane mode shuts down the radios that amplify all antenna circuitry. Compass isn't affected by airplane mode other than not being tuned by GPS location. Your observed relative changes will be mostly unaffected but absolute accuracy could suffer between one and ten degrees on much of the globe. Of course the GPS signals still hit the iPhone case and antennas, just the hardware doesn't do the work to fix a location from those signals while in airplane mode. (Nor does e software do any processing of the location updates which is a big part of the functionality for many people as opposed to the hardware side of the radios being idle / off / silent) A: I think Airplane Mode disables the hardware chips. GPS and 3G/LTE are on the same chip. I would say, Airplane Mode also disables GPS. A: The existing answers are now outdated. Since iOS 8.2, you can still use the GPS even in flight mode. Apple's statement says: If you have a device with iOS 8.2 or earlier, Airplane Mode will also turn off GPS. Source: https://support.apple.com/en-gb/HT204234
[ "stackoverflow", "0016984813.txt" ]
Q: Behavior of Initialization Blocks I have code which I am unable to understand, how it produces that output. Here is the code below- Code: class Bird { { System.out.print("b1 "); } public Bird() { System.out.print("b2 "); } } class Raptor extends Bird { static { System.out.print("r1 "); } public Raptor() { System.out.print("r2 "); } { System.out.print("r3 "); } static { System.out.print("r4 "); } } class Hawk extends Raptor { public static void main(String[] args) { System.out.print("pre "); new Hawk(); System.out.println("hawk "); } } Output: r1 r4 pre b1 b2 r3 r2 hawk Questions: My specific questions regarding this code are- When Hawk class is instationed, it cause Raptor class to be instationed, and hence the static code block runs first. But then, static code should be followed by non-static ones, before printing pre. Isn't it? Those non-static initialization blocks seem to be actually acting like constructors. So, can these be used as constructors in regular programming? A: static code should be followed by non-static ones, before printing pre. Isn't it? Running Hawk.main triggers the initialization of all three classes. This is when the static intitializers run; pre is printed; new Hawk() triggers the execution of instance initializers for all three classes. can these be used as constructors in regular programming? They end up compiled together with code from constructors into <init> methods. So yes, they are similar to constructor code. The key difference is that they run regardless of which constructor runs, and run before the constructor body. A: The static blocks are run when the class is loaded therefore they run even before your method main() runs. The initializer blocks are run before the constructors. The difference between a constructor and a initializer block is that a constractor can have parameters. Also be aware that the initializer blocks and constructors run first in the base class and afterwards in the subclass.
[ "stackoverflow", "0038326659.txt" ]
Q: Have to terminate all the loops according the condition given in inner loop I have five loops as shown below a.each do |i| b.each do |j| c.each do |k| d.each do |m| if somecondition.eql?true break end end end end end The above condition terminates only inner loop, Is there anyway can I terminate all the loops? A: The standard way is to use catch and throw. catch :foo do a.each do |i| b.each do |j| c.each do |k| d.each do |m| if somecondition.eql?true throw :foo end end end end end end
[ "elementaryos.stackexchange", "0000001793.txt" ]
Q: Does upgrading elementary OS Freya (0.3) result in 0.3.1? I have elementary Freya 0.3 installed. If I upgrade it fully, do I get Freya 0.3.1 (the same one that can be downloaded) or do I end up with some half-breed between these two? In the announcement of v0.3.1 someone commented: "If you’re already running Freya, you will already have received all of the above (with the exception of the newly added hardware support) in your regular updates." This is slightly confusing. Does that mean that newly added hardware support requires a new install or just an additional update? to which Daniel responded: A transitional package should be made available at some point in the future, but for now I would highly recommend a clean install as the best upgrade method. This answer seems to imply that simply upgrading Freya 0.3 does not in fact result in the same system as a clean 0.3.1 install. A: The kind of harsh but true answer is that you will never have the same exact thing as a clean install no matter OS you upgrade. There will always be some minor (and sometimes some major) differences, especially when the new version changes any default configuration files. Specifically regarding the new hardware enablement stack, this is not pulled down automatically. While theoretically everyone should experience better results, it's possible that the new hardware stack will give certain setups worse results. If you're not experiencing any issues with your hardware, you should probably remain on the 0.3.0 (Trusty-based) stack. If you need help upgrading to the new hardware stack from 0.3.0, please see this post
[ "electronics.stackexchange", "0000169285.txt" ]
Q: Initializing the ESC through microcontroller I have an esc and a brush less dc motor. the connections are given in the pictures. i have written the program for the micrcontroller such that it send 1ms high 19ms low pulses to esc for 5 seconds. then i change the high duration to 2ms and low to 18ms. but nothing happens at the esc not the motor. the motor doesnt rotates. i tried 1.5ms high too, but nothing happens. is there any initialization of esc, so that then pwm is sent to it for rotating the motor. i mean that is there any serial communication involved in it? if yes then what are the instruction? A: I have used 2 ESCs in a hovercraft project I built. Brushless ESCs expect a calibration at power up. Usually this is achieved by sending the high value pulse (2ms) first, waiting for around 2-3 seconds for the beep, then sending the low value (1ms) pulse, and waiting for another beep (another 2-3 seconds). ESC then identifies these are the values you will send for max and zero speed. After that you are free to speed up from zero. Usually, for most ESCs, the low pulse duration doesn't matter as long as it is around 20ms.
[ "askubuntu", "0001163685.txt" ]
Q: Problem installing R package with lblas and lapack dependencies I am trying to install the HMSC R package into RStudio Version 1.2.1335 and R version 3.6.1 (2019-07-05) -- "Action of the Toes" on a Linux Ubuntu 18.04.2 LTS System The code to install through R is as follows library(devtools) install_url('https://cran.r-project.org/src/contrib/Archive/BayesLogit/BayesLogit_0.6.tar.gz') install_github("hmsc-r/HMSC", build_opts = c("--no-resave-data", "--no-manual")) When installing BayesLogit_0.6.tar.gz I get the following error /home/barefootbushman/miniconda3/bin/../lib/gcc/x86_64-conda_cos6-linux-gnu/7.3.0/../../../../x86_64-conda_cos6-linux-gnu/bin/ld: cannot find -lblas /home/barefootbushman/miniconda3/bin/../lib/gcc/x86_64-conda_cos6-linux-gnu/7.3.0/../../../../x86_64-conda_cos6-linux-gnu/bin/ld: cannot find -llapack collect2: error: ld returned 1 exit status /usr/share/R/share/make/shlib.mk:6: recipe for target 'BayesLogit.so' failed make: *** [BayesLogit.so] Error 1 ERROR: compilation failed for package ‘BayesLogit’ * removing ‘/home/barefootbushman/R/x86_64-pc-linux-gnu-library/3.6/BayesLogit’ Error in i.p(...) : (converted from warning) installation of package ‘/tmp/RtmpL8qXxH/file18aa17542138/BayesLogit_0.6.tar.gz’ had non-zero exit status I have checked for the installation of -lblas and -lapack using sudo apt-get update Hit:1 http://nz.archive.ubuntu.com/ubuntu bionic InRelease Hit:2 http://nz.archive.ubuntu.com/ubuntu bionic-updates InRelease Hit:3 http://nz.archive.ubuntu.com/ubuntu bionic-backports InRelease Hit:4 https://repo.skype.com/deb stable InRelease Hit:5 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ InRelease Get:6 https://desktop-download.mendeley.com/download/apt stable InRelease [2,456 B] Ign:7 http://dl.bintray.com/basespace/BaseMount-DEB saucy InRelease Ign:8 http://dl.bintray.com/basespace/BaseSpaceFS-DEB saucy InRelease Hit:9 http://security.ubuntu.com/ubuntu bionic-security InRelease Hit:10 http://ppa.launchpad.net/inkscape.dev/stable/ubuntu bionic InRelease Get:11 http://dl.bintray.com/basespace/BaseMount-DEB saucy Release [1,838 B] Get:12 http://dl.bintray.com/basespace/BaseSpaceFS-DEB saucy Release [1,837 B] Hit:13 http://ppa.launchpad.net/marutter/rrutter/ubuntu bionic InRelease Fetched 6,131 B in 2s (4,067 B/s) Reading package lists... Done Followed by sudo apt-get install libblas-dev liblapack-dev Reading package lists... Done Building dependency tree Reading state information... Done libblas-dev is already the newest version (3.7.1-4ubuntu1). liblapack-dev is already the newest version (3.7.1-4ubuntu1). 0 upgraded, 0 newly installed, 0 to remove and 28 not upgraded. However, I still get the same error when attempting to install BayesLogit in R. Any help on how to overcome this error would be appreciated. Chris A: To install the HMISC R package in all currently supported versions of Ubuntu open the terminal and type: sudo apt install r-cran-hmisc The r-cran-hmisc package does not depend on either libblas-dev or liblapack-dev, so you won't get a cannot find -lblas or cannot find -llapack error message when trying to install r-cran-hmisc. The error message that you got when trying to install the HMISC R package is Anaconda's fault for sure, but I don't know where the culprit Anaconda file is located in your system. Usually when a path is borked by Anaconda you can symbolic link it back to the appropriate Ubuntu executable. If Anaconda has messed up too many paths in your system, the only way you're going to get rid of the mess is by completely uninstalling and purging Anaconda.
[ "stackoverflow", "0012204841.txt" ]
Q: MySQL query returning a negative row number Well this is an odd thing for sure. Am using MySQL to display a series of alerts, and the query I'm using separates by way of what level the alert is. The table has five columns, but the one being used here is the level column (alert level: 1 - normal; 2 - moderate; 3 - high). ID is used to only display the oddity with the query. The weird thing is when I run this query, it displays normally: SELECT * FROM `alerttxt` ORDER BY level ASC It loses an entry on the web page when I switch the order, but shows all the rows in PHPMyAdmin...which is odd itself: SELECT * FROM `alerttxt` ORDER BY level DESC But the minute I add in an extra element: SELECT * FROM `alerttxt` WHERE level = '2' ORDER BY ID ASC Things go haywire. I ran this same query in PHPMyAdmin, also using ORDER BY ID DESC, and the return was as follows: Showing rows 0 - -1 I've never seen this before and am not quite sure how to fix it. Anyone else seen this before and be able to fix it? Thanks, all! Added 8/31/12 - for grumpy ID level system status restoretime 0 2 MyISU System is functioning normally NULL 1 2 Network System is functioning normally NULL 2 1 Blackboard System is functioning normally NULL 3 3 Email System is functioning normally NULL 4 1 Banner System is functioning normally NULL and the structure: Column | Type | Null | Default ----------------------------------------------------------------- ID int(11) No level varchar(3) No 1 system varchar(255) No status varchar(755) No System is functioning normally restoretime text Yes NULL A: I assume it's a bug in phpMyAdmin, as search for that error message and comments for this answer seem to confirm. And it's quite easy to check: run the queries you've asked for in MySQL console.
[ "stackoverflow", "0039095082.txt" ]
Q: Instaparse: How to recognise a newline I want to parse the text of a file that contains newlines. The file could be in Windows or Unix, but for now it is a Windows file with this contents: (************** ***************) The above file contents has been read in with slurp and will contain a newline. Here is the grammar that I am trying to use: S = start-comment stars <inside-comment> start-comment = '(' stars = '*' + <inside-comment> = '\n' + This grammar is also slurped in from a file, which I believe makes things a little easier: "The only escape characters needed are the ordinary escape characters for strings and regular expressions (additionally, instaparse also supports \' inside single-quoted strings)." The newline does not seem to be being parsed: Parse error at line 1, column 16: (************** ^ Expected one of: "\n" "*" What do I need to set <inside-comment> to so that the error comes on the first star of the second line, which will indicate that the grammar has recognized the newline? A: Newlines in Windows show up as \r\n and in Unix as \n. So you need something like this: #'\r?\n' Double the blackslashes if your grammar is inside a string: "some-rule = #'\\r?\\n'"
[ "stackoverflow", "0003417808.txt" ]
Q: UITableView: custom gestures make it scrolling no more I have an UIViewController which contains a UITableView (subclassed) and another UIView (subclassed). They are on the same hierarchy level but the UIView is added last so it is the frontmost. I overrid touchesBegan/Moved/Ended to intercept the Gestures from the top UIView: my goal is to get the selected UITableViewCell and, if double tapped, create an ImageView to be dragged around. I appear to get it done but now I cannot scroll the UITableView anymore, even though I forward the touch events. Here are the methods for the UIView: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"BO"); UITouch * touch = [touches anyObject]; CGPoint tPoint = [touch locationInView:self]; InventoryViewController * invViewCont = self.viewController; UITableView * invTab = invViewCont.inventoryTableView; [invTab deselectRowAtIndexPath:[invTab indexPathForSelectedRow] animated:YES]; NSArray * cells = [invTab visibleCells]; BOOL found = NO; for (UITableViewCell * cell in cells) { if (CGRectContainsPoint(cell.frame, tPoint)) { [cell touchesBegan:touches withEvent:event]; found = YES; break; } } if (!found) { [invViewCont.inventoryTableView touchesBegan:touches withEvent:event]; } } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"Mo"); UITouch * touch = [touches anyObject]; CGPoint tPoint = [touch locationInView:self]; copyObj.center = tPoint; InventoryViewController * invViewCont = self.viewController; UITableView * invTab = invViewCont.inventoryTableView; [invTab deselectRowAtIndexPath:[invTab indexPathForSelectedRow] animated:YES]; NSArray * cells = [invTab visibleCells]; BOOL found = NO; for (UITableViewCell * cell in cells) { if (CGRectContainsPoint(cell.frame, tPoint)) { [cell touchesMoved:touches withEvent:event]; found = YES; break; } } if (!found) { [invViewCont.inventoryTableView touchesMoved:touches withEvent:event]; } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch * touch = [touches anyObject]; if ([touch tapCount] == 2) { [self desubCopyView]; } CGPoint tPoint = [touch locationInView:self]; copyObj.center = tPoint; InventoryViewController * invViewCont = self.viewController; UITableView * invTab = invViewCont.inventoryTableView; [invTab deselectRowAtIndexPath:[invTab indexPathForSelectedRow] animated:YES]; NSArray * cells = [invTab visibleCells]; BOOL found = NO; for (UITableViewCell * cell in cells) { if (CGRectContainsPoint(cell.frame, tPoint)) { [cell touchesEnded:touches withEvent:event]; //[cell.imageView touchesEnded:touches withEvent:event]; found = YES; break; } } if (!found) { [invViewCont.inventoryTableView touchesEnded:touches withEvent:event]; } } And here are those in the UITableViewCell -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch * touch = [touches anyObject]; if ([touch tapCount] == 2) { CGPoint tPoint = [touch locationInView:self]; NSLog(@"CellX %lf CY %lf", tPoint.x, tPoint.y); UIGraphicsBeginImageContext(self.bounds.size); [self.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIImageView * newView = [[UIImageView alloc] initWithImage:viewImage]; [dragArea addSubview:newView]; dragArea.copyObj = newView; [newView release]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.4]; dragArea.copyObj.transform = CGAffineTransformMakeScale(1.3, 1.3); [UIView commitAnimations]; tPoint = [self convertPoint:tPoint toView:dragArea]; dragArea.copyObj.center = tPoint; } [super touchesBegan:touches withEvent:event]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"MOV %@", self.imageView.image); [super touchesMoved:touches withEvent:event]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"ENDED"); [super touchesEnded:touches withEvent:event]; } And in my UITableView I have simply: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"BEGTB"); [super touchesBegan:touches withEvent:event]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"MOVTB"); [super touchesMoved:touches withEvent:event]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ NSLog(@"ENDTB"); [super touchesEnded:touches withEvent:event]; } I am surely missing something but I do not know what A: I found a workaround for this, override the methods for touch gestures in my custom UITableView in order to make it scroll programMatically as I drag upon it an object. Here is the 'solution'. I still believe there is another simpler way to do this but I did not find it, so posting this and marking it as an 'answer' might help someone else.
[ "stackoverflow", "0044481675.txt" ]
Q: HasOne not found in EF 6 I am very new to Entity Framework and I am trying to figure out relations. I have found this code: class MyContext : DbContext { public DbSet<Post> Posts { get; set; } public DbSet<Tag> Tags { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<PostTag>() .HasKey(t => new { t.PostId, t.TagId }); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Post) .WithMany(p => p.PostTags) .HasForeignKey(pt => pt.PostId); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Tag) .WithMany(t => t.PostTags) .HasForeignKey(pt => pt.TagId); } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public List<PostTag> PostTags { get; set; } } public class Tag { public string TagId { get; set; } public List<PostTag> PostTags { get; set; } } public class PostTag { public int PostId { get; set; } public Post Post { get; set; } public string TagId { get; set; } public Tag Tag { get; set; } } I get an error while compiling the code: 'EntityTypeConfiguration' does not contain a definition for 'HasOne' and no extension method 'HasOne' accepting a first argument of type 'EntityTypeConfiguration' could be found (are you missing a using directive or an assembly reference?) I have tried to find it on Google and StackOverflow, but the only things I found was how to use it and not why it gives problems. Do I actually miss a reference? If so, which one? A: HasOne() is an Entity Framework Core method. In prior versions you use HasOptional() or HasRequired().
[ "stackoverflow", "0016394549.txt" ]
Q: Action Script 3. How to hide button till game ends? I'm creating game and I need to make that when game over "Try Again" button appears. I have done the button just don't know how to hide It till game ends. It is shown all the time. This is my button: function tryAgain(e:MouseEvent):void { trace("Try again"); createCards(); } A: button.visible = false; function tryAgain(e:MouseEvent):void { button.visible = true; createCards(); } visible property on AS3 Reference
[ "stackoverflow", "0030063259.txt" ]
Q: How to serialize only inherited properties of a class using a JsonConverter I'm trying to serialize only the inherited properties of a class using json.net. I'm aware of the [JsonIgnore] attribute, but I only want to do ignore them on certain occasion, so I used a custom JsonConverter instead. Here's my class: public class EverythingButBaseJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { // Find properties of inherited class var classType = value.GetType(); var classProps = classType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList(); // Remove the overrided properties classProps.RemoveAll(t => { var getMethod = t.GetGetMethod(false); return (getMethod.GetBaseDefinition() != getMethod); }); // Get json data var o = (JObject)JToken.FromObject(value); // Write only properties from inhertied class foreach (var p in o.Properties().Where(p => classProps.Select(t => t.Name).Contains(p.Name))) p.WriteTo(writer); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(""); } public override bool CanRead { get { return false; } } public override bool CanConvert(Type objectType) { return true; } } When doing a simple o.WriteTo(writer); it give the same result as not using a converter. When iterating through properties and using WriteTo on the properties, it works fine for base type (int, string, etc), but I'm having problem with collections. Expected: { "Type": 128, "Time": [ 1, 2, ], "Pattern": 1, "Description": "" } Got: "Type": 128, "Time": [ 1, 2, ]"Pattern": 1, "Description": "" As you can see, the collection is missing the "," and endline portion. I'm also missing the global { } for the whole object. I am doing things the correct way? Is there an easier way to get the result I want? A: Not sure why your code doesn't work (maybe a Json.NET bug?). Instead, you can remove the properties you don't want from the JObject and write the entire thing in one call: public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { // Find properties of inherited class var classType = value.GetType(); var classProps = classType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList(); // Remove the overrided properties classProps.RemoveAll(t => { var getMethod = t.GetGetMethod(false); return (getMethod.GetBaseDefinition() != getMethod); }); // Get json data var o = (JObject)JToken.FromObject(value); // Remove all base properties foreach (var p in o.Properties().Where(p => !classProps.Select(t => t.Name).Contains(p.Name)).ToList()) p.Remove(); o.WriteTo(writer); } Alternatively, you could create your own contract resolver and filter out base properties and members: public class EverythingButBaseContractResolver : DefaultContractResolver { protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { if (member.ReflectedType != member.DeclaringType) return null; if (member is PropertyInfo) { var getMethod = ((PropertyInfo)member).GetGetMethod(false); if (getMethod.GetBaseDefinition() != getMethod) return null; } var property = base.CreateProperty(member, memberSerialization); return property; } } And then use it like: var settings = new JsonSerializerSettings { ContractResolver = new EverythingButBaseContractResolver() }; var json = JsonConvert.SerializeObject(rootObject, Formatting.Indented, settings);
[ "stackoverflow", "0002597721.txt" ]
Q: Create WPF Browser (XBAP) Application in PowerBuilder 12? Is it possible to create XBAP applications in Powerbuilder 12 ? I learned that powerbuilder 12 supports WPF but im not sure about WPF Browser (XBAP) Apps. Any help or link is appreciated. Thanks! A: So, since it's not released yet, nothing's official, but from what I've heard of the announcements, that's not the intention in this release. Mind you, it wasn't intended in previous releases to support .NET controls but people like Bruce Armstrong found creative ways to do it anyway. The announced intention is to look at a new web solution post-PB12 (PB12 is pretty massive already), but it's not 100% clear if they'll settle on XBAP, which is a logical extension from their WPF work, or something else like HTML5. Good luck, Terry.
[ "stackoverflow", "0045029354.txt" ]
Q: How is this "operation" called in Python I'm trying to understand how this bit works: Var_1, Var_2, Result = some_function() the script: def some_function(): return True, False, {"Some": "Dictionary"} def main(): Var_1, Var_2, Result = some_function() if not Var_1: do something else: do something_else(Var_2, Result) if __name__ == '__main__': main() For me the difficult to grasp is the bit of doing inception and provide(return) values which will be used in the main function and in the same trigger the some_function() from within the main() function. Since I'm new to advanced concepts in python, I found it really interesting. How this "operation" is called so I can read a bit more about how it works. i.e. returning some values in line order separated by , and interpreting them based on the position in line(for the lack of better description). A: It's returning a tuple. A tuple in Python is similar to a list, but it's immutable: you can't add, remove or replace items. Often, tuples are constructed with the syntax (a, b, c), but the parentheses are optional in many cases, so a, b, c is also valid. On the receiving end, tuple unpacking is used to get the individual elements of the tuple, and assign them to separate variables. A: What is happening here is in fact not that several values are returned. Instead, a single tuple is returned, and this is then unpacked using something called tuple unpacking. The code is equivalent to tmp_tuple = some_function() # return tuple Var_1, Var_2, Result = tmp_tuple # unpack tuple
[ "stackoverflow", "0059723576.txt" ]
Q: is there any way to extract the data values from these objects I have data like as below in image and i am trying to extract Data array from the json that was in below image. Data is having key values like condition_type and other values also. I can be able to get the each individual values using below code const submitcode = (data) => { const tasks = Object.values(data); console.log(tasks[0].Data[0]); } console.log(tasks[0].Data[0]); Could any one please suggest is there any way to fetch Data array from these 6 objects using react JS. Many thanks in advance A: Here is a simple snippet that returns array of Data's const array = [ {Cols: [], Data: [{condition_type: "1"}], title: "Environmental Condition"}, {Cols: [], Data: [{condition_type: "2"}], title: "Ventilation"}, {Cols: [], Data: [{condition_type: "3"}], title: "Thermal Comfort"}, {Cols: [], Data: [{condition_type: "4"}], title: "Internal Loads"}, {Cols: [], Data: [{condition_type: "5"}], title: "Exhaust"}, {Cols: [], Data: [{condition_type: "6"}], title: "Misc"}, ] console.log(array.map(({Data: [val]})=>val)) or if you want to directly access the values of particular keys const array = [ {Cols: [], Data: [{condition_type: "1"}], title: "Environmental Condition"}, {Cols: [], Data: [{condition_type: "2"}], title: "Ventilation"}, {Cols: [], Data: [{condition_type: "3"}], title: "Thermal Comfort"}, {Cols: [], Data: [{condition_type: "4"}], title: "Internal Loads"}, {Cols: [], Data: [{condition_type: "5"}], title: "Exhaust"}, {Cols: [], Data: [{condition_type: "6"}], title: "Misc"}, ] console.log(array.map(({Data: [{condition_type}]})=>condition_type)) A: Considering your array in the screenshot is called tasks, you can use a map with object and array destructuring: tasks.map(({ Data: [el] }) => el); const tasks = [{ Data: [{ a: 1, b: 2 }] }, { Data: [{ a: 3, b: 4 }] }]; console.log(tasks.map(({ Data: [el] }) => el)); Or also a bit hacky, using object destructiring twice also with the array, using the array index: tasks.map(({ Data: { 0: el } }) => el); const tasks = [{ Data: [{ a: 1, b: 2 }] }, { Data: [{ a: 3, b: 4 }] }]; console.log(tasks.map(({ Data: { 0: el } }) => el));
[ "stackoverflow", "0004039044.txt" ]
Q: Recreate "Styles" drop down area of Office Ribbon? I am trying to recreate the "Styles" section of the Office ribbon: http://www.winsupersite.com/images/reviews/office2007_b2_06.jpg I like how it starts out as only one row, then you can scroll through the rows, then click the arrow to expand all into a table like above. Does anyone have any ideas on how to recreate this whole interactivity?? A: CSS #container { width:200px;height:50px;overflow-x:hidden;overflow-y:auto; border:1px solid black; position:relative } #expander { position:absolute;right:0;bottom:0px;font-size:10px;margin:0;padding:1; border:1px solid black; border-width:1px 0 0 1px } .item { float:left; font-size:30px;height:40px;width:50px; margin:5px; background:gainsboro;text-align:center } HTML <div id='container'> <div class='item'>A</div> <div class='item'>B</div> <div class='item'>C</div> <div class='item'>D</div> <div class='item'>E</div> <div class='item'>F</div> <div class='item'>G</div> <div class='item'>H</div> <div class='item'>I</div> <div class='item'>J</div> <div class='item'>K</div> <button id='expander' onclick='expand()'>&#9650;</button> </div> JS function $(id) { return document.getElementById(id); } function expand() { $('container').style.overflow = "auto"; $('container').style.height = "300px"; $('container').style.width = "300px"; } function contract() { $('container').style.overflow = "hidden"; $('container').style.height = "50px"; $('container').style.width = "200px"; } ...should get you started. It's got a few bugs you'll have to figure out: When to call contract() Button isn't positioned directly under scrollbar Button scrolls with content (and disappears)
[ "ru.stackoverflow", "0000804113.txt" ]
Q: Как замедлить видео на javascript? Привет, можно ли замедлить видео на javascript? Если да, то как? Подскажите пожалуйста. A: Вот код: document.querySelector('video').playbackRate = 3.0; Значение 3.0 означает что видео ускорено в 3 раза. По дефолту видео воспроизводиться с нормальной скоростью, то есть 1.0. Чтобы замедлить видео на половину 0.5
[ "spanish.stackexchange", "0000003005.txt" ]
Q: Alternativas a "irretrasable" La vicepresidenta del Gobierno de España dijo recientemente "medidas irretrasables" que no existe en el español. Yo encuentro como sinónimos medidas inaplazables, medidas de imposible retraso. ¿Qué otras alternativas existen? A: La palabra que primero se me ocurre es "impostergable". Pero hay otras palabras afines: inaplazable, urgente, perentorio, improrrogable, ineludible.
[ "stackoverflow", "0021183873.txt" ]
Q: how to run linq on XxmlElement rather than XElement in C# How to get the attributes of XmlElement rather than XElement in C# with linq? public string test (XmlElement element) { var enumAttr = from attr in element.Attributes select attr; foreach (var data in enumAttr) { // TO DO } } It's giving an error, Could not find an implementation of the query pattern for source type 'System.Xml.XmlAttributeCollection'. 'Select' not found. Consider explicitly specifying the type of the range variable 'attr' A: This is because XmlAttributeCollection only implements IEnumerable rather than IEnumerable<T>. You can just change your query expression to: var enumAttr = from XmlAttribute attr in element.Attributes select attr; which is equivalent to: var enumAttr = from attr in element.Attributes.Cast<XmlAttribute>() select attr; But you're not really doing anything with the LINQ here anyway - you can just use: foreach (XmlAttribute data in enumAttr.Attributes)
[ "stackoverflow", "0023271769.txt" ]
Q: Change property on object on event without codebehind I am trying to change Visibility on a textbox when the event "DropDownClosed" on a combobox occurs. The thing is, I can't use codebehind (and thereby eventtrigers I think?) because I am trying to follow the Model-View-Viewmodel design. An example of what I am looking for: <Grid> <ComboBox x:Name="Combobox"> <ComboBoxItem Content="true"/> <ComboBoxItem Content="false"/> </ComboBox> <TextBlock Text="Some text" IsHitTestVisible="False"> <TextBlock.Style> <Style TargetType="TextBlock"> <Setter Property="Visibility" Value="Visible"/> // Code that makes textbox visibility become "collapsed" when Combobox event "DropDownClosed" occurs. </Style> </TextBlock.Style> </TextBlock> Anyone has any ideas? Thanks in advance. A: Here is a simple working example based on the code fragment you posted. I'll go over it step by step. XAML (I'm using a StackPanel for ease of use.) <StackPanel> <StackPanel.Resources> <BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter"/> </StackPanel.Resources> <ComboBox x:Name="Combobox" SelectedIndex="{Binding Choice, Mode=TwoWay}"> <ComboBoxItem Content="true"/> <ComboBoxItem Content="false"/> </ComboBox> <TextBlock Text="Some text" IsHitTestVisible="False" Visibility="{Binding Visible, Converter={StaticResource BoolToVisibilityConverter}}"> </TextBlock> </StackPanel> First we declare a BooleanToVisibilityConverter resource. This is a built-in class that does exactly what you need, it converts a bool value to a Visibility value <StackPanel.Resources> <BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter"/> </StackPanel.Resources> Next, we bind the ComboBox to a property of the ViewModel called Choice. Note that I am binding the SelectedIndex property <ComboBox x:Name="Combobox" SelectedIndex="{Binding Choice, Mode=TwoWay}"> <ComboBoxItem Content="true"/> <ComboBoxItem Content="false"/> </ComboBox> Finally, I'm binding the Visibility property of the TextBlock to a boolean property of the ViewModel called Visible, this binding is using the BooleanToVisibilty property we declared as a resource <TextBlock Text="Some text" IsHitTestVisible="False" Visibility="{Binding Visible, Converter={StaticResource BoolToVisibilityConverter}}"> </TextBlock> I also removed the TextBlock style as it was not needed. The Visibility can be set on the TextBlock directly. Now for the ViewModel public class MainWindowViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private int choice = 0; public int Choice { get { return choice; } set { if (value != choice) { choice = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Choice")); } Visible = choice == 0; } } } private bool visible = true; public bool Visible { get { return visible; } set { if (value != visible) { visible = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Visible")); } } } } } As I noted earlier the Choice property is declared as an int, and is being bound in the XAML to the SelectedIndex property, which is also an int. I did this for the sake of simplicity as I didn't want to introduce another Converter to translate your "true" and "false" strings into a true/false boolean value. I do not consider this an ideal design, but it serves it's purpose. Visible = choice == 0; This line sets the boolean Visible property whenever Choice is changed. It sets it to true if index == 0 (which is the "true" string of your ComboBox) and sets it to false otherwise. This in turn causes the Visible property to raise a notification, and the BoolToVisibility converter converts that bool to Visibility.Visible when true or Visibility.Collapsed when false.
[ "stackoverflow", "0012506178.txt" ]
Q: ruby connect to oracle using kerberos Since Oracle has built in support for kerberos and sqlplus can connect to database using kerberos using oci8 can i do something similar in ruby like this ? require 'oci8' oci = OCI8.new('SomeUser','SomePass','hostname.servicename') oci.exec('select * from table') do |record| puts record.join(',') end can i have a blank username and password ? and will the connection be sucessful ? am i on the right path ? A: I guess, Ruby/RoR is compiled against OCI, since Oracle Call Interface and Net Services Support Kerberos authentication this is possible. Although I cannot tell whether there might be some limitation in Ruby's interface. First of all, you need to get it working with SQL*Plus, after that try your application. Begin with Configuring Kerberos Authentication. If Ruby OCI8 is implemented correctly, this should do it: OCI8.new(nil, nil, 'net_service_name') or OCI8.new('/@net_service_name')
[ "stackoverflow", "0061326337.txt" ]
Q: Load more implementation in ReactJs I am trying to implement load more button for my small project GiF generator. First I thought of appending next set of 20 response at the bottom, but failed to do. Next, I thought of implementing loading the next set of 20 results by simply removing the current one. I tried to trigger a method on click of button, but I failed to do so. Its updating the state on second click of load more and then never updating it again. Please help me find what I am missing, I have started learning React yesterday itself. import React, { useEffect, useState } from 'react'; import './App.css'; import Gif from './Gif/Gif'; const App = () => { const API_KEY = 'LIVDSRZULELA'; const [gifs, setGif] = useState([]); const [search, setSearch] = useState(''); const [query, setQuery] = useState('random'); const [limit, setLimit] = useState(20); const [pos, setPos] = useState(1); useEffect(() => { getGif(); }, [query]) const getGif = async () => { const response = await fetch(`https://api.tenor.com/v1/search?q=${query}&key=${API_KEY}&limit=${limit}&pos=${pos}`); const data = await response.json(); setGif(data.results); console.log(data.results) } const updateSearch = e => { setSearch(e.target.value); } const getSearch = e => { e.preventDefault(); setQuery(search); setSearch(''); } const reload = () => { setQuery('random') } const loadMore = () => { // this is where I want my Pos to update with 21 on first click 41 on second and so on let temp = limit + 1 + pos; setPos(temp); setQuery(query); } return ( <div className="App"> <header className="header"> <h1 className="title" onClick={reload}>React GiF Finder</h1> <form onSubmit={getSearch} className="search-from"> <input className="search-bar" type="text" value={search} onChange={updateSearch} placeholder="type here..." /> <button className="search-button" type="submit">Search</button> </form> <p>showing results for <span>{query}</span></p> </header> <div className="gif"> {gifs.map(gif => ( <Gif img={gif.media[0].tinygif.url} key={gif.id} /> ))} </div> <button className="load-button" onClick={loadMore}>Load more</button> </div> ); } export default App; Please, help me find, what I am doing wrong, As I know the moment I will update setQuery useEffect should be called with new input but its not happening. A: Maybe try something like this: // Fetch gifs initially and then any time // the search changes. useEffect(() => { getGif().then(all => setGifs(all); }, [query]) // If called without a position index, always load the // initial list of items. const getGif = async (position = 1) => { const response = await fetch(`https://api.tenor.com/v1/search?q=${query}&key=${API_KEY}&limit=${limit}&pos=${position}`); const data = await response.json(); return data.results; } // Append new gifs to existing list const loadMore = () => { let position = limit + 1 + pos; setPos(position); getGif(position).then(more => setGifs([...gifs, ...more]); } const getSearch = e => { e.preventDefault(); setQuery(search); setSearch(''); } const updateSearch = e => setSearch(e.target.value); const reload = () => setQuery('random'); Basically, have the getGifs method be a bit more generic and then if loadMore is called, get the next list of gifs from getGift and append to existing list of gifs.
[ "stackoverflow", "0015172050.txt" ]
Q: Saving user settings in Metro app using VB.NET How to saving user settings in Metro app using VB.NET? I want to save the password at first time open the metro apps.And open the metro apps need password to access. A: See Accessing app data with the Windows Runtime for an overview of all your storage options. More specifically though, if you do need to store secure information on the client device (always a risk there) then use the PasswordVault APIs The Credential Locker example should help.
[ "stackoverflow", "0026398020.txt" ]
Q: When assigning attributes, you must pass a hash as an argument I am following Agile Web Development with Rails 4. Chapter Cart 9 Cart Creation. When I want to update a cart, I get the following Error Notification: When assigning attributes, you must pass a hash as an arguments. CartController#update. class CartsController < ApplicationController include CurrentCart before_action :set_cart, only: [:show, :edit, :update, :destroy] rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart def index @carts = Cart.all end def show end def new @cart = Cart.new end def edit end def create @cart = Cart.new(cart_params) respond_to do |format| if @cart.save format.html { redirect_to @cart, notice: 'Cart was successfully created.' } format.json { render :show, status: :created, location: @cart } else format.html { render :new } format.json { render json: @cart.errors, status: :unprocessable_entity } end end end def update @cart = Cart.find(params[:id]) respond_to do |format| if @cart.update_attributes(params[:cart]) format.html { redirect_to @cart, notice: 'Cart was successfully updated.' } format.json { render :show, status: :ok, location: @cart } else format.html { render :edit } format.json { render json: @cart.errors, status: :unprocessable_entity } end end end def destroy @cart.destroy if @cart.id == session[:card_id] session[:card_id] = nil respond_to do |format| format.html { redirect_to store_url, notice: 'Your cart is currently empty.' } format.json { head :no_content } end end private def set_cart @cart = Cart.find(params[:id]) end def cart_params params[:cart] end def invalid_cart logger.error "Attempt to access invalid cart #{params[:id]}" redirect_to store_url, notice: 'Invalid cart' end end A: Your params is probably an instance of ActionController::Parameters If so, you need to permit the attributes you want to use, like so: def cart_params params.require(:cart).permit(:attribute1, :attribute2, :attribute3) end A: Try this: In your update method replace if @cart.update_attributes(params[:cart]) by if @cart.update_attributes(cart_params) In your cart_params private method do this: def cart_params params.require(:cart).permit(:attribute1, :attribute2, :attribute3) end With Rails 4, the concept of strong parameters has been introduced which basically forbids mass assignment of attributes in the controller. This means that the mass assingment protection that was once in model (attr_accessible) has now been moved to the controller. Hence in your models you no more need to use this: attr_accessible :attribute1, attribute 2 #attributes that can be mass-assinged attr_protected :attribute3 #attribute that is protected and cannot be mass-assinged Instead you can now do this in your controller through : params.require(:cart).permit(:attribute1, :attribute2, :attribute3) This means that only attribute1, attribute2. attribute3 of cart are accessible while other are protected attributes
[ "math.stackexchange", "0003163287.txt" ]
Q: Proofcheck: $|f| \leq 1$ $\mu-$a.e. then $\lim_{n \to \infty} \int_{\mathbb R} |f(x)|^{n}d\lambda (x) = \lambda(\{|f|=1\})$ Let $f \in L^{1}(\mathbb R)$ and $|f| \leq 1$ $\mu-$a.e. then $\lim_{ n \to \infty}\int_{\mathbb R} |f(x)|^{n}d\lambda (x) = \lambda(\{|f|=1\})$ My idea: Define $f_{n}(x):=|f(x)|^{n}$ Note that $f_{n}\leq |f| \leq 1$ $\mu-$a.e. $\lim_{ n \to \infty}\int_{\mathbb R}f_{n}(x)d\lambda (x)=\lim_{ n \to \infty}\int_{\mathbb R}|f(x)|^{n}d\lambda (x)=\lim_{ n \to \infty} \int_{\mathbb R}|f(x)|^{n}1_{\{|f|=1\}}+|f(x)|^{n}1_{\{|f|<1\}}d\lambda (x)$ It follows from the DCT (given that $f \in L^{1}$): $\lim_{ n \to \infty}\int_{\mathbb R}|f(x)|^{n}1_{\{|f|=1\}}+|f(x)|^{n}1_{\{|f|<1\}}d\lambda (x)=\int_{\mathbb R}\lim_{ n \to \infty}1_{\{|f|=1\}}+|f(x)|^{n}1_{\{|f|<1\}}d\lambda (x)=\int_{\mathbb R}1_{\{|f|=1\}}d\lambda=\lambda(\{|f|=1\})$ A: The idea is correct, but perhaps it will be more save if we write it like that : we put $f_n=f^n$ and we consider $A=\{x\in\mathbb{R} \; ; |f(x)|<1\}$, since $f\leq 1$ a.e we get $A^c=\{x\in\mathbb{R} \; ; |f(x)|=1\}$ so : $$ |f_n(x)|\longrightarrow g(x)\left\{\begin{array}{lcr} 0 & \rm{if}& x\in A \\1 & \rm{if}& x\in A^c \end{array} \right. $$ since $|f_n|\leq |f|\in L^1(\mathbb{R})$, by DCT we get $$ \lim_n\int_\mathbb{R} |f_n|d\lambda=\int_\mathbb{R} \lim_n|f_n|d\lambda=\int_\mathbb{R} g d\lambda=\int_{A^c} d\lambda=\lambda(A^c). $$
[ "stackoverflow", "0013023781.txt" ]
Q: Using curl to use the build in Facebook like Im trying to create the build in like button from facebook, but now facebook requieres to use the curl system, and onces i created the action, facebook gives me this code: curl -F 'access_token=AAAAAKcSOZB8IBACXBZBQ1F5fUqqEeueY0bkj7eAZAeAWgjU5vU8c8ZC5X8L1ZAWGYVTlR0vySQQU0raZCuNCmPlcjxavrG6hsZD' \ -F 'object=http://samples.ogp.me/226075010839791' \ 'https://graph.facebook.com/me/og.likes' But I not sure how to invoque this code using a link or a form button, my site has several user access token store in a mysql Onces the like command is send, facebook will send back a id_from_create_call which will have to be store so when a user dislikes something, the value send by facebook must be use here: curl -X DELETE \ -F 'access_token=AAAAAKcSOZB8IBACXBZBQ1F5fUqqEeueY0bkj7eAZAeAWgjU5vU8c8ZC5X8L1ZAWGYVTlR0vySQQU0raZCuNCmPlcjxavrG6hsZD' \ 'https://graph.facebook.com/{'{id_from_create_call}'}' Can someone help me? A: https://developers.facebook.com/docs/reference/php/ It will be better for you to use FB api..
[ "stackoverflow", "0031605617.txt" ]
Q: How to refresh data at midnight in a MVC application? For a client we are building a website that displays products. Once a day, at midnight, the order of the products on the homepage must be changed. In other words, the order of the products must be shuffled. I now have this solved as follows, but I don't think this is the way to go... In application_start in global.asax, load the product ids and shuffle them. In IIS set recycle of the app pool at 00:00:00. In IIS set idle time-out to 1440 minutes (24 * 60) So my question is, how would you handle this requirement? A: There are million reasons why "sleeps" on task threads from IIS can fail and never be executed. One other option is to use Windows Task Scheduler There you can call you own C# code (windows application) that can wake up your IIS webapplication, targeting a specific URL, and there you do your own clean up tasks. Other similar way is to use those "ping" services that are used to verify if a site is alive, and if there you can change the "time intervals" you might would be able to pass the same "maintenance url". Oher option: in case you use SQL Server, SQL Server Batch or Task Scheduling (from here you can invoke an application)
[ "stackoverflow", "0059527568.txt" ]
Q: How to create a View extension function in Kotlin I'm trying to create an extension function in Kotlin. I did try several tutorials, but didn't quite understand, how to implement this one. I'm trying to create a setWidth() function as such //Find my_view in the fragment val myView = v.findViewById<RelativeLayout>(R.id.my_view) //Then use the extension function myView.setNewWidth(500) This is how I've defined my extension function private fun View?.setNewWidth(i: Int) { val layoutParams: ViewGroup.LayoutParams = View.layoutParams layoutParams.width = i View.layoutParams = layoutParams } I don't understand what I need to do here. I want to call the extension function as myView.ExtensionFunction(), but I don't know how to do that. The tutorials, were un-informative. A: I think the main problem here is how the extension function is defined, in particular, the lines that have View.layoutParams - this is calling a static property on View that doesn't exist. You need to use the one from the instance. If you'd write the extension function like so: private fun View?.setNewWidth(i: Int) { val layoutParams = this?.layoutParams layoutParams?.width = i this?.layoutParams = layoutParams } Then you can call the method like you want. Personally, I don't find this so readable and I'd remove the nullability here and write it as: private fun View.setNewWidth(i: Int) { val newLayoutParams = layoutParams newLayoutParams?.width = i layoutParams = newLayoutParams } The only difference is that now you need ?. to call the method if the view is nullable, which I personally find fine - myView?.setNewWidth(123). I assume most of the time you won't have a nullable view.
[ "askubuntu", "0001093495.txt" ]
Q: Ubuntu 16.04 Network Manager DHCP and PXE setup. Can't find `dnsmasq.conf` I'm about to upgrade my (seperate computer) firewall (Going from IPCop to IPFire). I'd like to use PXE to boot the upgrade on the firewall. I depend on the firewall system for DHCP, so when it's down for reinstallation, nobody will get an IP address. I think I know the magic to add to dnsmasq.conf to cause it to serve DHCP, but, I don't see /etc/dnsmasq.conf. Using locate says: $ locate dnsmasq.conf /etc/dbus-1/system.d/dnsmasq.conf /snap/core/5548/etc/dbus-1/system.d/dnsmasq.conf /snap/core/5662/etc/dbus-1/system.d/dnsmasq.conf /snap/core/5742/etc/dbus-1/system.d/dnsmasq.conf /usr/share/doc/dnsmasq-base/examples/dnsmasq.conf.example This is probably due to my use of Network Manager. I plan to use dhcpd-hpa to serve the PXE stuff. Are there landmines? A: @JackyChan After the cp /usr/share/doc/dnsmasq-base/examples/dnsmasq.conf.example /etc/dnsmasq.conf, I did inotifywatch -t 180 -v --event access /etc/dnsmasq.conf /etc/dnsmasq.d/ /etc/dnsmasq.d-available/ while, in another window, did sudo service NetworkManager restart inotifywatch detected no accesses. After further research, I put the file (all #comments and blank lines, for now) in /etc/NetworkManager/dnsmasq.d/dnsmasq.conf, and ran inotifywatch -t 180 -v --event access /etc/NetworkManager/dnsmasq.d/dnsmasq.conf while, in another window, did I sudo service NetworkManager restart inotifywatch saw 7 accesses to /etc/NetworkManager/dnsmasq.d/dnsmasq.conf The directory /etc/NetworkManager/dnsmasq.d is where dnsmasq.conf is sought, for a NetworkManager controlled dnsmasq
[ "stackoverflow", "0039609110.txt" ]
Q: After submit redirect to another page I have search form in php with submit button. (that made like shortcode) I need redirect on another page with data. For example http://localhost/wordpress/?data_min=21.09.2016&data_max=22.09.2016 and with "?data_min=21.09.2016&data_max=22.09.2016" redirect to http://localhost/search_form/?data_min=21.09.2016&data_max=22.09.2016 $sHeader = ' < div class = "panel list_header" > < form class = "filter_form" action = "" > < fieldset > < ul > ' . $sFilters . ' < /ul> < /fieldset> < div class = "filter_form_submit_button_wrapper" > < input type = "submit" name = "submit" value = "Suchen" > < /div> < /form> < /div> '; return $sHeader; } How can i make this? with onsubmit or how? A: Try this $sHeader = ' <div class="panel list_header"> <form class="filter_form" method="get" action=" http://localhost/search_form/"> <fieldset> <ul>' . $sFilters . '</ul> </fieldset> <div class="filter_form_submit_button_wrapper"> <input type="submit" name="submit" value="Suchen"> </div> </form> </div> '; return $sHeader;}
[ "stackoverflow", "0052272290.txt" ]
Q: Memory Leak in Custom Textview with Spannable Android I have one custom textview which has five city names and spannable click listener for each one of them. Code is as follow /** * Created by @raj on 26/04/18. */ class TopCitiesTextView : TextView { private var mListener: OnCityClickListener? = null constructor(ctx: Context?) : super(ctx) { initView(ctx, null, 0) } constructor(ctx: Context?, attrs: AttributeSet?) : super(ctx, attrs) { initView(ctx, attrs, 0) } constructor(ctx: Context?, attrs: AttributeSet?, defStyle: Int) : super(ctx, attrs, defStyle) { initView(ctx, attrs, defStyle) } private fun initView(ctx: Context?, attrs: AttributeSet?, defStyle: Int) { } override fun onFinishInflate() { super.onFinishInflate() val cityArray: Array<out String> = context.resources.getStringArray(R.array.top_cities_view_text) val spannableString: SpannableString = SpannableString(cityArray[0]) this.text = spannableString this.append(" ") for (i in 1 until cityArray.size) { val citySpannableString = SpannableString(cityArray[i]) citySpannableString.setSpan(object : ClickableSpan() { override fun onClick(widget: View?) { mListener?.onCityClicked(cityArray[i]) } override fun updateDrawState(ds: TextPaint) { super.updateDrawState(ds) ds.isUnderlineText = false } }, 0, citySpannableString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) this.append(citySpannableString) if (i != cityArray.size-1) this.append(", ") } movementMethod = LinkMovementMethod.getInstance() } fun setCityClickListener(listener: OnCityClickListener) { this.mListener = listener } interface OnCityClickListener { fun onCityClicked(city: String?) } } But the issue is that I am getting memory leak while using this textview in fragment's layout(xml) file. Here is the screenshot of leakcanary. How to remove this memory leak? A: Remove the ClickableSpan from text in onDestroy of your Activity to avoid the Leak. if (textView.getText() instanceof SpannableString) { SpannableString spannableStr = (SpannableString) textView.getText(); ClickableSpan[] spans = spannableStr.getSpans(0, spannableStr.length(), ClickableSpan.class); for (ClickableSpan span : spans) { spannableStr.removeSpan(span); } textView.setText(spannableStr); }
[ "stackoverflow", "0043802488.txt" ]
Q: Java get request error using google distance matrix api for some reason when we send a get request to the google distance matrix api we get an error saying we have exceeded our daily quota, nonetheless we haven't done even 100 request as can be seen here: https://i.stack.imgur.com/B94c1.png the code to send the get request is as follows: public class JsonRead { // Coverteix tot el contingut del BufferedReader en una String per per el seu posterior tractament private String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } //Per alguna rao, depen de quines adreçes disparen OVER_QUERY_LIMIT // Agafa una String que conte la direcció, fa una GET Request i retorna el contingut en format JsonObject public JsonObject readJsonFromUrl(String url) throws IOException { System.out.println(url); InputStream is = new URL(url).openStream(); try { JsonParser par = new JsonParser(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); JsonObject json = (JsonObject) par.parse(jsonText); return json; } finally { is.close(); } } public JsonObject getDistancies (int inici, int fi, String adress, JsonArray bicing) throws IOException{ String array_adreces = ""; JsonRead jr = new JsonRead(); for (int i = inici; i <= fi ; i++){ JsonObject aux = bicing.get(i).getAsJsonObject(); if (aux.get("streetName").getAsString().contains("/")){ array_adreces += aux.get("streetName").getAsString() + ",Barcelona" + "|"; } else { array_adreces += aux.get("streetName").getAsString() + " " + aux.get("streetNumber").getAsString() + ",Barcelona" + "|"; } array_adreces = array_adreces.replaceAll(" ", "+"); } // Fem una web call que ens retorna les distancies de totes les estacions a l'adreça que l'usuari dona JsonObject distancies = jr.readJsonFromUrl("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + array_adreces +"&destinations=" + adress + "&mode=bicycling&language=es-ES&region=es&key=AIzaSyBc2N_mjY8w3cDiqQcra4KjF_Gm4-0ZLUI"); return distancies; } } As can be seen, we send a get request using a number of adresses stored in a Json file. The Json file can be seen here: http://wservice.viabicing.cat/v2/stations However, we think the issue might be related to the request's lenght, because when we reduce it's lenght i gives us no trouble. Here is a resquest (I can't post two links at the moment, sorry): https://maps.googleapis.com/maps/api/distancematrix/json?origins=Gran+Via+Corts+Catalanes+760,Barcelona|Roger+de+Flor/+Gran+Vía,Barcelona|Ali+Bei+44,Barcelona|Ribes+13,Barcelona|Pg+Lluís+Companys+11,Barcelona|Pg+Lluís+Companys+18,Barcelona|Pg+Lluís+Companys+1,Barcelona|Pg+Lluís+Companys+2,Barcelona|Marquès+de+l'Argentera+17,Barcelona|Carrer+Comerç+27,Barcelona|Trelawny+2,Barcelona|Pg+Marítim+Barceloneta+23,Barcelona|Avinguda+Litoral+16,Barcelona|Avinguda+del+Marques+Argentera+19,Barcelona|Girona+74,Barcelona|Av.+Meridiana+47,Barcelona|Av.+Meridiana+47,Barcelona|Rosselló+412,Barcelona|Rosselló+354,Barcelona|Indústria+157,Barcelona|Sant+Antoni+Maria+Claret+214,Barcelona|Sardenya+296,Barcelona|Bruc+45,Barcelona|Marina+185,Barcelona|Bruc+102,Barcelona|Dos+Maig+230,Barcelona|Provença+322,Barcelona|Marina+311,Barcelona|Provença+388,Barcelona|Diagonal+231,Barcelona|Plaça+del+Mar+72,Barcelona|Plaça+del+Mar+1,Barcelona|Baluart+58,Barcelona|Sant+Pere+Més+Alt+4,Barcelona|Sant+Ramon+de+Penyafort+1,Barcelona|Catedral+6,Barcelona|Pl.+Antonio+López+,Barcelona|Pl.+Pau+Vila+,Barcelona|Pl.+Pau+Vila+,Barcelona|Doctor+Aiguader+2,Barcelona|Pl.+Poeta+Boscà/Atlàntida,Barcelona|Ciutat+de+Granada+168,Barcelona|Av+Meridiana+80,Barcelona|Av+Meridiana+66,Barcelona|Marina++65,Barcelona|Ramon+trias+Fargas+19,Barcelona|Ramon+Trias+Fargas+,Barcelona|Meridiana+40,Barcelona|Rosa+Sensat+en+front+20,Barcelona|Av.+Paral.lel+54,Barcelona|Pl.+Vicenç+Martorell+,Barcelona|Pl.+Carles+Pi+i+Sunyer+,Barcelona|Sant+Oleguer+2,Barcelona|La+Rambla+80,Barcelona|Portal+de+Santa+Madrona+2,Barcelona|La+Rambla+2,Barcelona|Plaça+dels+Àngels+1,Barcelona|Plaça+dels+Àngels+2,Barcelona|Rambla+Catalunya++47,Barcelona|Rambla+Catalunya+42,Barcelona|Pl.+Catalunya++5,Barcelona|Pl.+Catalunya+7,Barcelona|Pl.+Catalunya+,Barcelona|Pl.+Catalunya+,Barcelona|Gran+Via+609,Barcelona|Rocafort+214,Barcelona|Rambla+Catalunya+133,Barcelona|Avda.+Litoral+,Barcelona|Villarroel+2,Barcelona|Floridablanca++145,Barcelona|Provença+215,Barcelona|Enric+Granados+99,Barcelona|Josep+Tarradellas+129,Barcelona|Josep+Tarradellas+58,Barcelona|Còrsega+216,Barcelona|Pl.+Universitat+,Barcelona|Pl.+Universitat+,Barcelona|Enric+Granados+35,Barcelona|Vilamarí+davant+61,Barcelona|Rocafort+72,Barcelona|Comte+Borrell+177,Barcelona|Diputació+152,Barcelona|Paral·lel+146,Barcelona|Viladomat+2,Barcelona|Mallorca+41,Barcelona|Londres+101,Barcelona|Rosselló+101,Barcelona|Rosselló+108,Barcelona|Comte+Borrell+119,Barcelona|Provença+241,Barcelona|Gran+Via+375,Barcelona|Gran+Via+375,Barcelona|Tarragona+103,Barcelona|Gran+Via+361,Barcelona|Tarragona+141,Barcelona|Viriat+45,Barcelona|Viriat+53,Barcelona|Tarragona+159,Barcelona|Av.+Diagonal+602,Barcelona|Av.+Diagonal+612,Barcelona|&destinations=Via+Augusta,+209,+08021+Barcelona,+Spain&mode=bicycling&language=es-ES&region=es&key=AIzaSyBc2N_mjY8w3cDiqQcra4KjF_Gm4-0ZLUI As you can see, using a get request for each adress isn't feasible as there ara approximately 100 adresses, is there any way to increase the accepted lenght of a get request? If not, what's the maximum allowed lenght? A: I think that is because we put special character in spain like ´ or ñ.
[ "serverfault", "0000461797.txt" ]
Q: Why is sar output not matching? I am using sar utility for collecting and saving system activity information. After saving the information, I am seeing/reporting the information but the output is not matching. Can some one please help me in understanding the behavior or if I am doing a silly mistake in my understanding. Below are the details. Step 1: To collect and save system activity sar -o sa_30_dec_2012 1 > /dev/null 2>&1 & Step 2: To report first 10 minutes readings with an interval of 1 second sar 1 10 -f sa_30_dec_2012 Step 3: To report first 10 readings within an interval of 2 seconds sar 2 5 -f sa_30_dec_2012 Output of Step 2 07:18:34 IST CPU %user %nice %system %iowait %steal %idle 07:18:35 IST all 1.51 0.00 1.51 3.02 0.00 93.97 07:18:36 IST all 1.50 0.00 1.00 0.00 0.00 97.50 07:18:37 IST all 1.02 0.00 0.51 0.00 0.00 98.48 07:18:38 IST all 2.55 0.00 0.51 0.00 0.00 96.94 07:18:39 IST all 3.03 0.00 0.51 0.00 0.00 96.46 07:18:40 IST all 1.49 0.00 1.49 3.48 0.00 93.53 07:18:41 IST all 1.52 0.00 0.51 0.00 0.00 97.97 07:18:42 IST all 1.01 0.00 1.01 0.00 0.00 97.99 07:18:43 IST all 1.53 0.00 0.00 0.00 0.00 98.47 07:18:44 IST all 2.53 0.00 1.52 0.00 0.00 95.96 Average: all 1.77 0.00 0.86 0.66 0.00 96.72 Output of Step 3 07:18:34 IST CPU %user %nice %system %iowait %steal %idle 07:18:36 IST all 1.50 0.00 1.25 1.50 0.00 95.74 07:18:38 IST all 1.78 0.00 0.51 0.00 0.00 97.71 07:18:40 IST all 2.26 0.00 1.00 1.75 0.00 94.99 07:18:42 IST all 1.26 0.00 0.76 0.00 0.00 97.98 07:18:44 IST all 2.03 0.00 0.76 0.00 0.00 97.21 Average: all 1.77 0.00 0.86 0.66 0.00 96.72 If you observe, the readings for timestamp 07:18:36 match but the readings after that do not match (the values are not equal). For example, the values of the following timestamps are not equal:- Step 2 output 07:18:38 IST all 2.55 0.00 0.51 0.00 0.00 96.94 07:18:40 IST all 1.49 0.00 1.49 3.48 0.00 93.53 Step 3 output 07:18:38 IST all 1.78 0.00 0.51 0.00 0.00 97.71 07:18:40 IST all 2.26 0.00 1.00 1.75 0.00 94.99 Why are the Step 2 and Step 3 outputs not matching? These commands were executed on Ubuntu 12.04 LTS. Any help is very much appreciated. A: Since the interval is changed to 2 seconds, it averages the data for those two seconds. If we take two lines from the first output (two 1-second intervals): 07:18:34 IST CPU %user %nice %system %iowait %steal %idle ... 07:18:37 IST all 1.02 0.00 0.51 0.00 0.00 98.48 07:18:38 IST all 2.55 0.00 0.51 0.00 0.00 96.94 %user (column 4) averages to 1.78 -> (1.02 + 2.55)/2=1.78. Same goes for all other columns. 07:18:38 IST all 1.78 0.00 0.51 0.00 0.00 97.71
[ "stackoverflow", "0001699287.txt" ]
Q: Need help in executing the SQL via shell script and use the result set I currently have a request to build a shell script to get some data from the table using SQL (Oracle). The query which I'm running return a number of rows. Is there a way to use something like result set? Currently, I'm re-directing it to a file, but I'm not able to reuse the data again for the further processing. Edit: Thanks for the reply Gene. The result file looks like: UNIX_PID 37165 ---------- PARTNER_ID prad -------------------------------------------------------------------------------- XML_FILE -------------------------------------------------------------------------------- /mnt/publish/gbl/backup/pradeep1/27241-20090722/kumarelec2.xml pradeep1 /mnt/soar_publish/gbl/backup/pradeep1/11089-20090723/dataonly.xml UNIX_PID 27654 ---------- PARTNER_ID swam -------------------------------------------------------------------------------- XML_FILE -------------------------------------------------------------------------------- smariswam2 /mnt/publish/gbl/backup/smariswam2/10235-20090929/swam2.xml There are multiple rows like this. My requirement is only to use shell script and write this program. I need to take each of the pid and check if the process is running, which I can take care of. My question is how do I check for each PID so I can loop and get corresponding partner_id and the xml_file name? Since it is a file, how can I get the exact corresponding values? A: Here is one suggested approach. It wasn't clear from the sample you posted, so I am assuming that this is actually what your sample file looks like: UNIX_PID 37165 PARTNER_ID prad XML_FILE /mnt/publish/gbl/backup/pradeep1/27241-20090722/kumarelec2.xml pradeep1 /mnt/soar_publish/gbl/backup/pradeep1/11089-20090723/dataonly.xml UNIX_PID 27654 PARTNER_ID swam XML_FILE smariswam2 /mnt/publish/gbl/backup/smariswam2/10235-20090929/swam2.xml I am also assuming that: There is a line-feed at the end of the last line of your file. The columns are separated by a single space. Here is a suggested bash script (not optimal, I'm sure, but functional): #! /bin/bash cat myOutputData.txt | while read line; do myPID=`echo $line | awk '{print $2}'` isRunning=`ps -p $myPID | grep $myPID` if [ -n "$isRunning" ] then echo "PARTNER_ID `echo $line | awk '{print $4}'`" echo "XML_FILE `echo $line | awk '{print $6}'`" fi done The script iterates through every line (row) of the input file. It uses awk to extract column 2 (the PID), and then does a check (using ps -p) to see if the process is running. If it is, it uses awk again to pull out and echo two fields from the file (PARTNER ID and XML FILE). You should be able to adapt the script further to suit your needs. Read up on awk if you want to use different column delimiters or do additional text processing. Things get a little more tricky if the output file contains one row for each data element (as you indicated). A good approach here is to use a simple state mechanism within the script and "remember" whether or not the most recently seen PID is running. If it is, then any data elements that appear before the next PID should be printed out. Here is a commented script to do just that with a file of the format you provided. Note that you must have a line-feed at the end of the last line of input data or the last line will be dropped. #! /bin/bash cat myOutputData.txt | while read line; do # Extract the first (myKey) and second (myValue) words from the input line myKey=`echo $line | awk '{print $1}'` myValue=`echo $line | awk '{print $2}'` # Take action based on the type of line this is case "$myKey" in "UNIX_PID") # Determine whether the specified PID is running isRunning=`ps -p $myValue | grep $myValue` ;; "PARTNER_ID") # Print the specified partner ID if the PID is running if [ -n "$isRunning" ] then echo "PARTNER_ID $myValue" fi ;; *) # Check to see if this line represents a file name, and print it # if the PID is running inputLineLength=${#line} if (( $inputLineLength > 0 )) && [ "$line" != "XML_FILE" ] && [ -n "$isRunning" ] then isHyphens=`expr "$line" : -` if [ "$isHyphens" -ne "1" ] then echo "XML_FILE $line" fi fi ;; esac done I think that we are well into custom software development territory now so I will leave it at that. You should have enough here to customize the script to your liking. Good luck!
[ "stackoverflow", "0021539882.txt" ]
Q: Initialize listbox in c# with a list I want to initialize value and memberDisplay of my list box using the output of this code : Here is my code : public List<showMaterialGroup> ShowSubGroup() { List<showMaterialGroup> q = (from i in dbconnect.tblMaterialGroups.AsEnumerable() where i.tenderId == _tenderId select new showMaterialGroup() { id = i.id.ToString(), title = i.title, documentnumber = ReturnDocNumber(i.tenderId), }).ToList(); return q; } Here i call the function : txtgroup.DisplayMember = objtender.ShowSubGroup(); txtgroup.ValueMember = objtender.ShowSubGroup(); So how can i do that? A: I'm assuming txtgroup is a ListBox, even though it's sorta named like a TextBox might be named. You can't assign a list to the DisplayMember and ValueMember properties. Assign the list as the DataSource, then use the DisplayMember and ValueMember properties to specify which field should be displayed to the user and used as the actual value for the item in the list, respectively. Try this instead: txtgroup.DataSource = objtender.ShowSubGroup(); txtgroup.DisplayMember = "title"; txtgroup.ValueMember = "id";
[ "stackoverflow", "0018035483.txt" ]
Q: Yii: How to get list of checkboxes? I have a table called Table, it has id and name as attributes. For each entry in Table, I would like to generate a checkbox. How can I do this? I am using the Yii-Boostrap plugin, which I'm expecting I would need use something like this: foreach(...) echo $form->checkBoxRow($model, 'name'); Which I got from the Yii-Bootstrap Documentation. A: Try this simple one And in this for precheck to work just pass the array as second parameter as shown below <?$select=array('2','3');?> <?php echo CHtml::checkBoxList( 'TableValues', '$select',//you can pass the array here which you want to be pre checked CHtml::listData(Table::model()->findAll(),'id','name'), array('checkAll'=>'Select all tasks', 'checkAllLast'=>true) ); ?> And you can get the selected checkbox values in the controller using print_r($_POST['TableValues']); UPDATED For this the precheck to work u have to assign the array to the model attribute as shown below <?php $model->modelAttributename=array('3','5')//respective checked values as of yours <?php echo $form->checkBoxList( $model, 'modelAttributename', CHtml::listData(Table::model()->findAll(),'id','name'), array('checkAll'=>'Select all tasks', 'checkAllLast'=>true) ); ?>
[ "stackoverflow", "0009363755.txt" ]
Q: Replacing contenteditable characters on the fly with (or without) rangy I'm working on a little experimental editor where I would like to visualize the time between typed characters. Therefore I'm using javascript and a contenteditable div to wrap every character with a SPAN and a timestamp attribute. I build a little function with the help of rangy: function insertAtCursor(char, timestamp) { var sel = rangy.getSelection(); var range = sel.rangeCount ? sel.getRangeAt(0) : null; if (range) { var el = document.createElement("span"); $(el).attr('time', timestamp); el.appendChild(document.createTextNode(char)); range.insertNode(el); range.setStartAfter(el); rangy.getSelection().setSingleRange(range); } } Now I'm facing two problems with this concept where I would appreciate some help: a. With the above function the output ends in nested span's like seen here: <span time="12345">a <span time="12345">b <span time="12345">c</span> </span> </span> b. Even if I could get the above function running, a copy&paste or drag&drop action would possibly also end in some nested span's ... and I wonder if there is a way to avoid that at all? Thanks, Andreas A: I'm not convinced this a good idea overall, particularly if the text could get large. A couple of improvements: time should probably be data-time to validate as HTML5 you need to handle the case where some content is selected (adding range.deleteContents() would do). However, if you are going to do this, I would suggest checking if the cursor is at the end of a text node inside an existing <span> and appending the new <span> after the text node's parent. Something like this: Live demo: http://jsfiddle.net/kWL82/1/ Code: function insertAtCursor(char, timestamp) { var sel = rangy.getSelection(); var range = sel.rangeCount ? sel.getRangeAt(0) : null; var parent; if (range) { var el = document.createElement("span"); $(el).attr('data-time', timestamp); el.appendChild(document.createTextNode(char)); // Check if the cursor is at the end of the text in an existing span if (range.endContainer.nodeType == 3 && (parent = range.endContainer.parentNode) && (parent.tagName == "SPAN")) { range.setStartAfter(parent); } range.insertNode(el); range.setStartAfter(el); rangy.getSelection().setSingleRange(range); } }
[ "scifi.stackexchange", "0000076930.txt" ]
Q: How do people in the Matrix develop a residual self image that resembles their own body? As we know people born in and connected to the Matrix retain a residual self image. Morpheus told Neo: Your appearance now is what we call residual self image. It is the mental projection of your digital self. Freed people that hack back into the Matrix keep that projection and do not change it at will (see: Did People Within The Matrix Always Resemble their Real World Bodies?). But here's the question: How do people born (or grown for that matter) in the Matrix develop a residual self image that resembles their own body in the first place? You simply do not know how you look if you never saw yourself. It would therefore require that the Matrix feeds your brain with a mental image based on your real body thus requiring some scanners (or whatever) inside the tank to obtain ones features within the goo. That leads to the more important question as to why would the machines go through all this trouble to provide "proper" residual self images for their connected humans? The prime purpose of the Matrix is to keep their "guests" attached for live, pretty unaware of the fact that they are in the Matrix - as Morpheus puts it, blinded from the truth of being a prisoner. That goal could be perfectly achieved without everybody knowing their own look safe those who are freed from the Matrix (but then again why would the machines be worried about them)? For the sake of the discussion lets assume that there is only one layer of the Matrix - that being: the "Zion-real world" is the real world - as nested layers of the Matrix would of course simplify things greatly. A: The line about "residual self image" occurred when they were in a construct--a small virtual world created by the computers of the Nebuchadnezzar, disconnected from the Matrix. See the transcript here), when Neo asks "Right now we're inside a computer program?", Morpheus replies: Is it really so hard to believe? Your clothes are different. The plugs in your arms and head are gone. Your hair is changed. Your appearance now is what we call residual self image. It is the mental projection of your digital self. So I think the implication is that his image in the construct was not directly determined by the programming of the construct, but depended on his own mental self-image, which he had formed from seeing his own "digital self" during his life in the Matrix (which would explain why his appearance in the construct matched how he had looked in the Matrix rather than how he looked in the real world, as Omegacron pointed out, and note that the scriptwriters actually had Morpheus highlight this point in the beginning of the line I quoted). There was nothing to suggest it worked the same way in the Matrix--to speculate, a person's appearance there may have been programmed by the machines to simulate what the person would look like if they were able to exercise their muscles, grow their hair etc., given their genetics and other biological factors present at birth. A: The brain and the body are still connected You're assuming there's a total disconnect between brain and body. Based on what we see (damage to the brain causes damage to the real-world body, conversely damage to the real-world body also causing the digital self to falter) this simply isn't true. Morpheus: The body cannot live without the mind Since the brain and body are intimately connected it makes perfect sense for the RSI to mirror the real world body, ensuring the minimum of effort on the part of the machines. Imagine the additional computing power needed to trick a 10-year-old into thinking they've got the body of a 30-year-old or to explain to a supposedly healthy 20-year-old (who's really 80) why they're tired all the time. The machines want to be helpful The Matrix and Zion are a sham. The whole point is to allow the small proportion of dissidents to freely move around inside it and escape from it. If the RSI was dramatically different from the self, it would make things much harder. You simply wouldn't know who was who and who you could trust. The machines can scan you As to how, as you've already pointed out, the machines have access to your body. It would be a simple matter for them to scan you periodically and then serve that image up to you whenever you view yourself (on film, in mirrors or when you look down) so you see what they want you to see. These images will reinforce your own self-image as you grow up. A: This is more of a psychology question than plot explanation, but the answer is still the same. Any human being - even one that has never seen themselves in a reflection, such as a blind person - has a mental image of what they imagine themselves to look like. This is human nature, and occurs with both children and adults. To address your question, however, the "residual self" presented in the film is an image of their digital self, not the physical one sitting in a capsule somewhere. Someone who grew up in the Matrix would have only their digital selves to judge by, which is why Neo appeared similar to how he did within the Matrix (sans plugs and nifty new hairstyle). The convenient fact that everyone's digital self looks like their actual body is a conceit by the film-makers that must be taken as fact in the Matrix-verse.
[ "math.stackexchange", "0001875411.txt" ]
Q: Real proofs with shorter equivalent proofs in Complex numbers? Are there any proofs about Real numbers that have shorter equivalent proofs going through Complex numbers? Are there proofs about Integers going through Reals, with longer equivalent proofs using pure Integers? A: Many many interesting definite integrals of functions whose indefinite integrals have no closed form are derived using contour integration in the complex plane. Some of these can, however, be derived by far messier work in the real line. Almost everything involving computational complexity in computer science ends up using the logarithm, which can be defined for only integer arguments if you choose to do so, but whose properties, as a function on the reals, are of great interest and use in complexity analysis.
[ "math.stackexchange", "0003070402.txt" ]
Q: Probability disjunction: Sum probabilities greater than actual probability Is it true that $$P(A \lor B \lor C \lor ...) \leq P(A) + P(B) + P(C) + ...$$? I saw the general form of the probability disjunction here: https://stats.stackexchange.com/questions/87533/whats-the-general-disjunction-rule-for-n-events , but the right-hand side of the formula contains positive terms beyond simply $P(A)$, $P(B)$, etc. My attempt by induction: $$P(A \lor B) = P(A) + P(B) - P(A \land B) \leq P(A) + P(B)$$ Assume now $P(\bigvee_{i=1}^n C_i) \leq \sum_{i=1}^nP(C_i)$ Then $$P(C_{n+1}\lor \bigvee_{i=1}^n C_i) = P(\bigvee_{i=1}^n C_i) + P(C_{n+1}) - P(C_{n+1}\land \bigvee_{i=1}^n C_i) \leq \sum_{i=1}^nP(C_i) + P(C_{n+1}) - P(C_{n+1}\land \bigvee_{i=1}^n C_i) \leq \sum_{i=1}^nP(C_i) + P(C_{n+1})$$ A: Yes the statement is true. Let $(A_i)_{i\geq 1}$ be a collection of events. Then note that $$ \begin{align} P\left(\bigcup_{i=1}^\infty A_i\right) &=P(A_1)+P(A_2\bar{A_1})+P(A_3\bar{A_2}\bar{A_1})+P(A_4\bar{A_3}\bar{A_2}\bar{A_1})+\dotsb\\ &\leq P(A_1)+P(A_2)+P(A_3)+P(A_4)+\dotsb \end{align} $$ where the first equality is by countable additivity and the second by the fact that $A\subseteq B\implies P(A)\leq P(B)$.
[ "stackoverflow", "0004008231.txt" ]
Q: flexigrid popup modal window I am trying to create a script using FLEXIGRID as a method to display the information from a database, but I want the users to able to input info into the database as well. I would like to be able to launch a modal window where the user can input the information and submit it. The way the buttons on the FLEXIGRID are coded is as following: $(document).ready(function(){ $("#flex1").flexigrid ( { url: 'post2.php', dataType: 'json', colModel : [ {display: 'ID', name : 'id', width : 40, sortable : true, align: 'center', hide: true}, ...... buttons : [ {name: 'Add', bclass: 'add', onpress : test}, {separator: true}, {name: 'Delete', bclass: 'delete', onpress : test}, {separator: true}, .... some more code ... } ); }); function test(com,grid) { if (com=='Add') { the code that triggers the modal window } } Okay, my problem: When I press 'Add', I would like a modal popup window to appear to load using Ajax the content of a local file so the user can input the information. What I have so far: I tried using the code from JqModal: loaded the CSS and Javascript: <link rel="stylesheet" type="text/css" href="css/jqmodal.css" /> <script type="text/javascript" src="js/jqModal.js"></script> $().ready(function() { $('#ex2').jqm({ajax: 'examples/2.html', trigger: 'a.ex2trigger'}); }); added the div at the bottom of the page: <div class="jqmWindow" id="ex2"> Please wait... <img src="inc/busy.gif" alt="loading" /> </div> but how to trigger the function? Thanks, Cristian. LE: This is the code I have right now and it still doesn't work: IE says: Object doesn't support this property or method flexigrid, line 56 character 5 That's exactly where the $dialog function starts. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Flexigrid</title> <link rel="stylesheet" type="text/css" href="css/flexigrid.css" /> <link rel="stylesheet" type="text/css" href="css/jquery-ui-1.7.3.custom.css" /> <script type="text/javascript" src="js/jquery-1.2.3.pack.js"></script> <script type="text/javascript" src="js/flexigrid.js"></script> <script type="text/javascript" src="js/jquery-ui-1.7.3.custom.min.js.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#flex1").flexigrid ( { url: 'post2.php', dataType: 'json', colModel : [ {display: 'ID', name : 'id', width : 40, sortable : true, align: 'center', hide: true}, {display: 'URL', name : 'url', width : 450, sortable : true, align: 'left'}, {display: 'File Name', name : 'filename', width : 270, sortable : true, align: 'left'}, {display: 'Availability', name : 'availability', width : 50, sortable : true, align: 'center'}, {display: 'State', name : 'state', width : 40, sortable : true, align: 'center'}, {display: 'Total Size', name : 'totalsize', width : 90, sortable : false, align: 'center'}, {display: 'Current Size', name : 'currentsize', width : 90, sortable : false, align: 'center'}, {display: 'Procent', name : 'procent', width : 40, sortable : true, align: 'center'}, {display: 'Log', width : 20, sortable : false, align: 'center'}, ], buttons : [ {name: 'Add', bclass: 'add', onpress : test}, {separator: true}, {name: 'Delete', bclass: 'delete', onpress : test}, {separator: true}, {name: 'Select All', bclass : 'selectall', onpress : test}, {name: 'DeSelect All', bclass : 'deselectall', onpress : test}, {separator: true} ], searchitems : [ {display: 'URL', name : 'url'}, {display: 'Filename', name : 'filename', isdefault: true} ], sortname: "state", sortorder: "asc", usepager: true, title: '', useRp: false, rp: 10, showTableToggleBtn: true, singleSelect: true } ); }); $(document).ready(function() { $("#myDialog").dialog({ autoOpen: false, resizable: false, position: 'center', stack: true, height: 'auto', width: 'auto', modal: true }); $("#showDialog").button().click(function (event) { $("#myDialog").dialog('open'); }); }); function test(com,grid) { if (com=='Add') { $("#myDialog").dialog('open'); } if (com=='Select All') { $('.bDiv tbody tr',grid).addClass('trSelected'); } if (com=='DeSelect All') { $('.bDiv tbody tr',grid).removeClass('trSelected'); } if (com=='Delete') { if($('.trSelected',grid).length>0){ if(confirm('Delete ' + $('.trSelected',grid).length + ' items?')){ var items = $('.trSelected',grid); var itemlist =''; for(i=0;i<items.length;i++){ itemlist+= items[i].id.substr(3)+","; } $.ajax({ type: "POST", url: "delete.php", data: "items="+itemlist, success: function(data){ $('#flex1').flexReload(); alert(data); } }); } } else { return false; } } } </script> </head> <body> <table id="flex1" style="display:none"></table> <div id="myDialog" style="display:none" title=""></div> </body> </html> LE2: How to load the external file thru ajax: $(document).ready(function(){ //define config object var dialogOpts = { modal: true, bgiframe: true, autoOpen: false, height: 500, width: 500, draggable: true, resizeable: true, open: function() { //display correct dialog content $("#myDialog").load("form.php");} }; $("#myDialog").dialog(dialogOpts); //end dialog $('#showdialog').click(function (event){ $("#myDialog").dialog("open"); return false; } ); }); A: The following sample will work with jQuery UI dialog First defines the needed markup for the dialog: <div id="myDialog" style="display:none" title=""></div> Then, on DOM ready, setup the dialog to be a jquery UI dialog $("#myDialog").dialog({ autoOpen: false, position: 'center', stack: true, height: 'auto', width: 'auto', modal: true }); Please notice the autoOpen: false parameter. When you want to show the dialog just call the open method inside of your code function test(com,grid) { if (com=='Add') { $("#myDialog").dialog('open'); } } hope it helps! Update: I have created a sample on jsbin.com for you. You can see it working here while you can see the code here.
[ "stackoverflow", "0031894062.txt" ]
Q: Rails: Building a link_to link with nested resources I have three models in my routes.rb: resources :products do resources :departments, :revenues end I'm trying to link to a product's department from the department show.html like this: <% @products.each do |product| %> <%= link_to product_department_path(:id => product.id) do %><li><%= product.name %></li><% end %> <% end %> What this is doing is giving me HTML like this: <ul> <a href="/products/2/departments/1"><li>Product1</li></a> <a href="/products/2/departments/2"><li>Product2</li></a> <a href="/products/2/departments/3"><li>Product3</li></a> <a href="/products/2/departments/5"><li>Product4</li></a> </ul> What I really need is this: <ul> <a href="/products/1/departments/"><li>Product1</li></a> <a href="/products/2/departments/"><li>Product2</li></a> <a href="/products/3/departments/"><li>Product3</li></a> <a href="/products/4/departments/"><li>Product4</li></a> </ul> A: Your code is a little verbose, so I have simplified it. I think you want product_departments_path <li> <%= link_to product.name, product_departments_path(product) %> </li>
[ "stackoverflow", "0001796199.txt" ]
Q: web.xml URL pattern matching question for Tomcat I'd like to use this kind of a pattern for my Java web app: <url-pattern>/*/test.html</url-pattern> and then parse the URL in the servlet to get what the value of the star is, and use that value to query a different table in the database. However this seems to be an illegal pattern for Tomcat. Is there any way I can achieve this without having to hard code the bit between the slashes? (example uses in case you're wondering what the context is: /vancouver-hotel/rooms.html, /seattle-hotel/rooms.html) A: Best way is to rearrange your URL structure to /hotels/<cityname> and let a HotelServlet listen on /hotels/* and get the <cityname> as pathinfo using request.getPathInfo(). You can use the usual java.lang.String methods to parse the pathinfo further. For example a split("/") and then storing the parts as a request attribute or something else which can be accessed by business/domain objects.
[ "history.stackexchange", "0000050924.txt" ]
Q: Why is the name "Tecumseh" used for US Navy ships? It is common practice to name warships after historical heroes of a nation. The US Navy had four vessel named USS Tecumseh Two of them were tugboats, but the other two were a then-cutting-edge ironclad monitor and ballistic missile submarine. Yet Tecumseh was never the hero of the US. He was a bitter enemy, allying with the British in the War of 1812, and trying to establish a Native American state, halting US advance to the West forever. Why is he then so honored by ship-namings? Is he deemed so gallant and cool to warrant this? Side question: Were there other US ships named after vanquished foes (other than Confederate generals), and especially Native Americans? PS.: I do not wish in any way suggest, that I am not OK with the ships so named, just curious. I could definitely not imagine an USS Lord Cornwallis or USS Santa Anna. A: While Tecumseh was an enemy of the US while alive, his name was well known. The first ship named after him was a Canonicus-class monitor during the Civil War, some 50 years after Tecumseh's death. The other Canonicus monitors were named after other Native Americans or places with names derived from Native American words (generally - the first was renamed Ajax from Manayunk after the war). So, 50 years after his death the name was still known. Further, the story of the statue named "Tecumseh" at the US Naval Academy, installed in 1866 at the Academy, is instructive. The statue was actually of another Native American, Tamanend, and served as the bowsprit of the Delaware, sunk in the Civil War. It ended up being named Tecumseh instead, which indicates with some clarity that (a) the name was well known, and (b) the name was respected by the midshipmen of the time. Respecting the qualities of one's enemies is not an unusual occurrence, particularly after several generations have passed. Now, why was Tecumseh still known some 50 years after his death? An article in the Indiana Magazine of History from 1989 sheds some background. It would appear that his life was written about quite often. The first body of literature, coming from a predominantly antebellum romantic school, portrayed Tecumseh as the noble savage. This forceful interpretation persists in popular and academic writings to the present day even though it faded after the Civil War. Further, the article has evidence that he was written about with much praise shortly after his death. It quotes an 1820 letter to the Indiana Centinal [sic]: Every schoolboy in the Union now knows that Tecumseh was a great man. He was truly great - and his greatness was his own, unassisted by science or the aid of education. As a statesman, a warrior and a patriot, take him all in all, we shall not look upon his like again. Combined with multiple pre Civil War biographies of Tecumseh, it is clear that the story of Tecumseh was broadly known and often romanticized. It would seem quite likely that, when the US Navy went in search of names for a class of ships named after Native Americans, Tecumseh's name would be high on the list. As for the names in the Canonicus (and other monitors) class, the Monitor Center notes: A note on the names of these vessels seems in order. Secretary of the Navy Gideon Welles directed that new vessels being built should illustrate the pride of the American nation by having distinctly American names. As a result, many of the monitors received names of American rivers, lakes, mountains, cities or Indian tribes. This practice created a list of names that in some cases proved nearly unpronounceable. The practice nevertheless remained in place until 1869, when the new Secretary of the Navy, Adolph A. Borie, ordered the wholesale renaming of ships, often adopting new names based on classical Greek figures or gods. This practice has somewhat complicated for many the tracing of these Civil War era ships.
[ "stackoverflow", "0006726939.txt" ]
Q: Which is the correct way to register a new net_device? i'm trying to register a new net_device in linux...i can alloc and register it correctly and ifconfig shows it. The problem arrives when i try to put the interface up: ifconfig my_dev up A kernel freeze occurs...the problem is present only on x86 machines and i can't figure out the reason...on a pcc machine all works well. The code is very simple: static struct net_device *my_dev; static int veth_dev_init(struct net_device *dev); static int veth_open(struct net_device *dev); static int veth_close(struct net_device *dev); static int veth_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd); static struct veth_priv { ... }; static struct net_device_ops veth_ops = { .ndo_init = veth_dev_init, .ndo_open = veth_open, .ndo_stop = veth_close, .ndo_do_ioctl = veth_ioctl }; static int __init veth_init() { my_dev = alloc_netdev(sizeof(struct veth_priv), "my_dev", ether_setup); if (my_dev == NULL) return -ENOMEM; my_dev->netdev_ops = &veth_ops; register_netdev(my_dev); return 0; } static void __exit veth_exit() { unregister_netdev(my_dev); free_netdev(my_dev); } module_init(veth_init); module_exit(veth_exit); The first four functions veth_dev_init, veth_open, veth_close and veth_ioctl simply return 0. Maybe is there a missing field in veth_ops structure? Thank you all! A: Yea, you missed one element in struct net_device_ops Add .ndo_start_xmit also, And the function must return NETDEV_TX_OK or NETDEV_TX_BUSY. use as follows static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev) { return NETDEV_TX_OK; } And also change the open as static int veth_open(struct net_device *dev) { memcpy(dev->dev_addr, "\0ABCD0", ETH_ALEN); netif_start_queue(dev); return 0; } Then in veth_ops static struct net_device_ops veth_ops = { .ndo_init = veth_dev_init, .ndo_open = veth_open, .ndo_stop = veth_close, .ndo_start_xmit = veth_xmit, .ndo_do_ioctl = veth_ioctl, }; Then after inserting the module give ifconfig my_dev 192.168.10.98 ...
[ "physics.stackexchange", "0000359857.txt" ]
Q: What is the origin of gravity? We know that an object that feels no force should travel at a constant speed. But a body accelerating because of gravity feels no force. This seems to be a paradox. Could we possibly find the origins of gravity if we solve this paradox? A: This is too broad a question to do it justice here, but basically you are quite correct that the fact a freely falling observer is weightless was the key to constructing general relativity. The starting point for the work on general relativity was the statement of the equivalence principle. This can be stated in lots of ways, but basically it states that inertial and gravitational mass are equivalent. So when you write Newton's second law: $$ F = ma $$ and Newton's law of gravity: $$ F = \frac{GMm}{r^2} $$ The equivalence principle tells us that the $m$ in both equations is the same. The equivalence principle also means that an observer in free fall must experience no force, or technically that their proper acceleration is zero. Trying to construct a theory that includes this principle leads you straight to a class of theories called metric theories, and of this type of theory general relativity is the simplest one that works. Since a stray string theorist has wandered into the hallowed halls of general relativity I'd like to expand on my answer to talk a bit about what is going on. Suppose ACuriousMind is the one falling towards the Earth and I am the one stationary on the surface. And suppose someone has sneaked up behind us and blindfolded us both so we can't see what's happening. How do we know which of us is falling and which is standing on the Earth's surface? The answer is simply that ACM feels himself to be weightless while I feel my weight i.e. I feel the surface of the Earth pushing me upwards. So even though neither of us can see a thing we both know where we are. But now suppose someone sneakily removes the earth and places a rocket motor under my feet that accelerates upwards at $9.81$ m/s$^2$. Since there's no Earth there is no gravity so ACM is just happily floating weightless in space. But I feel an acceleration pushing me up just like the Earth's gravity. Both of us are blindfolded remember, so as far we as know nothing has changed and the situation is exactly the same as it was before. But of course now there is no gravity. Now I am in a non-inertial frame, while you are in an inertial frame, and this is the point made in ACuriousMind's answer. You are accelerating towards me because I am accelerating towards you. So you can be accelerating towards me even though you are weightless. So why did I jump straight to general relativity? Well let's put the Earth back, and now suppose my brother Albert has dug a deep tunnel right to the centre of the Earth and is hovering there. He is hovering because the gravity at the centre of the Earth because the gravity falls to zero at the centre of the Earth. And since I am stationary on the surface and Albert is stationary at the centre we are stationary with respect to each other. That means ACM is accelerating (as he falls) towards both me and Albert at the same rate. But, Albert is weightless while I'm not. Unlike before we can't snatch the Earth away and reproduce the situation with rocket motors. For both Albert and ACM to be weightless they cannot be accelerating towards each other. And this is the key point. We can always reproduce the effect of gravity using Newtonian mechanics and non-inertial frames, but we can only do it locally. That is we can do it for selected pairs of observers but not for all observers. And this is where general relativity comes in. A: This is not special to gravity, and has nothing to do with the equivalence principle as some comments and answers here imply. You are mischaraterizing Newton's laws. We don't know that an object that "feels no force" should travel at constant speed, we know that an object upon which in an inertial frame of reference no force acts should travel at constant speed. And actually, in the non-inertial comoving frame of reference in which the object rests and thus feels no force, we have that the object still doesn't move - but the earth does, so the law still holds - the object feels no force and, in its comoving frame of reference, indeed travels at the constant speed of 0. Your paradox arises not from anything special about gravity - you could create the exact same "paradox" for any other force between two bodies - but from the failure to distinguish which reference frame we are talking about. In the object's frame, it experiences no force and moves at zero speed. In the earth's frame, it experiences a force and accelerates.