input
stringlengths
51
42.3k
output
stringlengths
18
55k
Add timer to change image on hover <p>So here's my code and the <a href="https://jsfiddle.net/dgvtvvj0/" rel="nofollow">jsfiddle</a>. The effects works great, only thing is I have no idea how to add a timer to it.</p> <p>E.g. When someone hovers over the image, it doesn't change the image instantly. You have to keep the cursor over it for 10 seconds before it will change.</p> <p>HTML</p> <pre><code>&lt;a href="https://www.google.com/"&gt;&lt;img src="chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png" onmouseover="this.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-images-content.png'" onmouseout="this.src='chrome-extension://cipmepknanmbbaneimacddfemfbfgpgo/images/content/providers/google-translate-content.png'" /&gt;&lt;/a&gt; </code></pre>
<p>You could use setTimeout() function from Javascript to do your thing</p> <pre><code>onmouseover="window.setTimeout(function(){ document.getElementById('image1').src='http://www.w3schools.com/css/img_fjords.jpg' },1000);" </code></pre> <p>Note that this.src may no longer work.</p> <p><a href="https://jsfiddle.net/BoyWithSilverWings/dgvtvvj0/3/" rel="nofollow">https://jsfiddle.net/BoyWithSilverWings/dgvtvvj0/3/</a></p>
Replacing Captured Groups in Regular Expression <p>Is it possible to do something like the following:</p> <pre><code>Sub GetANewDirectory() Dim MyString As String MyString = "C:\File1\File2\File3\AnImportantFile.txt" Dim MyRegEx As New VBScript_RegExp_55.RegExp With MyRegEx .Global = True .IgnoreCase = True .MultiLine = False .Pattern = ".*(File1)\\(File2)\\(File3).*" End With Dim MyMatch As Variant Set MyMatch = MyRegEx.Execute(MyString) ' The following syntax doesn't work MyMatch(0).SubMatches(0) = Func1(MyMatch(0).SubMatches(0)) MyMatch(0).SubMatches(1) = Func2(MyMatch(0).SubMatches(1)) MyMatch(0).SubMatches(2) = Func3(MyMatch(0).SubMatches(2)) Debug.Print MyMatch(0) ' My desired result is: ' C:\File1Apple\File2Banna\File3Mango\AnImportantFile.txt End Sub Function Func1(Arg1 As String) As String Func1 = Arg1 &amp; "Apple" End Function Function Func2(Arg1 As String) As String Func2 = Arg1 &amp; "Banna" End Function Function Func3(Arg1 As String) As String Func3 = Arg1 &amp; "Mango" End Function </code></pre> <p>My apologies if this seems a bit abstract, but I have a real need for something like this. I am certain that I can accomplish the task without regular expressions, but I can see where this kind of feature could be useful.</p>
<p>If you really need the usage of external functions to handle the operation, then your best option (with a regular expression) is to pass a function pointer into the <code>.Replace</code> method of the <code>RegExp</code> object. This function will receive as argument:</p> <ol> <li>The part of the string that matched the pattern in the <code>RegExp</code></li> <li>One argument for each of the capture groups in the pattern</li> <li>The offset inside the original string where the pattern matched</li> <li>The original string</li> </ol> <p>The function must return the string that will replace the part of the original string that matched the pattern.</p> <pre><code>Option Explicit Dim MyString MyString = "C:\File1\File2\File3\AnImportantFile.txt" With New RegExp .Global = True .IgnoreCase = True .MultiLine = False ' groups: (1 ) (2 ) (3 ) .Pattern = "\\([^\\]+)\\([^\\]+)\\([^\\]+)\\" MyString = .Replace(MyString, GetRef("ReplaceHandler")) End With WScript.Echo MyString Function ReplaceHandler( matchedString, group1, group2, group3, offset, originalString ) ReplaceHandler = Join(Array("", Func1(group1), Func2(group2), Func3(group3), ""), "\") End Function Function Func1( Arg1 ) Func1 = Arg1 &amp; "Apple" End Function Function Func2( Arg1 ) Func2 = Arg1 &amp; "Banna" End Function Function Func3( Arg1 ) Func3 = Arg1 &amp; "Mango" End Function </code></pre>
Divide elements of column by a sum of elements (of same column) grouped by elements of another column <p>I have been working on a spark application and was trying to transform a dataframe as shown in table 1. I want to divide each element of a column (_2) by a sum of elements (of same column) grouped by elements of another column (_1). Table 2 is the expected result.</p> <p><strong>table 1</strong></p> <pre><code>+---+---+ | _1| _2| +---+---+ | 0| 13| | 0| 7| | 0| 3| | 0| 1| | 0| 1| | 1| 4| | 1| 8| | 1| 18| | 1| 4| +---+---+ </code></pre> <p><strong>table 2</strong></p> <pre><code>+---+----+ | _1| _2 | +---+----+ | 0|13/x| | 0| 7/x| | 0| 3/x| | 0| 1/x| | 0| 1/x| | 1| 4/y| | 1| 8/y| | 1|18/y| | 1| 4/y| +---+----+ </code></pre> <p>where, x= (13+7+3+1+1) and y = (4+8+18+4)</p> <p>Then, I want to calculate entropy for each element in column _1: i.e. for each element in column _1 calculate <strong><em>sum(p_i x log(p_i))</em></strong> in the column _2. Where, p_i's are basically the values in column _2 for each value in column _1 in <strong>table 2</strong>.</p> <p>The final output would be.</p> <pre><code>+---+---------+ | _1| ENTROPY | +---+---------+ | 0|entropy_1| | 1|entropy_2| +---+---------+ </code></pre> <p>How can I implement this in spark (preferably in scala)? What would be the optimized way to perform the above operations? I'm new to scala, any related suggestions will be highly appreciated.</p> <p>Thank you. </p>
<p>If you want a concise solution and groups are reasonably small you can use window functions. First you have to define a window:</p> <pre><code>import org.apache.spark.sql.expressions.Window val w = Window.partitionBy("_1").rowsBetween(Long.MinValue, Long.MaxValue) </code></pre> <p>probability:</p> <pre><code>import org.apache.spark.sql.functions.sum val p = $"_2" / sum($"_2").over(w) val withP = df.withColumn("p", p) </code></pre> <p>and finally the entropy:</p> <pre><code>import org.apache.spark.sql.functions.log2 withP.groupBy($"_1").agg((-sum($"p" * log2($"p"))).alias("entropy")) </code></pre> <p>For the example data </p> <pre><code>val df = Seq( (0, 13), (0, 7), (0, 3), (0, 1), (0, 1), (1, 4), (1, 8), (1, 18), (1, 4)).toDF </code></pre> <p>the result is:</p> <pre class="lang-none prettyprint-override"><code>+---+------------------+ | _1| entropy| +---+------------------+ | 1|1.7033848993102918| | 0|1.7433726580786888| +---+------------------+ </code></pre> <p>If window functions are not acceptable performance wise you can try aggregation-join-aggregation:</p> <pre><code>df.groupBy($"_1").agg(sum("_2").alias("total")) .join(df, Seq("_1"), "inner") .withColumn("p", $"_2" / $"total") .groupBy($"_1").agg((-sum($"p" * log2($"p"))).alias("entropy")) </code></pre> <p>where:</p> <pre><code>df.groupBy($"_1").agg(sum("_2").alias("total")) </code></pre> <p>computes sum of <code>_2</code> by <code>_1</code>, </p> <pre><code>_.join(df, Seq("_1"), "inner") </code></pre> <p>adds aggregated column to the original data,</p> <pre><code>_.withColumn("p", $"_2" / $"total") </code></pre> <p>computes probabilities, and:</p> <pre><code>_.groupBy($"_1").agg((-sum($"p" * log2($"p"))).alias("entropy")) </code></pre> <p>aggregates to get entropy.</p>
Polymer 1.x: Getting custom element to say HELLO WORLD in Plunker <p><a href="http://plnkr.co/edit/p7IE7v6DHLVnEggeO8PF?p=preview" rel="nofollow">In this Plunk, why won't the <code>x-foo</code> element render HELLO WORLD?</a>.</p> <p>Given the more complex <code>content-el</code> seems to be importing an <code>iron-data-table</code> perfectly correctly. Am I overlooking something simple? Please answer with a working plunk.</p> http://plnkr.co/edit/p7IE7v6DHLVnEggeO8PF?p=preview <pre><code>&lt;base href="https://polygit.org/polymer/components/"&gt; &lt;link rel="import" href="polymer/polymer.html"&gt; &lt;script src="webcomponentsjs/webcomponents-lite.min.js"&gt;&lt;/script&gt; &lt;dom-module id="x-foo"&gt; &lt;template&gt; &lt;style&gt;&lt;/style&gt; HELLO WORLD &lt;/template&gt; &lt;script&gt; (function() { 'use strict'; Polymer({ is: 'x-foo', }); })(); &lt;/script&gt; &lt;/dom-module&gt; </code></pre>
<p>You'll notice the browser console displays:</p> <blockquote> <p><a href="https://polygit.org/polymer/components/polymer/polymer.html" rel="nofollow">https://polygit.org/polymer/components/polymer/polymer.html</a> Failed to load resource: the server responded with a status of 400 ()</p> <p><a href="https://polygit.org/polymer/components/webcomponentsjs/webcomponents-lite.min.js" rel="nofollow">https://polygit.org/polymer/components/webcomponentsjs/webcomponents-lite.min.js</a> Failed to load resource: the server responded with a status of 400 ()</p> <p>x-foo.html:14 Uncaught ReferenceError: Polymer is not defined</p> </blockquote> <p>The browser cannot find the required imports for Polymer because your <code>&lt;base&gt;</code> URL has a malformed polygit configuration in <code>x-foo.html</code>:</p> <pre><code>&lt;base href="https://polygit.org/polymer/components/"&gt; </code></pre> <p>Expected <a href="https://polygit.org/" rel="nofollow">URL format</a> for <code>polygit.org</code>:</p> <pre><code>&lt;server-name&gt;/[&lt;configurations&gt;/]components/&lt;component&gt;/&lt;path&gt; </code></pre> <p>where <code>&lt;configurations&gt;/</code> is:</p> <pre><code>&lt;component&gt;[+&lt;org&gt;]+&lt;ver&gt;|:&lt;branch&gt;|* </code></pre> <p>So your <code>&lt;base&gt;</code> URL should be any of the following:</p> <pre><code>&lt;base href="https://polygit.org/components/"&gt; &lt;base href="https://polygit.org/polymer+:master/components/"&gt; &lt;base href="https://polygit.org/polymer+v1.7.0/components/"&gt; </code></pre> <p><a href="https://plnkr.co/edit/FHBpjdHmytYuKsDS9NnB?p=preview" rel="nofollow">plunker</a></p>
How further we can access a php get variable? <p>I have a page where i show the each person's brief record and there is link for details of each person which takes to another page if someone wants to edit record there is option on that page but making another get variable in not working. </p> <pre><code>&lt;form action="std_edit.php?edit_id=&lt;?php echo $std_id; ?&gt;"&gt; &lt;input class="std_edit" type="submit" name="edit" value = "Edit"&gt; &lt;/form&gt; </code></pre> <p>i echoed the previous get variable and its printing fine. how can i make it work fine for me?</p>
<p>First thing you can "GET" a variable as long as you can see that in the URL. e.g: exmaple.com?std_id=Boo</p> <p>In code you do something:</p> <pre><code>$std_id = $_GET['std_id']; //$std_id will be Boo &lt;form action="std_edit.php?edit_id=&lt;?php echo $std_id; ?&gt;"&gt; &lt;input class="std_edit" type="submit" name="edit" value = "Edit"&gt; &lt;/form&gt; </code></pre> <p>If you want some variable it has to be there in URL. Taking sample example above, you cannot do something like:</p> <pre><code>$std_id = $_GET['id']; </code></pre> <p>Reason, id is not there in URL.</p>
Google Analytics and Second Dimensions <p><a href="https://i.stack.imgur.com/FomoZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/FomoZ.png" alt="enter image description here"></a></p> <p>I get codes from a referral url that I place into a custom dimension when calling Universal Google Analytics which works with everything like Geo etc, but doesn't work with demographic data like <strong>Age</strong> in Analytics. Does anyone know how to make that work?</p> <p>Working example:</p> <p><a href="https://i.stack.imgur.com/RIxfW.png" rel="nofollow"><img src="https://i.stack.imgur.com/RIxfW.png" alt="enter image description here"></a></p>
<p>My guess is that the scope of your dimension and age does not match since age is a user level metrics it only allows user level custom dimension with it.</p> <p>Hope this helps,</p> <p>Cheers Analytics ML</p>
how to combine combine footer_callback with multi_filter in datatables <p>I am trying to combine <a href="https://datatables.net/examples/advanced_init/footer_callback.html" rel="nofollow">footer_callback</a> with <a href="https://datatables.net/examples/api/multi_filter.html" rel="nofollow">multi_filter</a></p> <p>this is my fiddle <a href="https://jsfiddle.net/HattrickNZ/7bh7w2tu/2/" rel="nofollow">attempt</a> but I cannot get the footer_callback code to work. I am not sure if I need to do major changes. </p> <p>I have 2 footers, 1 I use for the search per column(multi_filter) and the 2nd I use for the sumation of a colum(footer_callback). I have slightly modified the code for the multi_filter to work (html and js). I am just not sure what to do for the footer_call_back to work. <strong>Can anyone advise how I can get the footer_callback code to work(currenly commented out)?</strong></p> <p><strong>html code for footer_call_back:</strong></p> <pre><code>&lt;tfoot&gt; &lt;tr&gt; &lt;th colspan="4" style="text-align:right"&gt;Total:&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/tfoot&gt; </code></pre> <p><strong>js code for footer_callback:</strong></p> <pre><code>"footerCallback": function ( row, data, start, end, display ) { var api = this.api(), data; // Remove the formatting to get integer data for summation var intVal = function ( i ) { return typeof i === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof i === 'number' ? i : 0; }; // Total over all pages total = api .column( 4 ) .data() .reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 ); // Total over this page pageTotal = api .column( 4, { page: 'current'} ) .data() .reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 ); // Update footer $( api.column( 4 ).footer() ).html( '$'+pageTotal +' ( $'+ total +' total)' ); } </code></pre> <p><strong>html code for multi_filter:</strong></p> <pre><code> &lt;tfoot id="search"&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Position&lt;/th&gt; &lt;th&gt;Office&lt;/th&gt; &lt;th&gt;Age&lt;/th&gt; &lt;th&gt;Start date&lt;/th&gt; &lt;th&gt;Salary&lt;/th&gt; &lt;/tr&gt; &lt;/tfoot&gt; </code></pre> <p><strong>jscoder for multifilter:</strong></p> <pre><code>// Setup - add a text input to each footer cell $('#example tfoot#search th').each(function() { var title = $(this).text(); $(this).html('&lt;input type="text" placeholder="Search ' + title + '" /&gt;'); }); // DataTable var table = $('#example').DataTable(); // Apply the search table.columns().every(function() { var that = this; $('input', this.footer()).on('keyup change', function() { if (that.search() !== this.value) { that .search(this.value) .draw(); } }); </code></pre> <hr> <h2>EDIT1</h2> <p>That does not work or that fixes the <code>footer_callback</code> but breaks the <code>multi_filter</code></p> <p>I have tidied up the so the columns line up here <a href="https://jsfiddle.net/HattrickNZ/7bh7w2tu/5/" rel="nofollow">FIDDLE</a>:</p> <p>and then done the changes recommended here <a href="https://jsfiddle.net/HattrickNZ/7bh7w2tu/6/" rel="nofollow">FIDDLE</a> which looks like this: </p> <pre><code>$(document).ready(function() { $('#example').DataTable( { // footer_callback code goes here... } ); // end $('#example').DataTable( { //multi_filter code goes here... } ); </code></pre> <p>and that gets the <code>footer_callback</code> to work but then the <code>multi_filter</code> does not work. Anyway I can get both of them to work together?</p>
<p>You need put this <code>footerCallback</code> in data table initialization function.like this</p> <pre><code>$('#example').DataTable( { "footerCallback": function ( row, data, start, end, display ) { var api = this.api(), data; // Remove the formatting to get integer data for summation var intVal = function ( i ) { return typeof i === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof i === 'number' ? i : 0; }; // Total over all pages total = api .column( 4 ) .data() .reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 ); // Total over this page pageTotal = api .column( 4, { page: 'current'} ) .data() .reduce( function (a, b) { return intVal(a) + intVal(b); }, 0 ); // Update footer $( api.column( 4 ).footer() ).html( '$'+pageTotal +' ( $'+ total +' total)' ); } }); </code></pre> <p>Working demo refer this.</p> <p><strong><a href="https://jsfiddle.net/dipakthoke07/7bh7w2tu/8/" rel="nofollow">https://jsfiddle.net/dipakthoke07/7bh7w2tu/8/</a> OR <a href="http://jsfiddle.net/dipakthoke07/s8F9V/569/" rel="nofollow">http://jsfiddle.net/dipakthoke07/s8F9V/569/</a></strong></p> <p>Thank you hope this will help you.</p>
Is it possible to disable Findbugs Sensor for specific java project with sonar-scanner <p>I have an android project and was asked to setup sonar analysis.</p> <p>There is findbugs plugin installed on the Sonarqube server and I cannot remove it as other java projects are using it.</p> <p>The problem is I don't want the findbugs analysis, but it looks like it is mandatory when I config the sonar-project.properties like this:</p> <pre><code># Language sonar.language=java sonar.profile=Android Lint </code></pre> <p><a href="https://i.stack.imgur.com/6XXZV.png" rel="nofollow"><img src="https://i.stack.imgur.com/6XXZV.png" alt="enter image description here"></a></p> <p>I tried </p> <pre><code>sonar.findbugs.skip=true sonar.findbugs.disabled=true </code></pre> <p>but no luck</p> <p>so how can I disable the findbugs sensor for this specific project?</p>
<p>FindBugs is executed here because the quality profile (rule set) you're using includes FindBugs rules. To avoid FindBugs execution, create a profile with no FindBugs rules in it, and assign your project to be analyzed with that profile. You can make the assignment in Project <strong>Administration > Quality Profiles</strong>.</p>
Javascript set dynamic hidden input depending on checkbox <p>Im confused how to set some hidden input value depending on checkbox action. Something that make me confused is my checkbox is generate from looping variable, means that I have many checkbox for 1 array variable. lets look to my html code.</p> <pre><code>{foreach myList index value} //ignore this foreach, this is just logical view &lt;input type="checkbox" name="mycheckbox[index]"&gt; mycheckbox &lt;input type="hidden" name="myhiddenval[index]" value="0"&gt; {/foreach} </code></pre> <p>I know the logic how to set that value, but Im confused how to implement that logic to javascript. The simple logic is how javascript can set the value depend on the input index, I only know javascript can set the input value by ID/Class of component. In my mind, hidden value in that index changed to 1 if checkbox in the same index is checked, and 0 if don't.</p> <p><strong>UPDATE</strong></p> <p>I have found the solution, maybe this can help the other. here we are, </p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="ui checkbox"&gt; &lt;input class="manageUsr" type="checkbox" name="manage_users[${role_index - 1}]" data-index="${role_index - 1}" #{if role?.manage_user}checked#{/if}&gt; &lt;input class="hidden_input_${role_index - 1}" type="hidden" name="manage_users_h[${role_index - 1}]" value="#{if role?.manage_user}1#{/if}#{else}0#{/else}"&gt; &lt;/div&gt; </code></pre> <p>Note : role_index is the index of looping</p> <p><strong>Javascript</strong></p> <pre><code>&lt;script type="text/javascript"&gt; $(".manageUsr").change(function() { var i = $(this).data("index"); if(this.checked) { $('.hidden_input_'+i).prop("value", 1); } else { $('.hidden_input_'+i).prop("value", 0); } }); &lt;/script&gt; </code></pre> <p>Many thank to everyone who help me..</p>
<p>You can get all <code>&lt;input&gt;</code> to an array of element with jQuery:</p> <pre><code>$('input') </code></pre> <p>Then you can change value of hidden input depends on checkbox action:</p> <pre><code>{foreach myList index value} $('input[type="checkbox"]')[i].on('change', function () { $('input[type="hidden"]')[i].prop('value', $('input')[i].val(); }) {/foreach} </code></pre>
WSO2 clustering APIM and DAS with mysql,did not show stats with this error <ol> <li><p>Clustering APIM divide into 4 part,publisher,store,keymanager, gataway. And use DAS for stats. Database is mysql.</p></li> <li><p>I set the connection between APIM and DAS on publisher node.</p></li> <li><p>When I invoke an api ,APIM console give error as below.</p></li> </ol> <blockquote> <pre><code> [2016-10-13 11:13:54,775] ERROR - APIMgtUsageHandler Cannot publish event. null java.lang.NullPointerException at org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher.publishEvent(APIMgtUsageDataBridgeDataPublisher.java:124) at org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageHandler.handleRequest(APIMgtUsageHandler.java:169) at org.apache.synapse.rest.API.process(API.java:322) at org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:86) at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:65) at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:295) at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:83) at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180) at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:317) at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:149) at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) [2016-10-13 11:13:54,807] ERROR - APIMgtResponseHandler Cannot publish response event. null java.lang.NullPointerException at org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageDataBridgeDataPublisher.publishEvent(APIMgtUsageDataBridgeDataPublisher.java:140) at org.wso2.carbon.apimgt.usage.publisher.APIMgtResponseHandler.mediate(APIMgtResponseHandler.java:211) at org.apache.synapse.mediators.ext.ClassMediator.mediate(ClassMediator.java:84) at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:81) at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:48) at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:155) at org.apache.synapse.rest.Resource.process(Resource.java:297) at org.apache.synapse.rest.API.process(API.java:335) at org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:86) at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:52) at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:295) at org.apache.synapse.core.axis2.SynapseCallbackReceiver.handleMessage(SynapseCallbackReceiver.java:529) at org.apache.synapse.core.axis2.SynapseCallbackReceiver.receive(SynapseCallbackReceiver.java:172) at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180) at org.apache.synapse.transport.passthru.ClientWorker.run(ClientWorker.java:251) at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) </code></pre> </blockquote>
<p>In order to slove this problem ,I get in touch with the dev of wso2.</p> <p>rukshan gives me <a href="http://rukspot.com/configure_wso2_apim_analytics_using_xml.html" rel="nofollow">this solution</a>,configure DAS on api-manager.xml ,not on the UI.</p>
Jumping simulation stop falling when returned to ground <p>I am trying to simulate a jump in a Rect.</p> <p>I set the KEYDOWN and KEYUP events and K_SPACE button to simulate the jump. </p> <p>My difficulty is stopping the returning fall when the rect reaches the ground (using cordX).</p> <p>I realize that will not work and comment it out in the GAME_BEGIN statement.</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_caption("shield hacking") JogoAtivo = True GAME_BEGIN = False # Speed in pixels per frame speedX = 0 speedY = 0 cordX = 10 cordY = 100 jumping=False; run=False; def draw(): screen.fill((0, 0, 0)) quadrado = pygame.draw.rect(screen, (255, 0, 0), (cordX, cordY ,50, 52)) pygame.display.flip(); while JogoAtivo: for evento in pygame.event.get(): print(evento) #verifica se o evento que veio eh para fechar a janela if evento.type == pygame.QUIT: JogoAtivo = False pygame.quit(); if evento.type == pygame.KEYDOWN: if evento.key == pygame.K_a: print('GAME BEGIN') GAME_BEGIN = True draw(); if evento.type == pygame.KEYDOWN: if evento.key == pygame.K_LEFT: speedX=-0.006 run= True; if evento.type == pygame.KEYDOWN: if evento.key == pygame.K_RIGHT: speedX=0.006 run= True; if evento.type == pygame.KEYDOWN: if evento.key == pygame.K_SPACE: speedY=-0.090 jumping= True; if evento.type == pygame.KEYUP: if evento.key == pygame.K_SPACE: speedY=+0.090 jumping= True; if GAME_BEGIN: if not jumping: gravity = cordX; """if gravity == cordY: speedY=0;""" cordX+=speedX cordY+=speedY draw() </code></pre> <blockquote> <blockquote> <blockquote> <p>UPDATED BELOW</p> </blockquote> </blockquote> </blockquote> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_caption("shield hacking") JogoAtivo = True GAME_BEGIN = False # Speed in pixels per frame speedX = 0 speedY = 0 cordX = 10 cordY = 100 groundX=0; groundY=150; jumping=False; run=False; def draw(): screen.fill((0, 0, 0)) ground = pygame.draw.rect(screen, (0, 255, 0), (groundX, groundY,400, 10)) quadrado = pygame.draw.rect(screen, (255, 0, 0), (cordX, cordY ,50, 52)) pygame.display.flip(); while JogoAtivo: for evento in pygame.event.get(): print(evento) #verifica se o evento que veio eh para fechar a janela if evento.type == pygame.QUIT: JogoAtivo = False pygame.quit(); if evento.type == pygame.KEYDOWN: if evento.key == pygame.K_a: print('GAME BEGIN') GAME_BEGIN = True draw(); if evento.key == pygame.K_LEFT: speedX=-0.006 run= True; if evento.key == pygame.K_RIGHT: speedX=0.006 run= True; if evento.key == pygame.K_SPACE: speedY=-0.090 jumping= True; if evento.type == pygame.KEYUP: if evento.key == pygame.K_SPACE: speedY=+0.090 jumping= True; if GAME_BEGIN: cordX+=speedX cordY+=speedY draw(); if cordY +50&gt;= groundY: speedY=0 jumping=False; </code></pre>
<p>Tks, i have done what you said, here is my code</p> <pre><code> import pygame pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_caption("shield hacking") JogoAtivo = True GAME_BEGIN = False # Speed in pixels per frame speedX = 0 speedY = 0 cordX = 10 cordY = 100 groundX=0; groundY=150; jumping=False; run=False; def draw(): screen.fill((0, 0, 0)) ground = pygame.draw.rect(screen, (0, 255, 0), (groundX, groundY,400, 10)) quadrado = pygame.draw.rect(screen, (255, 0, 0), (cordX, cordY ,50, 52)) pygame.display.flip(); while JogoAtivo: for evento in pygame.event.get(): print(evento) #verifica se o evento que veio eh para fechar a janela if evento.type == pygame.QUIT: JogoAtivo = False pygame.quit(); if evento.type == pygame.KEYDOWN: if evento.key == pygame.K_a: print('GAME BEGIN') GAME_BEGIN = True draw(); if evento.key == pygame.K_LEFT: speedX=-0.006 run= True; if evento.key == pygame.K_RIGHT: speedX=0.006 run= True; if evento.key == pygame.K_SPACE: speedY=-0.090 jumping= True; if evento.type == pygame.KEYUP: if evento.key == pygame.K_SPACE: speedY=+0.090 jumping= True; if GAME_BEGIN: cordX+=speedX cordY+=speedY draw(); if cordY +50&gt;= groundY: speedY=0 jumping=False; </code></pre> <blockquote> <blockquote> <blockquote> <p>Really appreciate the help.</p> </blockquote> </blockquote> </blockquote>
Play video on webpage like a pop up after clicking image <p>I need to play a video when the play button is clicked. But I need this video to play on the same page with the background faded out. The video needs to be displayed like a pop up video. I'm having problems getting the video to come up as a pop up when the image is clicked. I need it to be something like <a href="https://en.todoist.com/" rel="nofollow">this</a> when I click the watch a video. How can I go about doing this?</p> <pre><code>&lt;div class="col-md-12 f-play-video"&gt; &lt;a href="https://youtu.be/7pvci1hwAx8"&gt;&lt;img class="play-button" src="http://www.clipartbest.com/cliparts/bcy/Egx/bcyEgxxzi.png"&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p></p> <pre><code>.f-play-video{ text-align: center; margin-top: 80px; } .play-button{ width:50px; } </code></pre> <p><a href="https://jsfiddle.net/4dd4ze53/3/" rel="nofollow">https://jsfiddle.net/4dd4ze53/3/</a></p>
<p>Following @ilmk, @A.Lau and @coskikoz, I managed to get the pop up working using bootstrap modal. This is my working code. </p> <pre><code>&lt;div class="col-md-12 f-play-video" data-toggle="modal" data-target="#myModal"&gt; &lt;img src="images/play-video.svg"&gt; &lt;/div&gt; &lt;div id="myModal" class="modal fade" role="dialog"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal"&gt;&amp;times;&lt;/button&gt; &lt;h4 class="modal-title"&gt;Video&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;iframe width="100%" height="360" src="&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/7pvci1hwAx8?rel=0&amp;amp;controls=0" "frameborder="0" allowfullscreen autoplay&gt;&lt;/iframe&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-default" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
Triangle Analysis in Java <p>I want to prompt a user for 3 sides to a triangle. Then figure out whether the triangle is a right triangle, equilateral, or isosceles. But I my program just catches an error in the error handling and exits the program when trying to get <code>side(1)</code>. So my question is do you see what is causing this or what is wrong with my code?</p> <p>driver program TestTriangle.java</p> <pre><code>public class TestTriangle { public static void main(String[] args) { System.out.println("Welcome to the Triangle Program"); System.out.println(); Triangle myTriangle = new Triangle(); myTriangle.buildTriangle(); System.out.println(); System.out.println("My analysis of this triangle is"); System.out.println(); myTriangle.classifyTriangle(); String prettyPerim = String.format("%.3g", myTriangle.perimeter()); String prettyArea = String.format("%.3g", myTriangle.area()); System.out.println("\tThe area of the triangle is " + prettyArea + "."); System.out.println("\tThe perimeter of the triangle is " + prettyPerim + "."); } } </code></pre> <p>program Triangle.java</p> <pre><code>import java.util.Scanner; import java.util.InputMismatchException; public class Triangle { public static final double TOLERANCE = 0.0001; private double min; private double mid; private double max; private Scanner input; public Triangle() { double side1 = 0.0, side2 = 0.0, side3 = 0.0; } public void buildTriangle() { double side1 = getSide(1); double side2 = getSide(2); double side3 = getSide(3); // if side1 is greater than side2, the min is side1 and the max is side2 if (side1 &lt; side2) { min = side1; max = side2; // otherwise the min is side2 and the max is side1 } else { min = side2; max = side1; } // if side3 is less than the min value, then the mid value is the min value and the min value is side3 if (side3 &lt; min) { mid = min; min = side3; // if side3 is greater than the max value then the mid is the max and the max is side3 } else if (side3 &gt; max) { mid = max; max = side3; // otherwise the mid is side3 } else { mid = side3; } } public double getSide(int index) { System.out.print("Please enter the length of side " + index + ": "); double sideVal = 0.0; try{ sideVal = input.nextDouble(); } catch (Exception e) { System.out.println("You did not enter a valid input. Exiting."); System.exit(1); } return sideVal; } public void classifyTriangle() { // if the max value is greater than the min and the mid combined it is not a triangle, exit the program. if (max &gt; min + mid) { System.out.println("Not a triangle"); System.exit(1); } else if (((Math.pow(min, 2)) + (Math.pow(mid, 2))) == (Math.pow(max, 2))) { System.out.println("This is a right triangle"); } else if (max == min || min == mid || max == mid) { if (max == min &amp;&amp; min == mid &amp;&amp; max == mid) { System.out.println("This is an equilateral triangle"); } else { System.out.println("This is an isosceles triangle"); } } } public double perimeter() { // calculate the perimeter double perimeter = max + mid + min; return perimeter; } public double area() { // calculate the area double semi = (max + mid + min) / 2; double product = (semi - max) * (semi - mid) * (semi - min) * semi; double area = Math.sqrt(product); return area; } } </code></pre>
<p>you need to intialize your input</p> <pre><code> input = new Scanner(System.in); </code></pre>
How to update database field when an item has been selected from drop down menu in rails? <p>I am new in ruby on rails, I have a drop down menu bar, I want to select an item from drop down menu bar at that time, database table should to update according to the selected item. <strong>_applied_candidate.html.erb</strong> this is my partial page</p> <pre><code> &lt;p&gt;Current Status: &lt;span class="fontstyle3"&gt; &lt;% data = CandidateWorkFlow.select(:workflow_step, :next_step).where("step_id = ?", offer_state.current_step) %&gt; &lt;% data.each do | d | %&gt; &lt;%= d.workflow_step %&gt; &lt;% end %&gt; &lt;/span&gt;&lt;/p&gt; &lt;p&gt;Next Status: &lt;span class="fontstyle3"&gt; &lt;% data.each do | d | %&gt; &lt;select name="user[role_id]" id="workflow_id"&gt; &lt;option value=""&gt;Please select&lt;/option&gt; &lt;% d.next_step.split(',').each do | s | %&gt; &lt;% data1 = CandidateWorkFlow.select(:workflow_step).where("step_id = ?",s) %&gt; &lt;% data1.each do |l| %&gt; &lt;option value=&lt;% s %&gt; &gt; &lt;%= l.workflow_step %&gt; &lt;/option&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;/select&gt; &lt;% end %&gt; &lt;/span&gt; &lt;/p&gt; </code></pre> <p><code>&lt;option value=&lt;% s %&gt; &gt; &lt;%= l.workflow_step %&gt; &lt;/option&gt;</code> this part of code <code>&lt;%s%&gt;</code> will store the value of items and this one part of code <code>&lt;%=l.workflow_step %&gt;</code> is selectable list, when the item from selectable list has been selected <code>&lt;%=l.workflow_step%&gt;</code> then update method should be called. <strong>AppliedJob.rb</strong> this is my model</p> <pre><code>class AppliedJob &lt; ActiveRecord::Base end </code></pre> <p><strong>applied_jobs</strong> this is my database table <strong>| id | user_id | job_posting_id | status | applied_by_id | current_step | prev_step |</strong> these are my field <strong>JobsController.rb</strong> this is my controller</p> <pre><code>class Candidate::JobsController &lt; Candidate::BaseController end </code></pre> <p>But in this code above there is no update method</p> <p><strong>Is it possible to update database value with the help of model method?</strong> please help me </p>
<p>You can do that using forms and javascript roughly like this:</p> <pre><code> &lt;% data.each do | d | %&gt; &lt;%= form_for url: &lt;your-url&gt; do |f| %&gt; &lt;select name="user[role_id]" id="workflow_id"&gt; &lt;option value=""&gt;Please select&lt;/option&gt; &lt;% d.next_step.split(',').each do | s | %&gt; &lt;% data1 = CandidateWorkFlow.select(:workflow_step).where("step_id = ?",s) %&gt; &lt;% data1.each do |l| %&gt; &lt;option value=&lt;% s %&gt; &gt; &lt;%= l.workflow_step %&gt; &lt;/option&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;/select&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>in your javascript:</p> <pre><code> $('#workflow_id').change(function(){ $('#&lt;your-form-id&gt;').submit(); }); </code></pre> <p>Before this you should make your form and select to have corresponding ids (because this is inside a loop same id is repeated for all forms and select input)</p>
elementTree is not opening and parsing my xml file <p>seems like <code>vehicles.write(cars_file)</code> and <code>vehicles = cars_Etree.parse(cars_file)</code> are having a problem with the file name:</p> <pre><code>import argparse import xml.etree.ElementTree as cars_Etree # elementTree not reading xml file properly if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( dest='file_name', action='store', help='File name', metavar='FILE' ) parser.add_argument( 'car_make', help='car name') args = parser.parse_args() with open(args.file_name, 'r') as cars_file: vehicles = cars_Etree.parse(cars_file) cars = vehicles.getroot() for make in cars.findall(args.car_make): name = make.get('name') if name != args.car_make: cars.remove(make) with open(args.file_name, 'w') as cars_file: vehicles.write(cars_file) </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): File "/Users/benbitdiddle/PycharmProjects/VehicleFilter/FilterTest.py", line 23, in &lt;module&gt; vehicles = cars_Etree.parse(cars_file) File "/Applications/anaconda/lib/python3.5/xml/etree/ElementTree.py", line 1184, in parse tree.parse(source, parser) File "/Applications/anaconda/lib/python3.5/xml/etree/ElementTree.py", line 596, in parse self._root = parser._parse_whole(source) xml.etree.ElementTree.ParseError: syntax error: line 1, column 0 </code></pre> <p>XML file, which I am trying to filter, is in the same project folder. I tried supplying the path with the file name and it still didn't work.</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;cars&gt; &lt;make name="toyota"&gt; &lt;model name="tacoma" /&gt; &lt;model name="tundra" /&gt; &lt;/make&gt; &lt;make name="ford"&gt; &lt;model name="escort" /&gt; &lt;model name="taurus" /&gt; &lt;/make&gt; &lt;make name="chevy"&gt; &lt;model name="silverado" /&gt; &lt;model name="volt" /&gt; &lt;/make&gt; &lt;/cars&gt; </code></pre>
<p>works fine now but im still improving it. thank you </p> <p>I made this modification in main.py:</p> <pre><code>path = "/Users/benbitdiddle/PycharmProjects/VehicleFilter/" CF = CarFilter(path+args.file_name, args.car_make) CF.filterCar() </code></pre> <p>And changed 'w' to wb' in CarFilter.py class file:</p> <pre><code> with open(self.file_name, 'wb') as car_file: self.vehicles.write(car_file) </code></pre>
malloc and pointer code demonstration <p>I don't have enough knowledge about pointer and malloc! I tried to read books but did't got it clearly and I can't understood these lines of code:</p> <pre><code>L = (int*)malloc(mid*sizeof(int)); R = (int*)malloc((n- mid)*sizeof(int)); </code></pre> <p>What value actually <code>L</code> and <code>R</code> having? </p> <pre><code>for(i = 0;i&lt;mid;i++) L[i] = A[i]; for(i = mid;i&lt;n;i++) R[i-mid] = A[i]; </code></pre> <p>and in for loop I see L and R having index no? I'm confused How come <code>L and R acting as array</code>. </p> <p>Full Code:</p> <pre><code>void MergeSort(int *A,int n) { int mid,i, *L, *R; if(n &lt; 2) return; // base condition. If the array has less than two element, do nothing. mid = n/2; // find the mid index. // create left and right subarrays // mid elements (from index 0 till mid-1) should be part of left sub-array // and (n-mid) elements (from mid to n-1) will be part of right sub-array L = (int*)malloc(mid*sizeof(int)); R = (int*)malloc((n- mid)*sizeof(int)); for(i = 0;i&lt;mid;i++) L[i] = A[i]; // creating left subarray for(i = mid;i&lt;n;i++) R[i-mid] = A[i]; // creating right subarray MergeSort(L,mid); // sorting the left subarray MergeSort(R,n-mid); // sorting the right subarray Merge(A,L,mid,R,n-mid); // Merging L and R into A as sorted list. free(L); free(R); } </code></pre>
<p>A pointer is really just the address of a memory location.</p> <p>The value of a pointer variable is the address the pointer is pointing to.</p> <p><a href="http://en.cppreference.com/w/c/memory/malloc" rel="nofollow">The <code>malloc</code> function</a> allocates a chunk of bytes somewhere in memory (where that memory is located is irrelevant). It returns a pointer to the first byte of that memory.</p> <hr> <p>A little more visually a pointer and what it points to could be seen as this:</p> <pre> +---------+ +------------+ | pointer | ---> | Memory ... | +---------+ +------------+ </pre> <p>You could also see the memory returned by <code>malloc</code> as an array. Taking parts of the code from your example, if <code>mid</code> is <code>5</code> then you have something like this:</p> <pre> +---+ +------+------+------+------+------+------+ | L | ---> [ L[0] | L[1] | L[2] | L[3] | L[4] | .... | +---+ +------+------+------+------+------+------+ </pre> <p>That is, the variable <code>L</code> points to the first element (<code>L[0]</code>) in the allocated "array".</p> <p>Do note that there is really no end to the "array" allocated by <code>malloc</code>. C doesn't have any bounds checking, and the compiler will not give you any error or warning for using an index that is out of bounds (for example <code>L[5]</code> using out example above). It will lead to <em>undefined behavior</em> and possibly crashes or weird behavior, but you can still access or even write to that element.</p> <p>Also note that taking the size of a pointer with the <code>sizeof</code> operator will not return the size of the memory it points to, but the size of the pointer itself. For example doing <code>sizeof L</code> will not return <code>mid</code> or <code>mid * sizeof(int)</code>. It will return the size of the pointer variable <code>L</code>, which is typically <code>4</code> or <code>8</code> depending on if you're on a 32 or 64 bit system.</p>
Ionic Datepicker and Timepicker <p>I am trying to build datepicker and timepicker components in my Ionic app for android.</p> <p>I have looked for various libs and plugins, but I was not able to find what I wanted -- iOS style date and time picker which user can scroll to go through dates and times like image below.</p> <p><a href="https://i.stack.imgur.com/vZgfX.png" rel="nofollow"><img src="https://i.stack.imgur.com/vZgfX.png" alt="enter image description here"></a></p> <p>Any advice and suggestion would be appreciated. Thank you in advance.</p>
<p>In Android it is called WheelPicker,I suggest you to use </p> <p><a href="https://github.com/AigeStudio/WheelPicker" rel="nofollow">WheelPicker</a></p> <pre><code>compile 'cn.aigestudio.wheelpicker:WheelPicker:1.1.2' </code></pre> <p><strong>OUTPUT</strong></p> <p><a href="https://i.stack.imgur.com/QYKhj.gif" rel="nofollow"><img src="https://i.stack.imgur.com/QYKhj.gif" alt="enter image description here"></a></p> <p><strong>OR</strong></p> <p>You can use <a href="https://github.com/ImKarl/CharacterPickerView" rel="nofollow">CharacterPicker</a></p> <pre><code>CharacterPickerWindow mOptions = new CharacterPickerWindow(activity); setPickerData(mOptions.getPickerView()); mOptions.setSelectOptions(0, 0, 0); mOptions.setOnoptionsSelectListener(new OnOptionChangedListener() { @Override public void onOptionChanged(int options1, int option2, int options3) { } }); mOptions.showAtLocation(v, Gravity.BOTTOM, 0, 0); </code></pre>
Problems adding a border to the side of a view in iOS <p>I'm having a problem adding a border to the bottom side of a view. When I build the project it's all fine. But when I run it, the lldb warning appears and the app stops at the delegate class and it won't show. Why is this happening?</p> <p>My view that I want to add the border to:</p> <pre><code>fileprivate func setContainerViews()-&gt; Void{ //First Container let container : UIView = UIView() container.backgroundColor = UIColor.init(netHex: 0xE8ECEF) container.translatesAutoresizingMaskIntoConstraints = false view.addSubview(container) container.topAnchor.constraint(equalTo: view.topAnchor,constant: UIApplication.shared.statusBarFrame.size.height).isActive = true container.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true container.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.40).isActive = true container.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true self.container = container //how I'm calling the function and adding it to the view /*let optionView = drawBottomLine(optionView: container) self.container?.addSubview(optionView) */ } </code></pre> <p>My border adding class:</p> <pre><code>func drawBottomLine(optionView:UIView)-&gt;UIView{ let bottomBorder = CALayer() bottomBorder.frame = CGRect(0.0, optionView.frame.height-1, optionView.frame.width, 0.7) bottomBorder.backgroundColor = UIColor.honePalette.accent.cgColor optionView.layer.addSublayer(bottomBorder) return optionView; } </code></pre>
<p>You are trying to add <code>container</code> as a subview of itself.</p> <p>In this line, you are sending in container</p> <pre><code>let optionView = drawBottomLine(optionView: container) </code></pre> <p>in the function, you add a sublayer to the container and return the container again. Thus optionView equals container</p> <p>Then in this line, you are trying to add the container to itself</p> <pre><code>self.container?.addSubview(optionView) </code></pre> <p>Thus, <strong>remove <code>self.container?.addSubview(optionView)</code></strong>, but also <strong>add <code>view.layoutIfNeeded()</code></strong> before you call drawBottomLine. That way you ensure the layout has been applied, and the frames that drawBottomLine use to calculate where the border should be is correct.</p>
radio group not working and vertical alignment android <pre><code>JSONArray jsonQuestion = new JSONArray(obj.get("question").toString()); for (int iii = 0; iii &lt; jsonQuestion.length(); iii++) { LinearLayout lll = new LinearLayout(Questionnaire.this); lll.setOrientation(LinearLayout.VERTICAL); JSONObject obj2 = (JSONObject) jsonQuestion.get(iii); System.out.println(obj2.get("question")); TextView tv = new TextView(Questionnaire.this); tv.setText(obj2.get("question").toString()); lll.addView(tv); JSONArray jsonAnswer = new JSONArray(obj.get("answer").toString()); Log.d("Reading Answer: ", jsonAnswer + ""); for (int iiii = 0; iiii &lt; jsonAnswer.length(); iiii++) { JSONObject obj3 = (JSONObject) jsonAnswer.get(iiii); System.out.println(obj2.get("questiosysid").toString().matches(obj3.get("questionid").toString())); if (obj2.get("questiosysid").toString().matches(obj3.get("questionid").toString())) { TextView tv1 = new TextView(Questionnaire.this); tv1.setText(obj3.get("inputname").toString()); RadioGroup group = new RadioGroup(Questionnaire.this); group.setOrientation(RadioGroup.HORIZONTAL); // RadioGroup.HORIZONTAL or RadioGroup.VERTICAL if (obj3.get("inputtype").toString().matches("radio")) { RadioButton newRadioButton = new RadioButton(Questionnaire.this); newRadioButton.setId(Integer.parseInt(obj3.get("answerid").toString())); newRadioButton.setText(obj3.get("inputname").toString()); group.addView(newRadioButton); lll.addView(group); } } } ll.addView(lll); } </code></pre> <p>This is my code for dynamically adding radio button.</p> <p>Problem is when I select one option then select anther it does not deselect the previous one. <strong>Why doesn't it deselect the the first one selecting another</strong> when they are both added to same radio group. Also it is not placing the radio buttons next to each other but on top of each other when the <strong>orientation is set to horizontal</strong></p> <p><strong>UPDATE</strong></p> <p>I moved my declaration of</p> <pre><code>RadioGroup group = new RadioGroup(Questionnaire.this); group.setOrientation(RadioGroup.HORIZONTAL); // RadioGroup.HORIZONTAL or RadioGroup.VERTICAL </code></pre> <p>out side parent for loop now i am getting</p> <blockquote> <p>java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. </p> </blockquote> <p>How should i deal with it? </p>
<p>you are added only one <code>RadioButton</code> in <code>RadioGroup</code> that's why you got many selected radio button. <code>RadioGroup</code> need minimum 2 <code>RadioButton</code> for check or Uncheck effect.</p> <p>try this,I hope it may work. </p> <pre><code>JSONArray jsonQuestion = new JSONArray(obj.get("question").toString()); for (int iii = 0; iii &lt; jsonQuestion.length(); iii++) { LinearLayout lll = new LinearLayout(Questionnaire.this); lll.setOrientation(LinearLayout.VERTICAL); JSONObject obj2 = (JSONObject) jsonQuestion.get(iii); System.out.println(obj2.get("question")); TextView tv = new TextView(Questionnaire.this); tv.setText(obj2.get("question").toString()); lll.addView(tv); JSONArray jsonAnswer = new JSONArray(obj.get("answer").toString()); Log.d("Reading Answer: ", jsonAnswer + ""); RadioGroup group = new RadioGroup(Questionnaire.this); group.setOrientation(RadioGroup.HORIZONTAL); // RadioGroup.HORIZONTAL or RadioGroup.VERTICAL for (int iiii = 0; iiii &lt; jsonAnswer.length(); iiii++) { JSONObject obj3 = (JSONObject) jsonAnswer.get(iiii); System.out.println(obj2.get("questiosysid").toString().matches(obj3.get("questionid").toString())); if (obj2.get("questiosysid").toString().matches(obj3.get("questionid").toString())) { TextView tv1 = new TextView(Questionnaire.this); tv1.setText(obj3.get("inputname").toString()); if (obj3.get("inputtype").toString().matches("radio")) { RadioButton newRadioButton = new RadioButton(Questionnaire.this); newRadioButton.setId(Integer.parseInt(obj3.get("answerid").toString())); newRadioButton.setText(obj3.get("inputname").toString()); group.addView(newRadioButton); } } } lll.addView(group); ll.addView(lll); } </code></pre>
Get pattern of SimpleDateFormat <p>I have a combo box with list of the current date with a different format. When the user selected the format, the current date with the selected format will be display. I need to save the selected pattern of the date in a file. I look everywhere and I can't find a specific answer for my problem. Is there a way to get the specific pattern of a date in java?</p>
<p>From the <a href="https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html#toPattern()" rel="nofollow">docs</a>:</p> <pre><code>public String toPattern() Returns a pattern string describing this date format. </code></pre>
trouble running all thread group within test plan during Jmeter's remote testing <p>i am having trouble with remote testing in jmeter.</p> <p>my server is able to ask the client to start the test plan.</p> <p>However, only the first active thread group is running, the rest of the active thread group did not run at all.</p> <p>is there anything that i might have missed??</p> <p>I did not tick "Run thread group consecutively"</p>
<p>thanks for the help, but i solved it myself. my CSV Dataset is a invalid location, making the rest of the thread group to not run at all.</p>
Chrome animation makes text blurry <p>Everything works good on Firefox but chrome shows the animated text blurry. I did everything like <code>-webkit-font-smoothing: subpixel-antialiased;</code> , <code>-webkit-transform: translate3d(0,0,0);</code> and everything mentioned here before:</p> <p><a href="http://stackoverflow.com/questions/6411361/webkit-based-blurry-distorted-text-post-animation-via-translate3d">Webkit-based blurry/distorted text post-animation via translate3d</a></p> <p>but the problem is still exists.</p> <p>I made very simple example to show you how it looks like. How can I fix this problem?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var text = 1; function next() { var next = (text == 2) ? 1 : 2; document.getElementById('text' + text).className = 'out'; document.getElementById('text' + next).className = 'in'; text = next; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { padding: 0; margin: 0; font-family: tahoma; font-size: 8pt; color: black; } div { height: 30px; width: 100%; position: relative; overflow: hidden; margin-bottom: 10px; } div div { opacity: 0; position: absolute; top: 0; bottom: 0; right: 0; left: 0; } .in { -webkit-animation: comein 1s 1; -moz-animation: comein 1s 1; animation: comein 1s 1; animation-fill-mode: both; } @keyframes comein { 0% { opacity: 0; } 100% { opacity: 1; } } .out { -webkit-animation: goout 1s 1; -moz-animation: goout 1s 1; animation: goout 1s 1; animation-fill-mode: both; } @keyframes goout { 0% { opacity: 1; } 100% { opacity: 0; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;div class="in" id="text1"&gt;Hello! I'm Test Text. I'm Test Text jr Father!&lt;/div&gt; &lt;div id="text2"&gt;Hi, I'm test text jr. I'm sharp and beautiful by nature but when I came in, Chrome made me blurry and I'm bad, I'm bad! ... Who's bad :)&lt;/div&gt; &lt;/div&gt; &lt;button onclick="next();"&gt;Next&lt;/button&gt;</code></pre> </div> </div> </p> <p><strong>You can also see this example at</strong> <a href="http://codepen.io/anon/pen/kkpJaL" rel="nofollow">CodePen</a></p>
<p>This has been a known bug for at least a year now: <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=521364#c36" rel="nofollow">https://bugs.chromium.org/p/chromium/issues/detail?id=521364#c36</a></p> <p>Status is promising from one of the devs working on it though:</p> <blockquote> <p>The problem was due to we raster things in an element's local space. If the element has a fractional translation, then the rasterized texture would be pasted onto the screen with the fractional translation using linear resampling, resulting in the blur.</p> <p>The solution is to raster things in a space that is pixel-aligned to our physical screen. i.e. applying the fractional translation to the vector graphics commands instead of rastered texture.</p> <p>The fix will be coming in two parts: </p> <ol> <li><p>The first part that allows our raster system to raster with any general matrix. This part is almost done. I have a WIP but it still has a bug that causes performance regression. I expect to finish it within a few days. <a href="https://codereview.chromium.org/2075873002/" rel="nofollow">https://codereview.chromium.org/2075873002/</a></p></li> <li><p>The second part that allows our tiling management to be able to manage set of textures that comes with different raster translation. I was originally going for general matrix but turns out the tile coverage computation becomes very difficult. I will instead do a simpler version that only supports translation and scale. I estimate this will need another week of work.</p></li> </ol> </blockquote>
xuggler maven dependency pom.xml file error <p>when i try to use xuggler maven dependencies in my java maven project getting error "Missing artifact xuggle:xuggle-xuggler:jar:5.2 " mentioned the pom.xml file please look at once</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.ensis.mediguru&lt;/groupId&gt; &lt;artifactId&gt;eDoctor&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;eDoctor&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;properties&gt; &lt;spring.version&gt;4.3.2.RELEASE&lt;/spring.version&gt; &lt;servlet.api.version&gt;3.1.0&lt;/servlet.api.version&gt; &lt;log4j.version&gt;1.2.17&lt;/log4j.version&gt; &lt;fasterxml.jackson.core.version&gt;2.5.3&lt;/fasterxml.jackson.core.version&gt; &lt;codehaus.jackson.version&gt;1.9.13&lt;/codehaus.jackson.version&gt; &lt;hibernate.version&gt;4.3.5.Final&lt;/hibernate.version&gt; &lt;mysql.version&gt;5.1.10&lt;/mysql.version&gt; &lt;!-- -&lt;xuggler.version&gt;0.16&lt;/xuggler.version&gt;--&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-web-api&lt;/artifactId&gt; &lt;version&gt;6.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- Spring Farmework --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-web&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-aop&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context-support&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-orm&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-tx&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Servlet --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt; &lt;version&gt;${servlet.api.version}&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-fileupload&lt;/groupId&gt; &lt;artifactId&gt;commons-fileupload&lt;/artifactId&gt; &lt;version&gt;1.3.1&lt;/version&gt; &lt;!-- makesure correct version here --&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.mail&lt;/groupId&gt; &lt;artifactId&gt;mail&lt;/artifactId&gt; &lt;version&gt;1.4.7&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Jackson --&gt; &lt;dependency&gt; &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt; &lt;artifactId&gt;jackson-mapper-asl&lt;/artifactId&gt; &lt;version&gt;${codehaus.jackson.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt; &lt;artifactId&gt;jackson-core-asl&lt;/artifactId&gt; &lt;version&gt;${codehaus.jackson.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt; &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt; &lt;version&gt;2.2.12&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.xml&lt;/groupId&gt; &lt;artifactId&gt;jaxb-impl&lt;/artifactId&gt; &lt;version&gt;2.1&lt;/version&gt; &lt;/dependency&gt; &lt;!-- xuggler for generating thumbnail --&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt; &lt;version&gt;1.6.4&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-cli&lt;/groupId&gt; &lt;artifactId&gt;commons-cli&lt;/artifactId&gt; &lt;version&gt;1.1&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt; &lt;artifactId&gt;logback-core&lt;/artifactId&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt; &lt;artifactId&gt;logback-classic&lt;/artifactId&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;xuggle&lt;/groupId&gt; &lt;artifactId&gt;xuggle-xuggler&lt;/artifactId&gt; &lt;version&gt;5.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Jackson --&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-core&lt;/artifactId&gt; &lt;version&gt;${fasterxml.jackson.core.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt; &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt; &lt;version&gt;${fasterxml.jackson.core.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Loggers --&gt; &lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;${log4j.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- @Inject --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.inject&lt;/groupId&gt; &lt;artifactId&gt;javax.inject&lt;/artifactId&gt; &lt;version&gt;1&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Hibernate --&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;${hibernate.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt; &lt;version&gt;${hibernate.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Apache Commons DBCP --&gt; &lt;dependency&gt; &lt;groupId&gt;commons-dbcp&lt;/groupId&gt; &lt;artifactId&gt;commons-dbcp&lt;/artifactId&gt; &lt;version&gt;1.4&lt;/version&gt; &lt;/dependency&gt; &lt;!--MYSQL Connector --&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;${mysql.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.commons&lt;/groupId&gt; &lt;artifactId&gt;commons-io&lt;/artifactId&gt; &lt;version&gt;1.3.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt; &lt;artifactId&gt;jersey-bundle&lt;/artifactId&gt; &lt;version&gt;1.13-b01&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;eDoctor&lt;/finalName&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.1.1&lt;/version&gt; &lt;configuration&gt; &lt;packagingExcludes&gt;WEB-INF/web.xml&lt;/packagingExcludes&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p></p> <p>can nay one tell how to resolve this?</p>
<p>you are very unlikely to find xuggler jar in public repositories. xuggler is dying out, means any active development is stopped. Better chance is to find any one who has build the xuggler matching your architecture x32 or x64 and then manually install to your local maven repository</p> <p>something like</p> <pre><code> mvn install:install-file -Dfile=c:\xuggle-xuggler-noarch-{version}.jar -DgroupId=xuggle -DartifactId=xuggle-xuggler-noarch -Dversion={version} -Dpackaging=jar </code></pre> <p>here is a one <a href="http://www.java2s.com/Code/Jar/x/Downloadxugglexugglernoarch54jar.htm" rel="nofollow">http://www.java2s.com/Code/Jar/x/Downloadxugglexugglernoarch54jar.htm</a></p>
App rejected for in-app purchase in Apple Review <p>I had app in App store in which I have in-app purchase to unlock some features. But in the current versions of the I thought of removing all the in-app purchase within the app and give all features for free.</p> <p>But Apple has reject my app for the following reason : </p> <blockquote> <p>From Apple</p> <p>4.0 BEFORE YOU SUBMIT: INFO NEEDED</p> <p>Information Needed</p> <p>We have begun the review of your app but aren't able to continue because we can't locate the In-App Purchase(s) within your app.</p> <p>At your earliest opportunity, please reply to this message providing the steps for locating the In-App Purchase(s) in your app.</p> </blockquote> <p>Please let me whether should I inform apple review team about this in review notes or should I remove all in-app purchase from sale. </p> <p>I fear removing in-app purchase from will affect the existing user using older version of the app.</p> <p>Any help is appreciated.</p>
<p>You can submit the app by adding an explanation in review notes section. This will accepted by Apple. Also your app will get approved.</p>
How to check grid checkbox ondouble click? <p>i want to check the checkbox on Grid only in double click and i don't want to check or uncheck on single click.</p> <p>Thanks in advance</p>
<p><code>CellContentDoubleClick</code> would do what you want. but you have to set your checkbox <code>ReadOnly</code> property <strong>true</strong> by default. i tested this event and works fine for me. let me know if this helps you:</p> <p><code>CellContentDoubleClick</code> event:</p> <pre><code>private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { if (dataGridView1.CurrentCell.ColumnIndex.Equals(1) &amp;&amp; e.RowIndex != -1) { if (dataGridView1.CurrentCell != null) dataGridView1.CurrentCell.ReadOnly = false; if (dataGridView1.CurrentCell.Value != null) dataGridView1.CurrentCell.Value = Convert.ToInt32(dataGridView1.CurrentCell.Value) &gt; 0 ? 0 : 1; } dataGridView1.CurrentCell.ReadOnly = true; } </code></pre> <p>and here is my GridView desing:</p> <p><a href="https://i.stack.imgur.com/tM0U5.png" rel="nofollow"><img src="https://i.stack.imgur.com/tM0U5.png" alt="enter image description here"></a></p>
How to fix cannot convert argument 1 from `int to `PUCHAR`? <p>I'm having trouble with MFC when performing the BULK OUT it says that XferData is invalid</p> <p><strong>Error</strong> <a href="https://i.stack.imgur.com/nYEdY.png" rel="nofollow"><img src="https://i.stack.imgur.com/nYEdY.png" alt="enter image description here"></a></p> <p><strong>HEADER FILE is <em>CyAPI.H</em></strong></p> <pre><code>//______________________________________________________________________________ // // Copyright (c) Cypress Semiconductor, 2011 // All rights reserved. // //______________________________________________________________________________ #ifndef CyUSBH #define CyUSBH #ifndef __USB200_H__ #define __USB200_H__ #pragma pack(push,1) typedef struct _USB_DEVICE_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; USHORT bcdUSB; UCHAR bDeviceClass; UCHAR bDeviceSubClass; UCHAR bDeviceProtocol; UCHAR bMaxPacketSize0; USHORT idVendor; USHORT idProduct; USHORT bcdDevice; UCHAR iManufacturer; UCHAR iProduct; UCHAR iSerialNumber; UCHAR bNumConfigurations; } USB_DEVICE_DESCRIPTOR, *PUSB_DEVICE_DESCRIPTOR; typedef struct _USB_ENDPOINT_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; UCHAR bEndpointAddress; UCHAR bmAttributes; USHORT wMaxPacketSize; UCHAR bInterval; } USB_ENDPOINT_DESCRIPTOR, *PUSB_ENDPOINT_DESCRIPTOR; typedef struct _USB_CONFIGURATION_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; USHORT wTotalLength; UCHAR bNumInterfaces; UCHAR bConfigurationValue; UCHAR iConfiguration; UCHAR bmAttributes; UCHAR MaxPower; } USB_CONFIGURATION_DESCRIPTOR, *PUSB_CONFIGURATION_DESCRIPTOR; typedef struct _USB_INTERFACE_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; UCHAR bInterfaceNumber; UCHAR bAlternateSetting; UCHAR bNumEndpoints; UCHAR bInterfaceClass; UCHAR bInterfaceSubClass; UCHAR bInterfaceProtocol; UCHAR iInterface; } USB_INTERFACE_DESCRIPTOR, *PUSB_INTERFACE_DESCRIPTOR; typedef struct _USB_STRING_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; WCHAR bString[1]; } USB_STRING_DESCRIPTOR, *PUSB_STRING_DESCRIPTOR; typedef struct _USB_COMMON_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; } USB_COMMON_DESCRIPTOR, *PUSB_COMMON_DESCRIPTOR; #pragma pack(pop) #endif //______________________________________________________________________________ class CCyIsoPktInfo { public: LONG Status; LONG Length; }; //______________________________________________________________________________ // {AE18AA60-7F6A-11d4-97DD-00010229B959} static GUID CYUSBDRV_GUID = {0xae18aa60, 0x7f6a, 0x11d4, 0x97, 0xdd, 0x0, 0x1, 0x2, 0x29, 0xb9, 0x59}; typedef enum {TGT_DEVICE, TGT_INTFC, TGT_ENDPT, TGT_OTHER } CTL_XFER_TGT_TYPE; typedef enum {REQ_STD, REQ_CLASS, REQ_VENDOR } CTL_XFER_REQ_TYPE; typedef enum {DIR_TO_DEVICE, DIR_FROM_DEVICE } CTL_XFER_DIR_TYPE; typedef enum {XMODE_BUFFERED, XMODE_DIRECT } XFER_MODE_TYPE; const int MAX_ENDPTS = 16; const int MAX_INTERFACES = 8; const int USB_STRING_MAXLEN = 256; //////////////////////////////////////////////////////////////////////////////// // // The CCyEndPoint ABSTRACT Class // //////////////////////////////////////////////////////////////////////////////// class CCyUSBEndPoint { protected: bool WaitForIO(OVERLAPPED *ovLapStatus); virtual PUCHAR BeginDirectXfer(PUCHAR buf, LONG bufLen, OVERLAPPED *ov); virtual PUCHAR BeginBufferedXfer(PUCHAR buf, LONG bufLen, OVERLAPPED *ov); public: CCyUSBEndPoint(void); CCyUSBEndPoint(CCyUSBEndPoint&amp; ept); CCyUSBEndPoint(HANDLE h, PUSB_ENDPOINT_DESCRIPTOR pEndPtDescriptor); HANDLE hDevice; // The fields of an EndPoint Descriptor UCHAR DscLen; UCHAR DscType; UCHAR Address; UCHAR Attributes; USHORT MaxPktSize; USHORT PktsPerFrame; UCHAR Interval; // Other fields ULONG TimeOut; ULONG UsbdStatus; ULONG NtStatus; DWORD bytesWritten; DWORD LastError; bool bIn; XFER_MODE_TYPE XferMode; bool XferData(PUCHAR buf, LONG &amp;len, CCyIsoPktInfo* pktInfos = NULL); bool XferData(PUCHAR buf, LONG &amp;bufLen, CCyIsoPktInfo* pktInfos, bool pktMode); virtual PUCHAR BeginDataXfer(PUCHAR buf, LONG len, OVERLAPPED *ov) = 0; virtual bool FinishDataXfer(PUCHAR buf, LONG &amp;len, OVERLAPPED *ov, PUCHAR pXmitBuf, CCyIsoPktInfo* pktInfos = NULL); bool WaitForXfer(OVERLAPPED *ov, ULONG tOut); ULONG GetXferSize(void); void SetXferSize(ULONG xfer); bool Reset(void); bool Abort(void); private: }; //////////////////////////////////////////////////////////////////////////////// // // The Control Endpoint Class // //////////////////////////////////////////////////////////////////////////////// class CCyControlEndPoint : public CCyUSBEndPoint { private: public: CCyControlEndPoint(void); CCyControlEndPoint(CCyControlEndPoint&amp; ept); CCyControlEndPoint(HANDLE h, PUSB_ENDPOINT_DESCRIPTOR pEndPtDescriptor); CTL_XFER_TGT_TYPE Target; CTL_XFER_REQ_TYPE ReqType; CTL_XFER_DIR_TYPE Direction; UCHAR ReqCode; WORD Value; WORD Index; bool Read(PUCHAR buf, LONG &amp;len); bool Write(PUCHAR buf, LONG &amp;len); PUCHAR BeginDataXfer(PUCHAR buf, LONG len, OVERLAPPED *ov); }; //////////////////////////////////////////////////////////////////////////////// // // The Isoc Endpoint Class // //////////////////////////////////////////////////////////////////////////////// class CCyIsocEndPoint : public CCyUSBEndPoint { protected: virtual PUCHAR BeginDirectXfer(PUCHAR buf, LONG bufLen, OVERLAPPED *ov); virtual PUCHAR BeginBufferedXfer(PUCHAR buf, LONG bufLen, OVERLAPPED *ov); public: CCyIsocEndPoint(void); CCyIsocEndPoint(HANDLE h, PUSB_ENDPOINT_DESCRIPTOR pEndPtDescriptor); PUCHAR BeginDataXfer(PUCHAR buf, LONG len, OVERLAPPED *ov); CCyIsoPktInfo* CreatePktInfos(LONG bufLen, int &amp;packets); }; //////////////////////////////////////////////////////////////////////////////// // // The Bulk Endpoint Class // //////////////////////////////////////////////////////////////////////////////// class CCyBulkEndPoint : public CCyUSBEndPoint { public: CCyBulkEndPoint(void); CCyBulkEndPoint(HANDLE h, PUSB_ENDPOINT_DESCRIPTOR pEndPtDescriptor); PUCHAR BeginDataXfer(PUCHAR buf, LONG len, OVERLAPPED *ov); }; //////////////////////////////////////////////////////////////////////////////// // // The Interrupt Endpoint Class // //////////////////////////////////////////////////////////////////////////////// class CCyInterruptEndPoint : public CCyUSBEndPoint { public: CCyInterruptEndPoint(void); CCyInterruptEndPoint(HANDLE h, PUSB_ENDPOINT_DESCRIPTOR pEndPtDescriptor); PUCHAR BeginDataXfer(PUCHAR buf, LONG len, OVERLAPPED *ov); }; //////////////////////////////////////////////////////////////////////////////// // // The Interface Class // //////////////////////////////////////////////////////////////////////////////// class CCyUSBInterface { private: protected: public: CCyUSBEndPoint *EndPoints[MAX_ENDPTS]; // Holds pointers to all the interface's endpoints, plus a pointer to the Control endpoint zero UCHAR bLength; UCHAR bDescriptorType; UCHAR bInterfaceNumber; UCHAR bAlternateSetting; UCHAR bNumEndpoints; // Not counting the control endpoint UCHAR bInterfaceClass; UCHAR bInterfaceSubClass; UCHAR bInterfaceProtocol; UCHAR iInterface; UCHAR bAltSettings; USHORT wTotalLength; // Needed in case Intfc has additional (non-endpt) descriptors CCyUSBInterface(HANDLE h, PUSB_INTERFACE_DESCRIPTOR pIntfcDescriptor); CCyUSBInterface(CCyUSBInterface&amp; ifc); // Copy Constructor ~CCyUSBInterface(void); }; //////////////////////////////////////////////////////////////////////////////// // // The Config Class // //////////////////////////////////////////////////////////////////////////////// class CCyUSBConfig { private: protected: public: CCyUSBInterface *Interfaces[MAX_INTERFACES]; UCHAR bLength; UCHAR bDescriptorType; USHORT wTotalLength; UCHAR bNumInterfaces; UCHAR bConfigurationValue; UCHAR iConfiguration; UCHAR bmAttributes; UCHAR MaxPower; UCHAR AltInterfaces; CCyUSBConfig(void); CCyUSBConfig(CCyUSBConfig&amp; cfg); // Copy Constructor CCyUSBConfig(HANDLE h, PUSB_CONFIGURATION_DESCRIPTOR pConfigDescr); ~CCyUSBConfig(void); }; //////////////////////////////////////////////////////////////////////////////// // // The USB Device Class - This is the main class that contains members of all the // other classes. // // To use the library, create an instance of this Class and call it's Open method // //////////////////////////////////////////////////////////////////////////////// class CCyUSBDevice { // The public members are accessible (i.e. corruptible) by the user of the library // Algorithms of the class don't rely on any public members. Instead, they use the // private members of the class for their calculations. public: CCyUSBDevice(HANDLE hnd = NULL, GUID guid = CYUSBDRV_GUID, BOOL bOpen = true); ~CCyUSBDevice(void); CCyUSBEndPoint **EndPoints; // Shortcut to USBCfgs[CfgNum]-&gt;Interfaces[IntfcIndex]-&gt;Endpoints CCyUSBEndPoint *EndPointOf(UCHAR addr); CCyControlEndPoint *ControlEndPt; CCyIsocEndPoint *IsocInEndPt; CCyIsocEndPoint *IsocOutEndPt; CCyBulkEndPoint *BulkInEndPt; CCyBulkEndPoint *BulkOutEndPt; CCyInterruptEndPoint *InterruptInEndPt; CCyInterruptEndPoint *InterruptOutEndPt; USHORT StrLangID; ULONG UsbdStatus; ULONG NtStatus; ULONG DriverVersion; ULONG USBDIVersion; char DeviceName[USB_STRING_MAXLEN]; char FriendlyName[USB_STRING_MAXLEN]; wchar_t Manufacturer[USB_STRING_MAXLEN]; wchar_t Product[USB_STRING_MAXLEN]; wchar_t SerialNumber[USB_STRING_MAXLEN]; CHAR DevPath[USB_STRING_MAXLEN]; USHORT BcdUSB; USHORT VendorID; USHORT ProductID; UCHAR USBAddress; UCHAR DevClass; UCHAR DevSubClass; UCHAR DevProtocol; UCHAR MaxPacketSize; USHORT BcdDevice; UCHAR ConfigValue; UCHAR ConfigAttrib; UCHAR MaxPower; UCHAR IntfcClass; UCHAR IntfcSubClass; UCHAR IntfcProtocol; bool bHighSpeed; DWORD BytesXfered; UCHAR DeviceCount(void); UCHAR ConfigCount(void); UCHAR IntfcCount(void); UCHAR AltIntfcCount(void); UCHAR EndPointCount(void); UCHAR Config(void) { return CfgNum; } // Normally 0 void SetConfig(UCHAR cfg); UCHAR Interface(void) { return IntfcNum; } // Usually 0 // No SetInterface method since only 1 intfc per device (per Windows) UCHAR AltIntfc(void); bool SetAltIntfc(UCHAR alt); GUID DriverGUID(void) { return DrvGuid; } HANDLE DeviceHandle(void) { return hDevice; } void UsbdStatusString(ULONG stat, PCHAR s); bool CreateHandle(UCHAR dev); void DestroyHandle(); bool Open(UCHAR dev); void Close(void); bool Reset(void); bool ReConnect(void); bool Suspend(void); bool Resume(void); bool IsOpen(void) { return (hDevice != INVALID_HANDLE_VALUE); } UCHAR PowerState(void); void GetDeviceDescriptor(PUSB_DEVICE_DESCRIPTOR descr); void GetConfigDescriptor(PUSB_CONFIGURATION_DESCRIPTOR descr); void GetIntfcDescriptor(PUSB_INTERFACE_DESCRIPTOR descr); CCyUSBConfig GetUSBConfig(int index); private: USB_DEVICE_DESCRIPTOR USBDeviceDescriptor; PUSB_CONFIGURATION_DESCRIPTOR USBConfigDescriptors[2]; CCyUSBConfig *USBCfgs[2]; HANDLE hWnd; HANDLE hDevice; HANDLE hDevNotification; HANDLE hHndNotification; GUID DrvGuid; UCHAR Devices; UCHAR Interfaces; UCHAR AltInterfaces; UCHAR Configs; UCHAR DevNum; UCHAR CfgNum; UCHAR IntfcNum; // The current selected interface's bInterfaceNumber UCHAR IntfcIndex; // The entry in the Config's interfaces table matching to IntfcNum and AltSetting void GetDevDescriptor(void); void GetCfgDescriptor(int descIndex); void GetString(wchar_t *s, UCHAR sIndex); void SetStringDescrLanguage(void); void SetAltIntfcParams(UCHAR alt); bool IoControl(ULONG cmd, PUCHAR buf, ULONG len); void SetEndPointPtrs(void); void GetDeviceName(void); void GetFriendlyName(void); void GetDriverVer(void); void GetUSBDIVer(void); void GetSpeed(void); void GetUSBAddress(void); //void CloseEndPtHandles(void); bool RegisterForPnpEvents(HANDLE h); }; //--------------------------------------------------------------------------- #endif </code></pre> <p><strong>CODE</strong></p> <pre><code>// MFCApplication2Dlg.cpp : implementation file // #include "stdafx.h" #include "MFCApplication2.h" #include "MFCApplication2Dlg.h" #include "afxdialogex.h" #include "afxwin.h" #include "CyAPI.h" #include "Periph.h" #include "Resource.h" #include "UART.h" #ifdef _DEBUG #define new DEBUG_NEW #endif bool IsConnect = false; // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CMFCApplication2Dlg dialog CMFCApplication2Dlg::CMFCApplication2Dlg(CWnd* pParent /*=NULL*/) : CDialogEx(CMFCApplication2Dlg::IDD, pParent) { m_hIcon = AfxGetApp()-&gt;LoadIcon(IDR_MAINFRAME); } void CMFCApplication2Dlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CMFCApplication2Dlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, &amp;CMFCApplication2Dlg::OnBnClickedButton1) ON_BN_CLICKED(IDC_BUTTON2, &amp;CMFCApplication2Dlg::OnBnClickedButton2) ON_BN_CLICKED(IDC_BUTTON3, &amp;CMFCApplication2Dlg::OnBnClickedButton3) END_MESSAGE_MAP() // CMFCApplication2Dlg message handlers BOOL CMFCApplication2Dlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX &amp; 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX &lt; 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu-&gt;AppendMenu(MF_SEPARATOR); pSysMenu-&gt;AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } void CMFCApplication2Dlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID &amp; 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMFCApplication2Dlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast&lt;WPARAM&gt;(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&amp;rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMFCApplication2Dlg::OnQueryDragIcon() { return static_cast&lt;HCURSOR&gt;(m_hIcon); } void CMFCApplication2Dlg::OnBnClickedButton1() { USBDevice-&gt;Open(0); if (USBDevice-&gt;IsOpen() != TRUE) { AfxMessageBox(_T("Failed to Open Device")); } else { IsConnect = true; } } void CMFCApplication2Dlg::OnBnClickedButton3() { USBDevice-&gt;Close(); IsConnect = false; } void CMFCApplication2Dlg::OnBnClickedButton2() { TCHAR tmpUart[60]; long OutPacketSize; OutPacketSize = sizeof(sUart); LPTSTR pBuffer; CString sBuffer; int i; if (IsConnect == false) { AfxMessageBox(_T("USB Connect Fail")); return; } CEdit *OutValue = (CEdit*)GetDlgItem(IDC_OUT_VALUE); pBuffer = sBuffer.GetBuffer(60); OutValue-&gt;GetWindowText(pBuffer, 60); _tcscpy(tmpUart, pBuffer); OutPacketSize = _tcslen(tmpUart); for (i = 0; i&lt;OutPacketSize; i++) sUart[i] = tmpUart[i]; sUart[OutPacketSize + 1] = 0; OutPacketSize = OutPacketSize + 1; // Perform the BULK OUT if (USBDevice-&gt;BulkOutEndPt) { USBDevice-&gt;BulkOutEndPt-&gt;XferData(sUart, OutPacketSize); } } </code></pre> <p>This function here will perform the bulk out event. But there seems to be a problem in the XferData(bool) in checking the <code>int[60]</code> to <code>PUCHAR</code>. What is the right declaration of the <code>sUart</code> variable to match with the <code>long OutPacketSize</code> I think <code>int sUart[60]</code> is incorrect. Please help me with this one, I'm new to <em>Microsoft Foundation Classes</em> (MFC)</p> <pre><code>void CMFCApplication2Dlg::OnBnClickedButton2() { int sUart[60]; TCHAR tmpUart[60]; long OutPacketSize; OutPacketSize = sizeof(sUart); LPTSTR pBuffer; CString sBuffer; int i; if (IsConnect == false) { AfxMessageBox(_T("USB Connect Fail")); return; } CEdit *OutValue = (CEdit*)GetDlgItem(IDC_OUT_VALUE); pBuffer = sBuffer.GetBuffer(60); OutValue-&gt;GetWindowText(pBuffer, 60); wcscpy_s(tmpUart, pBuffer); OutPacketSize = _tcslen(tmpUart); for (i = 0; i&lt;OutPacketSize; i++) sUart[i] = tmpUart[i]; sUart[OutPacketSize + 1] = 0; OutPacketSize = OutPacketSize + 1; // Perform the BULK OUT if (USBDevice-&gt;BulkOutEndPt) { USBDevice-&gt;BulkOutEndPt-&gt;XferData(sUart, OutPacketSize); } } </code></pre>
<p>Presuming the integer you're passing makes sense to the called function, I would expect the following to work:</p> <pre><code>USBDevice-&gt;BulkOutEndPt-&gt;XferData(reinterpret_cast&lt;PUCHAR&gt;(sUart), OutPacketSize); </code></pre>
Extract keys from elasticsearch result and store in other list <p>I have a ES returned list stored in a dict </p> <pre><code>res = es.search(index="instances-i*",body=doc) </code></pre> <p>The result returned by res looks like: </p> <pre><code>{ "took": 34, "timed_out": false, "_shards": { "total": 1760, "successful": 1760, "failed": 0 }, "hits": { "total": 551, "max_score": 0.30685282, "hits": [ { "_index": "instances-i-0034438e-2016.10.10-08:23:51", "_type": "type_name", "_id": "1", "_score": 0.30685282, "_source": { "ansible.isv_alias": "ruiba", "ansible": { "isv_alias": "ruiba", "WEB_URL": "sin01-cloud.trial.sentinelcloud.com/ruiba" } } } , { "_index": "instances-i-0034438e-2016.10.11-08:23:54", "_type": "type_name", "_id": "1", "_score": 0.30685282, "_source": { "ansible.isv_alias": "aike3", "ansible": { "isv_alias": "aike3", "WEB_URL": "sin01-cloud.trial.cloud.com/aike3" } } } , { "_index": "instances-i-883sf38e-2016.10.12-08:23:45", "_type": "type_name", "_id": "1", "_score": 0.30685282, "_source": { "ansible.isv_alias": "beijing", "ansible": { "isv_alias": "beijing", "WEB_URL": "sin01-cloud.trial.cloud.com/beijing" } } } . . . . so on </code></pre> <p>I need to extract the WEB_URL from the returned dict and store it in a LIST. </p> <p>Also i am curious if we can actually make sure that there is no DUPLICATE ENTRY OF The value of WEB_URL in the LIST being populated {This is 2nd part though}</p>
<p>To store the value of <code>WEB_URL</code> you need to iterate over the dictionary-</p> <pre><code>data = response_from_es['hits'] list_of_urls = [] for item in data['hits']: list_of_urls.append(item['_source']['ansible']['WEB_URL']) print list_of_urls </code></pre> <p>And to make the <code>list_of_urls unique</code> -> <code>set(list_of_urls)</code></p>
Creating a Java Project out of existing sources <p>I have some source files for a Java Project (the output is a jar file). </p> <p>I have several source directories. I have a properties file, I have a manifest file, and an image directory. </p> <p>I am able to compile all the java sources from the command line &amp; then able to recreate the jar file by adding the class files, manifest, properties file &amp; the image directory.</p> <p>However, I want to create a Eclipse project out of these for debugging purposes. How do I go about doing this?</p>
<p><strong>Case 1 : When extracted project was use in eclipse before</strong></p> <p>Extract the jar file into a separate folder </p> <p>and make the folder as a workspace for eclipse.</p> <p>And open eclipse</p> <p>right click </p> <p>import</p> <p><a href="https://i.stack.imgur.com/VktT7.png" rel="nofollow"><img src="https://i.stack.imgur.com/VktT7.png" alt="enter image description here"></a></p> <p>And go for next and finish</p> <p><strong>Case 2 : When extracted project was not used in eclipse before</strong></p> <p>Extract the jar file into a separate folder</p> <p>Create a new project </p> <p>Copy the java from extracted folder to new created project with same package in src</p> <p>Then build the projecct</p> <p><a href="https://i.stack.imgur.com/fT9iO.png" rel="nofollow"><img src="https://i.stack.imgur.com/fT9iO.png" alt="enter image description here"></a></p>
Quick sort CLRS Partition Always on n/3 Element <p>I am wondering if this is the correct recurrence when assuming that the pivot is always at the n/3 position when using Quicksort from CLRS. </p> <p>The recurrence I have is below</p> <p><a href="https://i.stack.imgur.com/9UEiH.gif" rel="nofollow"><img src="https://i.stack.imgur.com/9UEiH.gif" alt="enter image description here"></a></p>
<p>If the pivot always happens to be at the n/3 position then the recurrence for T(n) is:</p> <p><img src="https://i.stack.imgur.com/xOME6.gif" alt="recurrence"></p> <p>I'll explain where each of the three components of the sum comes from:</p> <ul> <li><p><img src="https://i.stack.imgur.com/2Wie2.gif" alt="cn"></p> <p>You need linear time to iterate over all the elements of the array, deciding for each element at which side of the pivot it belongs.</p></li> <li><p><img src="https://i.stack.imgur.com/XxHaK.gif" alt="one third"></p> <p>After positioning all the elements to the left or to the right of the pivot, you recursively sort the left side of the array which consists of about (n-1)/3 elements. This number comes from the fact that the pivot is at the n/3 position.</p></li> <li><p><img src="https://i.stack.imgur.com/LpqO5.gif" alt="two thirds"></p> <p>Recursively sort the right side of the array which consists of about 2(n-1)/3 elements.</p></li> </ul> <p>You haven't asked about solving the recurrence but I'll note that it solves to nlog(n) just as in the case in which the pivot always happens to be at the the n/2 position.</p>
How can I load data from table on jsp page in specific range? <p><a href="https://i.stack.imgur.com/kl9Hx.png" rel="nofollow">The Table</a></p> <p>I have a table on my jsp page. There are more than thousand of data in the table. I want to add a paging system on table in such way that when I click 1 number page , then selected number of data will be loaded only, such as 20 number row only will be loaded . Then when I select page no 2, the loaded row will be from 21th row to 40th row only. As like as google page loading system. Here is my Code:</p> <pre><code> function createDynamicTable(data){ currentbatchitemData = eval(data); for(var i = 0; i &lt; currentbatchitemData.length; i++){ var code = currentbatchitemData[i].empCode; var name = currentbatchitemData[i].empName; var salary = 0 ; var income = currentbatchitemData[i].incomeYear; var month = currentbatchitemData[i].month ; var des = currentbatchitemData[i].batchDesc; var tableInfo = "&lt;tr&gt;"; tableInfo += '&lt;td class="table-td-text-color"&gt;' + code + '&lt;/td&gt;' + '&lt;td class="table-td-text-color"&gt;' + name + '&lt;/td&gt;' + '&lt;td class="table-td-text-color"&gt;'+ salary + '&lt;/td&gt;' + '&lt;td class="table-td-text-color"&gt;' + '&lt;button type="button" class="btn-edit btn btn-xs"&gt;&lt;span class="fa fa-edit"&gt;&lt;/span&gt;&lt;/button&gt;'+ '&lt;button type="button" onclick="delRow(this);" class="btn-del btn btn-xs"&gt;&lt;span class="fa fa-trash"&gt;&lt;/span&gt;&lt;/button&gt;' +'&lt;/td&gt;'; $("#currentbatchitem tbody").append(tableInfo); } $(document).ready(function(){ $('#currentbatchitem').DataTable(); }); $("#income_year").val(income); $("#pay_month").val(month); $("#batch_description").val(des); InitHandlers(); /* } }) ;*/ } </code></pre>
<p>You need to implement server processing inorder to achieve your goal.</p> <p>Please follow the link.</p> <p><a href="https://datatables.net/examples/data_sources/server_side.html" rel="nofollow">https://datatables.net/examples/data_sources/server_side.html</a></p>
Populate p:dataTable from MySQL using Hibernate <p>I want to populate a <code>&lt;p:dataTable&gt;</code> but I want to populate it from MySQL database and I want to use Hibernate queries for it. I use JSF.</p> <p>Here is an image of my work. I want to view all the registered users.</p> <p><a href="https://i.stack.imgur.com/kLfVG.png" rel="nofollow"><img src="https://i.stack.imgur.com/kLfVG.png" alt="enter image description here"></a></p>
<p>Create a method in your managed bean with desired List type-</p> <pre><code>public List&lt;DesiredType&gt; getInfo() { return daoObject.getUserInfo(); } </code></pre> <p>Now in your dao implementation-</p> <pre><code> public List&lt;DesiredType&gt; getUserInfo() { String hql = "from EntityName"; Query q = sessionFactory.openSession().createQuery(hql); List&lt;DesiredType&gt; list = q.list(); return list; } </code></pre> <p>Now call <strong>getInfo()</strong> from xhtml page to populate the data table. Hope this help.</p>
how to get array of values as a values in json object in android <pre><code>String finalData = "{"Books":[{"name":"Genesis","chapters1":["Chapter No:1","Chapter No:2","Chapter No:3","Chapter No:4","Chapter No:5","Chapter No:6","Chapter No:7","Chapter No:8","Chapter No:9","Chapter No:10"]}]}; private void ChaptersData(String finalData) { try { JSONObject mainchapter=new JSONObject(finalData); JSONArray chapterdata=mainchapter.getJSONArray("Books"); chapterList=new String[chapterdata.length()]; for (int j=0;j&lt;=chapterdata.length();j++){ JSONObject chapInterData=(JSONObject) chapterdata.get(j); String chapter=chapInterData.getString(0); Log.e("Chapter", " "+chapter); chapterList[j]=chapter; } } catch (JSONException e) { e.printStackTrace(); } } </code></pre> <p>now how can i get the chapters from json object</p>
<p>put this code inside your for loop</p> <pre><code>JSONArray chap = chapInterData.getJSONArray("chapters1"); for(int k =0;k&lt;chap.length();k++) { String data=chap.getString(k); Log.e("data", " "+data); } </code></pre> <p>insert <code>data</code> in your desired <code>array</code></p>
return object length which includes key is true not false <p>I want to write some filter logic where an object returns its length which includes only key having true value.</p> <pre><code> $scope.generated.codesWithBalance = [A:true, B:true, C:false]; </code></pre> <p>so for above object it should return length as 2. Since C is false so want to exclude in the count.</p> <p>But now whenever i try to get the length it returns total length</p> <pre><code> Object.keys($scope.generated.codesWithBalance).length </code></pre> <p>Any way that i can avoid key having false value?</p>
<p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="nofollow"><code>Array.prototype.filter()</code></a> to get only the keys with true values.</p> <pre><code>Object.keys($scope.generated.codesWithBalance).filter(function(key, i, array) { return array[key]; }).length; </code></pre>
for loop not executing code sequencially (swift + spritekit) <p>Here's my code:</p> <pre><code>override func didMoveToView(view: SKView) { /* Setup your scene here */ let origin = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame)) let delay = SKAction.waitForDuration(2.0) for (var i = 0; i &lt; 6; i++) { //generate a random point on a circle centered at origin with radius of 500 let point = randomPointOnCircle(500, center: origin) let chanceToSpawn = arc4random_uniform(100) switch chanceToSpawn { case 0...60: self.runAction(delay){ let smallBall = SKSpriteNode(imageNamed: "smallBall”) self.addChild(smallBall) smallBall.xScale = 0.05 smallBall.yScale = 0.05 smallBall.position = point let finalDest = CGPointMake(origin.x, origin.y) let moveAction = SKAction.moveTo(finalDest, duration: 5.0) smallBall.runAction(SKAction.sequence([SKAction.waitForDuration(0.1), moveAction, SKAction.runBlock({ smallBall.removeFromParent() })])) delay } break case 61...80: //same as case 0…60, smallBall changed to “mediumBall” break case 81...99: //same as case 0…60, smallBall changed to “largeBall” break default: break } // ends switch statement }//ends for loop }//end didMoveToView </code></pre> <p>Basically I have balls that spawn on a random point on a circle and move towards the center. But the problem I am having is that no matter how I rearrange things (or rewrite things, i.e., trying different loops or defining functions for spawning the ball and the movement of the ball and simply calling them from inside the switch statement) all of the balls spawn at the same time. I am trying to make it so they spawn one after the other (meaning a ball spawns, the thread waits a few seconds, then spawns another ball.), and I can't seem to figure out why each ball is spawning at the same time as all the other balls. </p> <p>I'm fairly new to Swift/Spritekit programming and I feel like I'm overlooking some small detail and this is really bugging me. Any help appreciated!</p>
<p>try this, may be due to same time u are adding the actions for each balls, </p> <pre><code>smallBall.runAction(SKAction.sequence([SKAction.waitForDuration(0.1 + (i * 0.35/2)), moveAction, SKAction.runBlock({ smallBall.removeFromParent() })])) // delay added (0.1 + (increment the daly)) </code></pre> <p>try this </p>
Operations in multi index dataframe pandas <p>I need to process geographic and statistical data from a big data csv. It contains data from geographical administrative and geostatistical. Municipality, Location, geostatistical basic division and block constitute the hierarchical indexes.</p> <p>I have to create a new column ['data2'] for every element the max value of the data in the geo index, and divide each block value by that value. For each index level, and the index level value must be different from 0, because the 0 index level value accounts for other types of info not used in the calculation.</p> <pre><code> data1 data2 mun loc geo block 1 0 0 0 20 20 1 1 0 0 10 10 1 1 1 0 10 10 1 1 1 1 3 3/4 1 1 1 2 4 4/4 1 1 2 0 30 30 1 1 2 1 1 1/3 1 1 2 2 3 3/3 1 2 1 1 10 10/12 1 2 1 2 12 12/12 2 1 1 1 123 123/123 2 1 1 2 7 7/123 2 1 2 1 6 6/6 2 1 2 2 1 1/6 </code></pre> <p>Any ideas? I have tried with for loops, converting the indexes in columns with reset_index() and iterating by column and row values but the computation is taking forever and I think that is not the correct way to do this kind of operations.</p> <p>Also, what if I want to get my masks like this, so I can run my calculations to every level. </p> <pre><code>mun loc geo block 1 0 0 0 False 1 1 0 0 False 1 1 1 0 True 1 1 1 1 False 1 1 1 2 False 1 1 2 0 True 1 1 2 1 False 1 1 2 2 False mun loc geo block 1 0 0 0 False 1 1 0 0 True 1 1 1 0 False 1 1 1 1 False 1 1 1 2 False 1 2 0 0 True 1 2 2 0 False 1 2 2 1 False mun loc geo block 1 0 0 0 True 1 1 0 0 False 1 1 1 0 False 1 1 1 1 False 1 1 1 2 False 2 0 0 0 True 2 1 1 0 False 2 1 2 1 False </code></pre>
<p>You can first create <code>mask</code> from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.html" rel="nofollow"><code>MultiIndex</code></a>, compare with <code>0</code> and check at least one <code>True</code> (at least one <code>0</code>) by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow"><code>any</code></a>:</p> <pre><code>mask = (pd.DataFrame(df.index.values.tolist(), index=df.index) == 0).any(axis=1) print (mask) mun loc geo block 1 0 0 0 True 1 0 0 True 1 0 True 1 False 2 False 2 0 True 1 False 2 False 2 1 1 False 2 False 2 1 1 1 False 2 False 2 1 False 2 False dtype: bool </code></pre> <p>Then get <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.max.html" rel="nofollow"><code>max</code></a> values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> per first, second and third index, but before filter by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> only values where are not <code>True</code> in <code>mask</code>:</p> <pre><code>df1 = df.ix[~mask, 'data1'].groupby(level=['mun','loc','geo']).max() print (df1) mun loc geo 1 1 1 4 2 3 2 1 12 2 1 1 123 2 6 </code></pre> <p>Then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> <code>df1</code> by <code>df.index</code>, remove last level of <code>Multiindex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow"><code>mask</code></a> values where no change by <code>mask</code> (also is necessary remove last level) and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>fillna</code></a> by <code>1</code>, because dividing return same value.</p> <pre><code>df1 = df1.reindex(df.reset_index(level=3, drop=True).index) .mask(mask.reset_index(level=3, drop=True)).fillna(1) print (df1) Name: data1, dtype: int64 mun loc geo 1 0 0 1.0 1 0 1.0 1 1.0 1 4.0 1 4.0 2 1.0 2 3.0 2 3.0 2 1 12.0 1 12.0 2 1 1 123.0 1 123.0 2 6.0 2 6.0 Name: data1, dtype: float64 </code></pre> <p>Last divide by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow"><code>div</code></a>:</p> <pre><code>print (df['data1'].div(df1.values,axis=0)) mun loc geo block 1 0 0 0 20.000000 1 0 0 10.000000 1 0 10.000000 1 0.750000 2 1.000000 2 0 30.000000 1 0.333333 2 1.000000 2 1 1 0.833333 2 1.000000 2 1 1 1 1.000000 2 0.056911 2 1 1.000000 2 0.166667 dtype: float64 </code></pre>
Typewriter CSS Animation in table <p>I wanted to implement a typewriter effect in CSS and I found this great article in <a href="https://css-tricks.com/snippets/css/typewriter-effect/" rel="nofollow">CSS Tricks</a></p> <p>I was tinkering around with it and wanted to see if I can implement what would be on a hero image, shown here in <a href="http://codepen.io/neotriz/pen/JRkraZ" rel="nofollow">Codepen</a></p> <p>However, you can see that the blinking goes all the way to the end.</p> <p>Is there way to fix, or this unavoidable, since the display it's set to <code>table-cell</code>?</p>
<p>You can try that. Remove fixed width from intro container and give this into description. And for centering you can add margin: 0 auto into intro.</p> <pre><code>#intro{ display: table; height: 100vh; margin: 0 auto; .intro-description{ display: table-cell; vertical-align: middle; text-align: center; width: 100vw; } } </code></pre> <p>Codepen: <a href="http://codepen.io/anon/pen/WGydqj" rel="nofollow">http://codepen.io/anon/pen/WGydqj</a></p>
Product filter shows incorrect result admin product grid magento <p>I am using Magento Enterprise Edition 1.14.3 I have added a custom column <code>simple_count</code> to count the total no of products in a configurable product. Filter is working fine if i use <code>'type' =&gt; 'text'</code> but when i use <code>'type' =&gt; 'number'</code>, then filter shows incorrect result. Please see the code below:</p> <pre><code>$this-&gt;addColumn('simple_count', array( 'header' =&gt; Mage::helper('catalog')-&gt;__('Simple Count'), 'align' =&gt;'right', 'width' =&gt; '100px', 'type' =&gt; 'number', 'index' =&gt; 'simple_count', 'renderer' =&gt; 'Wcl_Employee_Block_Adminhtml_Employee_Renderer_Simplecount', )); </code></pre> <p>For rendering section:</p> <pre><code>class Wcl_Employee_Block_Adminhtml_Employee_Renderer_Simplecount extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract{ public function render(Varien_Object $row) { $entityId = $row['entity_id']; $product = Mage::getModel('catalog/product')-&gt;load($entityId); $productType = $product-&gt;getTypeID(); $sum = 0; if($productType == 'configurable'): $childProducts = Mage::getModel('catalog/product_type_configurable')-&gt;getUsedProducts(null,$product); //echo "Simple Count:".count($childProducts); //$sum =0; foreach($childProducts as $itempro): $productdata = Mage::getModel('catalog/product')-&gt;load($itempro-&gt;getId()); $stock = Mage::getModel('cataloginventory/stock_item')-&gt;loadByProduct($productdata)-&gt;getQty(); $sum = $sum + $stock; endforeach; $product-&gt;setSimpleCount($sum); $product-&gt;save(); if($sum == 0): return '0'; else: return $sum; endif; else: $product-&gt;setSimpleCount($sum); $product-&gt;save(); return '0'; endif; } protected function _addressFilter($collection, $column) { if (!$value = $column-&gt;getFilter()-&gt;getValue()) { return $this; } echo $column-&gt;getFilter()-&gt;getValue(); die; } } </code></pre> <p>If anyone knows this, please gelp me out. Thanks</p>
<pre><code> you can use filter_condition_callback like this $this-&gt;addColumn('simple_count', array( 'header' =&gt; Mage::helper('catalog')-&gt;__('Simple Count'), 'align' =&gt;'right', 'width' =&gt; '100px', 'type' =&gt; 'number', 'index' =&gt; 'simple_count', 'renderer' =&gt; 'Wcl_Employee_Block_Adminhtml_Employee_Renderer_Simplecount', 'filter_condition_callback' =&gt; array($this, '_filterValidityCondition'), )); protected function _filterValidityCondition($collection, $column) { if (!$value = $column-&gt;getFilter()-&gt;getValue()) { return; } if (isset($value['from']) &amp;&amp; $value['from']) { $this-&gt;getCollection()-&gt;addFieldToFilter($column-&gt;getIndex(), array('gteq' =&gt; $from)); } if (isset($value['to']) &amp;&amp; $value['to']) { $this-&gt;getCollection()-&gt;addFieldToFilter($column-&gt;getIndex(), array('leeq' =&gt; $to)); } } </code></pre>
How to write test cases for titanium with alloy <p>I am stuck while writing test cases for alloy framework as i am not getting how to use controllers and alloy files in mocha testing framework. I searched on google and few links suggested below code to moke a controller but it throws error that "TypeError: alloy.createController is not a function".</p> <p>var alloy = require('../../alloy'); it('Verify row controller', function() {</p> <pre><code> console.log(JSON.stringify(alloy)) var controller = alloy.createController('login', { name : "uniqueName", }); // if(controller.passwordTest.value !== "uniqueName"){ // throw new ("Verify row controller FAILED"); // } }); </code></pre>
<p>Currently, I can show you a (slightly modified) example of our codebase.</p> <p>First of all, our controller tests are pure javascript tests. All calls to the Ti api are executed against a mock. We solely focus on the controller under test and all dependencies are mocked.</p> <p>We rely on jasmine and jasmine-npm for that.</p> <ul> <li>install jasmine-npm; see <a href="https://github.com/jasmine/jasmine-npm" rel="nofollow">https://github.com/jasmine/jasmine-npm</a></li> <li>create 'spec' folder in the root of your project (folder with tiapp.xml)</li> <li>place all your test files inside this folder</li> <li>the filenames of test files must end with _spec.js</li> <li><p>run the jasmine command from within the root folder of your project</p> <p>describe('authenticate controller test', function() {</p> <pre><code>var USER_NAME = "John Doe"; var fooControllerMock = { getView: function(){} }; var fooViewMock = { open: function(){} } Ti = { // create here a mock for all Ti* functions and properties you invoke in your controller } Alloy = { CFG: { timeout: 100 }, Globals: { loading: { hide: function(){} }, networkClient: { hasAutoLogin: function(){} }, notifications: { showError: function(){} } }, createController: function(){} }; var controllerUnderTest; // class under test $ = { btnAuthenticate: { addEventListener: function(){} }, authenticate: { addEventListener: function(){}, close: function(){} }, username: { addEventListener: function(){}, getValue: function(){} }, password: { addEventListener: function(){} }, windowContainer: { addEventListener: function(){} } }; L = function(s){ return s; }; beforeEach(function () { controllerUnderTest = require('../app/controllers/auth'); }); it('should create foo controller when authentication was succesful', function(){ spyOn(Alloy.Globals.loading, 'hide'); spyOn(Alloy, 'createController').and.returnValue(fooControllerMock); spyOn(fooControllerMock, 'getView').and.returnValue(fooViewMock); spyOn($.username, 'getValue').and.returnValue(USER_NAME); spyOn($.auth, 'close'); controllerUnderTest.test._onAuthSuccess(); expect(Alloy.Globals.loading.hide).toHaveBeenCalled(); expect(Alloy.createController).toHaveBeenCalledWith('foo'); expect(fooControllerMock.getView).toHaveBeenCalled(); expect($.auth.close).toHaveBeenCalled(); }); it('should show error message when a login error has occured', function(){ spyOn(Alloy.Globals.loading, 'hide'); spyOn(Alloy.Globals.notifications, 'showError'); controllerUnderTest.test._onAuthLoginError(); expect(Alloy.Globals.loading.hide).toHaveBeenCalled(); expect(Alloy.Globals.notifications.showError).toHaveBeenCalledWith('msg.auth.failure'); }); }); </code></pre></li> </ul> <p>Be sure to write a mock implementation(just empty) for all Ti* stuff you call from within your controller. I know this is quite cumbersome but a solution is on it's way.</p> <p>Note that we already created an npm package which has a generated mock for this (based on api.jsca), together with some code with which you can mock all required dependencies, together with a set of testing best practices. However we will validate this code internally before we opensource it. I hope we can write our blog post and expose our accompanying github repo within a few weeks. Just keep an eye on tiSlack.</p> <p>Controller code:</p> <pre><code>function _onAuthSuccess() { Alloy.Globals.loading.hide(); Alloy.createController('foo').getView().open(); $.authenticate.close(); } function _onAuthLoginError() { Alloy.Globals.loading.hide(); Alloy.Globals.notifications.showError(L('msg.auth.failure')); } function _onAuthTokenValidationFailure() { Alloy.Globals.loading.hide(); } function _authenticate() { var username = $.username.value; var password = $.password.value; if(Alloy.Globals.validationEmail.isValidEmailAddress(username)){ Alloy.Globals.loading.show(L('authenticate.msg.logging.in'), false); } else { Alloy.Globals.notifications.showError(L('app.error.invalid.email')); } } function _onNetworkAbsent() { Alloy.Globals.loading.hide(); Alloy.Globals.notifications.showError(L('global.no.network.connection.available')); } function _hideKeyboard() { $.username.blur(); $.password.blur(); } function _focusPassword() { $.username.blur(); $.password.focus(); } function _init() { Ti.App.addEventListener('auth:success', _onAuthSuccess); Ti.App.addEventListener('auth:loginFailed', _onAuthLoginError); Ti.App.addEventListener('app:parseError', _onAppParseError); Ti.App.addEventListener('network:none', _onNetworkAbsent); $.btnAuthenticate.addEventListener('click', ..); $.authenticate.addEventListener('close', _cleanup); $.username.addEventListener('return', _focusPassword); $.password.addEventListener('return', _authenticate); $.windowContainer.addEventListener('touchstart', _hideKeyboard); } _init(); function _cleanup() { Ti.API.info('Closing and destroying the auth controller'); ... $.windowContainer.removeEventListener('touchstart', _hideKeyboard); $.destroy(); $.off(); } module.exports = { test: { _onAuthSuccess: _onAuthSuccess, _onAuthLoginError: _onAuthLoginError } } </code></pre> <p>and the corresponding view:</p> <pre><code>&lt;Alloy&gt; &lt;Window&gt; &lt;View id="windowContainer"&gt; &lt;TextField id="username" /&gt; &lt;TextField id="password" &gt; &lt;Button id="btnAuthenticate" /&gt; &lt;/View&gt; &lt;/Window&gt; &lt;/Alloy&gt; </code></pre>
knockout reset viewmodel to original data <p>what is the best way to reset knockout viewmodel back to the original data?</p> <p>if the original data json is not changed, after I do some changed on the observable, how can I set it back? just like refresh the page.</p>
<p>I think it is bad practice to "refresh" your viewModel. You could refresh it like this:</p> <pre><code>ko.cleanNode(document.getElementById("element-id")); ko.applyBindings(yourViewModel, document.getElementById("element-id")); </code></pre> <p>But I think it is cleaner to have a method on your view model called "reset", that sets your observables back to initial states. Maybe like this:</p> <pre><code>function MyViewModel() { this.something = ko.observable("default value"); this.somethingElse = ko.observable(0): this.reset = function() { this.something("default value"); this.somethingElse(0); } } </code></pre>
Additive Operator (+) Performing Concatenation Instead of Addition <p>I am new to Java. When I am processing through the loop below I want to show the loop's counter value being incremented by 1. When I kept the below code of that I am getting the value as like of concatenate with 1 with the counter value. Why is the <code>System.out.println</code> working with concatenation instead of addition?</p> <pre><code>for (c = 0; c &lt; Size; c++) { System.out.println("here the problem " + c+1 + " Case"); } </code></pre>
<p>The <code>+</code> operator is overloaded for both concatenation and additon, and both operators have the same precedence, so the operations are evaluated from left to right.</p> <p>Starting at the left, the first operand encountered is a String <code>"here the problem"</code>, so the operator knows that it should perform concatenation. It proceeds to concatenate <code>c</code> to that String, yielding a new String.</p> <p>The second <code>+</code> therefore is operating on that resulting String, and <code>1</code>, so once again it does concatenation.</p> <p>If you want to specifically control the order of the operations, and have <code>c + 1</code> evaluated before <code>"here the problem" + c</code> then you need to enclose the operation in parentheses:</p> <pre><code>"here the problem " + (c + 1) + " Case" </code></pre>
Color outliers multiple factors in boxplot <p>Let's say I have the following data frame:</p> <pre><code>library(ggplot2) set.seed(101) n=10 df&lt;- data.frame(delta=rep(rep(c(0.1,0.2,0.3),each=3),n), metric=rep(rep(c('P','R','C'),3),n),value=rnorm(9*n, 0.0, 1.0)) </code></pre> <p>My goal is to do a boxplot by multiple factors:</p> <pre><code>p&lt;- ggplot(data = df, aes(x = factor(delta), y = value)) + geom_boxplot(aes(fill=factor(metric))) </code></pre> <p>The output is:</p> <p><a href="https://i.stack.imgur.com/tT8gZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/tT8gZ.png" alt="enter image description here"></a></p> <p>So far so good, but if I do:</p> <pre><code>p+ geom_point(aes(color = factor(metric))) </code></pre> <p>I get:</p> <p><a href="https://i.stack.imgur.com/8VGQi.png" rel="nofollow"><img src="https://i.stack.imgur.com/8VGQi.png" alt="enter image description here"></a></p> <p>I do not know what it is doing. My goal is to color the outliers as it is done <a href="http://stackoverflow.com/questions/10805643/ggplot2-add-color-to-boxplot-continuous-value-supplied-to-discrete-scale-er">here</a>. Note that <a href="http://stackoverflow.com/questions/8499378/ggplot2-boxplot-how-do-i-match-the-outliers-color-to-fill-aesthetics">this solution</a> changes the inside color of the boxes to white and set the border to different colors. I want to keep the same color of the boxes while having the outliers inherit those colors. I want to know how to make the outliers get the same colors from their respective boxplots.</p>
<p>Do you want just to change the outliers' colour ? If so, you can do it easily by drawing boxplot twice.</p> <pre><code>p &lt;- ggplot(data = df, aes(x = factor(delta), y = value)) + geom_boxplot(aes(colour=factor(metric))) + geom_boxplot(aes(fill=factor(metric)), outlier.colour = NA) # outlier.shape = 21 # if you want a boarder </code></pre> <p><a href="https://i.stack.imgur.com/VnoUT.png" rel="nofollow"><img src="https://i.stack.imgur.com/VnoUT.png" alt="enter image description here"></a></p> [EDITED] <pre><code>colss &lt;- c(P="firebrick3",R="skyblue", C="mediumseagreen") p + scale_colour_manual(values = colss) + # outliers colours scale_fill_manual(values = colss) # boxes colours # the development version (2.1.0.9001)'s geom_boxplot() has an argument outlier.fill, # so I guess under code would return the similar output in the near future. p2 &lt;- ggplot(data = df, aes(x = factor(delta), y = value)) + geom_boxplot(aes(fill=factor(metric)), outlier.shape = 21, outlier.colour = NA) </code></pre>
how to save all items for each url <p>I add a url list like this. When it goes to pipeline, it seems all items from the url list will be passed to process_item. </p> <p>how to separate items according to the specific url? For example, to save items from one url to one file.</p> <pre><code>class MySpider(scrapy.Spider): name = 'example.com' allowed_domains = ['example.com'] start_urls = [ 'http://www.example.com/1.html', 'http://www.example.com/2.html', 'http://www.example.com/3.html', ] </code></pre>
<p>Add a ref_url to the item before yielding it, then check for it in the pipeline. There are other solutions, but this is the most direct one I guess.</p>
Pagination using Zend Db Sql <p>I'm following <a href="https://docs.zendframework.com/tutorials/in-depth-guide/zend-db-sql-zend-hydrator/" rel="nofollow">this tutorial</a> on zend documentation to create the blog module from the beginning, finished and everything is working properly. On the previous tutorial that was to create an album module they used <code>TableGateway</code> and also showed how to create the pagination with it, but in this blog module they didn't and they are using <code>Zend\Db\Sql</code>.</p> <p>I tried to find something on the internet about that and nothing...</p> <pre><code>public function findAllPosts() { $sql = new Sql($this-&gt;db); $select = $sql-&gt;select('posts'); $statement = $sql-&gt;prepareStatementForSqlObject($select); $result = $statement-&gt;execute(); if (! $result instanceof ResultInterface || ! $result-&gt;isQueryResult()) { return []; } $resultSet = new HydratingResultSet($this-&gt;hydrator, $this-&gt;postPrototype); $resultSet-&gt;initialize($result); return $resultSet; } </code></pre> <p>On the previous tutorial we created two methods, one called <code>fetchAll($paginated = false)</code> and another one called <code>fetchPaginatedResults</code>, if <code>$paginated</code> was true it called the method <code>fetchPaginatedResults</code>, for example:</p> <pre><code>public function fetchAll($paginated = false) { if ($paginated) { return $this-&gt;fetchPaginatedResults(); } return $this-&gt;tableGateway-&gt;select(); } private function fetchPaginatedResults() { // Create a new Select object for the table: $select = new Select($this-&gt;tableGateway-&gt;getTable()); // Create a new result set based on the Album entity: $resultSetPrototype = new ResultSet(); $resultSetPrototype-&gt;setArrayObjectPrototype(new Album()); // Create a new pagination adapter object: $paginatorAdapter = new DbSelect( // our configured select object: $select, // the adapter to run it against: $this-&gt;tableGateway-&gt;getAdapter(), // the result set to hydrate: $resultSetPrototype ); $paginator = new Paginator($paginatorAdapter); return $paginator; } </code></pre> <p>I was wondering, how to do the same using <code>Zend\Db\Sql</code> and <code>HydratingResultSet</code>?</p>
<p>You must pick <code>$db_adapter</code> and you will get the paginator by :</p> <pre><code>use Zend\Paginator\Paginator; use Zend\Paginator\Adapter\DbSelect; $sql = new Sql($this-&gt;db); $select = $sql-&gt;select('posts'); new Paginator(new DbSelect($select, $db_adpter)); </code></pre>
Importing packages causes Unicode error in Anaconda <p>In my program when I type: import matplotlib as pt, I get the following error:</p> <pre><code> File "C:\Users\hh\Anaconda3\lib\site-packages\numpy\__config__.py", line 5 blas_mkl_info={'libraries': ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll'], 'library_dirs': ['C:\Users\hh\Anaconda3\\Library\\lib'], 'include_dirs': ['C:\Users\hh\Anaconda3\\Library\\include'], 'define_macros': [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]} ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape </code></pre> <p>Any ideas why this is happening and what I can do to change this?</p> <p>This is the file that it is referring to: </p> <pre><code># This file is generated by C:\Minonda\conda-bld\numpy-1.11_1475607650950\work\numpy-1.11.2\setup.py # It contains system_info results at the time of building this package. __all__ = ["get_info","show"] blas_mkl_info={'libraries': ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll'], 'library_dirs': ['C:\Users\hh\Anaconda3\\Library\\lib'], 'include_dirs': ['C:\Users\hh\Anaconda3\\Library\\include'], 'define_macros': [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]} openblas_lapack_info={} blas_opt_info={'libraries': ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll'], 'library_dirs': ['C:\Users\hh\Anaconda3\\Library\\lib'], 'include_dirs': ['C:\Users\hh\Anaconda3\\Library\\include'], 'define_macros': [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]} lapack_opt_info={'libraries': ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll'], 'library_dirs': ['C:\Users\hh\Anaconda3\\Library\\lib'], 'include_dirs': ['C:\Users\hh\Anaconda3\\Library\\include'], 'define_macros': [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]} lapack_mkl_info={'libraries': ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll'], 'library_dirs': ['C:\Users\hh\Anaconda3\\Library\\lib'], 'include_dirs': ['C:\Users\hh\Anaconda3\\Library\\include'], 'define_macros': [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]} def get_info(name): g = globals() return g.get(name, g.get(name + "_info", {})) def show(): for name,info_dict in globals().items(): if name[0] == "_" or type(info_dict) is not type({}): continue print(name + ":") if not info_dict: print(" NOT AVAILABLE") for k,v in info_dict.items(): v = str(v) if k == "sources" and len(v) &gt; 200: v = v[:60] + " ...\n... " + v[-60:] print(" %s = %s" % (k,v)) </code></pre>
<p>You're missing (several) escape-backslashes in your path strings:</p> <pre><code>'C:\Users\hh\Anaconda3\\Library\\lib' </code></pre> <p>Here python will attempt to interprete <code>\U</code> as the start of a unicode escape sequence (see e.g. <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">https://docs.python.org/2/reference/lexical_analysis.html#string-literals</a>).</p> <p>As you already did in parts of this string, you should replace <code>\</code> with a <code>\\</code>:</p> <pre><code>'C:\\Users\\hh\\Anaconda3\\Library\\lib' </code></pre> <p>or use raw strings:</p> <pre><code>r'C:\Users\hh\Anaconda3\Library\lib' </code></pre> <p><strong>EDIT:</strong> I only now realized, that's a file created by numpy/anaconda not by yourself. So that might be worth a ticket for them I guess...</p>
DoesNotExist at /admin/login/ <pre><code> DoesNotExist at /admin/login/ Site matching query does not exist. Request Method: GET Request URL: https://tehb123.pythonanywhere.com/admin/login/?next=/admin/ Django Version: 1.9.3 Exception Type: DoesNotExist Exception Value: Site matching query does not exist. Exception Location: /usr/local/lib/python3.5/dist-packages/django/db/models/query.py in get, line 387 Python Executable: /usr/local/bin/uwsgi Python Version: 3.5.1 Python Path: ['/var/www', '.', '', '/home/tehb123/.local/lib/python3.5/site-packages', '/var/www', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages', '/home/tehb123/mysite'] Server time: Thu, 13 Oct 2016 05:34:55 +0000 </code></pre> <ul> <li><p>urls</p> <p>from django.conf.urls import url, patterns, include from django.contrib import admin from django.contrib.flatpages import views</p> <p>urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('Mysitez.urls')), # url(r'^pages/', include('django.contrib.flatpages.urls')), ]</p> <p>urlpatterns += [ url(r'^(?P.*/)$', views.flatpage), ]</p></li> <li><p>settings</p> <p>INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.templatetags', 'django.apps', 'django.contrib.sites', 'django.contrib.flatpages', 'Mysitez',</p> <p>]</p></li> </ul>
<h1>The admin site</h1> <p>once you create the project with django version > 1.6 , the admin site will enable django itself. but make sure you have following ["<a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/contrib/admin/</a>"], once you create project , make <code>python manage.py migrate</code> then create the admin user using (<code>python manage.py createsuperuser</code> ). do the run command see the url like ("<a href="http://127.0.0.1:8000/admin/" rel="nofollow">http://127.0.0.1:8000/admin/</a>") you can see the login page</p>
Multithreaded C program error <p>I'm having a problem running my C program. I keep getting the error warning: cast to pointer from integer of different size.. Does anyone have any suggestions to fix this? The program is supposed too design a pid manager. </p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;unistd.h&gt; #include&lt;time.h&gt; #include&lt;pthread.h&gt; #include&lt;semaphore.h&gt; #define MIN_PID 300 #define MAX_PID 5000 #define NUM_THREADS 100 #define YES 0 #define NO 1 sem_t SEM; struct PidTable{ int PID; int isAvailable; }*pId; int allocate_map(){ int i; pId=(struct PidTable *)calloc((MAX_PID-MIN_PID+1),sizeof(struct PidTable)); if(pId==NULL) return -1; pId[0].PID=MIN_PID; pId[0].isAvailable=YES; for( i=1;i&lt;MAX_PID-MIN_PID+1;i++){ pId[i].PID=pId[i-1].PID+1; pId[i].isAvailable=YES; } return 1; } int allocate_pid(){ int i ; for( i=0;i&lt;MAX_PID-MIN_PID+1;i++){ if(pId[i].isAvailable==YES){ pId[i].isAvailable=NO; return pId[i].PID; } } return -1; } void release_pid(int pid){ pId[pid-MIN_PID].isAvailable=YES; } void *processStart(void *id){ //long tid=(long)id; int pid,executionTime; sem_wait(&amp;SEM); pid=allocate_pid(); usleep(10000); sem_post(&amp;SEM); if(pid!=-1){ //printf("Thread %ld runnning....\n",tid); printf("New Process Allocated Pid= %d \n",pid); executionTime=rand()%10; sleep(executionTime); printf("Process %d releasing pid \n",pid); release_pid(pid); } pthread_exit(NULL); } int main(){ allocate_map(); srand(time(NULL)); void *status;int i; int ret=0;pthread_t thread[100]; sem_init(&amp;SEM,0,1); for(i=0;i&lt;NUM_THREADS;i++){ ret=pthread_create(&amp;thread[i],NULL,processStart,(void *)(i+1)); if(ret){printf("Error creating thread\n");exit(1);} } for(i=0; i&lt;NUM_THREADS; i++) { ret = pthread_join(thread[i], &amp;status); if (ret) { printf("ERROR; return code from pthread_join() is %d\n", ret); exit(-1); } } return 0; } </code></pre>
<blockquote> <p>warning: cast to 'void *' from smaller integer type 'int'</p> </blockquote> <p>Refers to the last argument in this call:</p> <pre><code>ret = pthread_create( &amp;thread[i], NULL, processStart, (void *)(i+1) ); </code></pre> <p>Whose prototype is:</p> <pre><code>int pthread_create( pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg ); </code></pre> <p>My guess the problem is you are trying to pass an <code>int</code> instead of an <code>int *</code> via a <code>void *</code>. We can't simply declare an <code>int *</code> and put <code>i + 1</code> into it as we'd end up changing the argument to the threads we've already launched. We'd need to do something like:</p> <pre><code>int args[100]; for(i = 0; i &lt; NUM_THREADS; i++) { args[i] = i + 1; ret = pthread_create(&amp;thread[i], NULL, processStart, &amp;args[i]); </code></pre> <p>Below is my rework of your code to address the above, other little problems and style issues:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;stdbool.h&gt; #include &lt;pthread.h&gt; #include &lt;semaphore.h&gt; #define MIN_PID 300 #define MAX_PID 500 #define NUM_THREADS 100 struct PidTable { int PID; bool isAvailable; } *pId; sem_t SEM; int allocate_map() { pId = calloc(MAX_PID - MIN_PID + 1, sizeof(*pId)); if (pId == NULL) { return -1; } for (int i = 0; i &lt; MAX_PID - MIN_PID + 1; i++) { pId[i].PID = MIN_PID + i; pId[i].isAvailable = true; } return 1; } int allocate_pid() { for (int i = 0; i &lt; MAX_PID - MIN_PID + 1; i++) { if (pId[i].isAvailable) { pId[i].isAvailable = false; return pId[i].PID; } } return -1; } void release_pid(int pid) { pId[pid - MIN_PID].isAvailable = true; } void *processStart(void *id) { sem_wait(&amp;SEM); int pid = allocate_pid(); usleep(10000); sem_post(&amp;SEM); if (pid != -1) { printf("New Process Allocated Pid= %d\n", pid); int executionTime = rand() % 10; sleep(executionTime); printf("Process %d releasing pid\n", pid); release_pid(pid); } else { fprintf(stderr, "Error allocating pid\n"); } pthread_exit(NULL); } int main() { pthread_t threads[NUM_THREADS]; int args[NUM_THREADS]; srand(time(NULL)); if (allocate_map() == -1) { fprintf(stderr, "Error allocating map\n"); return EXIT_FAILURE; } sem_init(&amp;SEM, 0, 1); for (int i = 0; i &lt; NUM_THREADS; i++) { args[i] = i + 1; int return_code = pthread_create(&amp;threads[i], NULL, processStart, &amp;args[i]); if (return_code != 0) { fprintf(stderr, "Error return code from pthread_create is %d\n", return_code); return EXIT_FAILURE; } } for (int i = 0; i &lt; NUM_THREADS; i++) { int return_code = pthread_join(threads[i], NULL); if (return_code != 0) { fprintf(stderr, "Error return code from pthread_join() is %d\n", return_code); return EXIT_FAILURE; } } return EXIT_SUCCESS; } </code></pre>
File's Data keeps getting overwritten by function <p>for some reason I am running into an issue where my function call seems to be overwriting the data read in from the file without me asking it to. I am trying to get the sum of the original list but I keep getting the sum of the squared list. </p> <p><strong>CODE:</strong></p> <pre><code>def toNumbers(strList): for i in range(len(strList)): strList[i] = strList [int(i)] return strList def squareEach(nums): for i in range(len(nums)): nums[i] = eval(nums[i]) nums[i] = nums[i]**2 return nums def sumList(nums): b = sum(nums) return b def main(): file=open("numbers.txt","r").readline().split(" ") print(str(squareEach(file))) print(str(sumList(file))) </code></pre>
<p>Your squareEach function modifies the original list which is passed to it. To see what's going, consider adding a print between your function calls. <code> def main(): file=open("numbers.txt","r").readline().split(" ") print(str(squareEach(file))) print(str(file)) print(str(sumList(file)) </code></p> <p>EDIT: The simplest fix would be to use a different list for storing your square numbers inside squareEach function</p> <pre><code>def squareEach(nums): squares = [] for i in range(len(nums)): num = eval(nums[i]) squares[i] = num**2 return squares </code></pre> <p>There are more efficient ways as suggested in other answers, but in your case, this appears to be the simplest fix.</p>
Search Widget - How to determine if "Enter" was pressed or result was selected? <p>I have a search box which throws up certain auto-suggested values when an address is searched for.</p> <p>Now there are way ways in which a search event is fired:</p> <ol> <li>User starts typing an address (ignores the auto-suggested values) and hits <kbd>Enter</kbd> key</li> <li>User starts typing an address and midway through the process, <strong>selects</strong> a value from the auto-suggested list</li> </ol> <p>In this scenario, is there a way I can figure out whether a selection was made or the <kbd>Enter</kbd> key was pressed in the event handler?</p> <h2>Javascript</h2> <pre><code>var esriMap = new Map("esriMap", { basemap: "topo", center: [-12.4260, 31.3403], zoom: 12 }); var search = new Search({ map: esriMap, }, dom.byId("esriSearch")); search.startup(); search.on("select-result", searchboxResult); // the event handler function searchboxResult(e) { // determine "Enter" key versus "Selection from auto-suggest" } </code></pre>
<p>Ofcourse, there is a way to figure out whether a selection was made or the Enter key was pressed while showing selection on the map.</p> <p>Below is the working code to implement this-</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>require([ "esri/map", "esri/dijit/Search", "dojo/on", "dojo/domReady!" ], function (Map, Search, on) { var map = new Map("map", { basemap: "gray", center: [-120.435, 46.159], // lon, lat zoom: 7 }); var search = new Search({ map: map }, "search"); search.startup(); var isEnter= false; on(search.inputNode, "keypress", function(evt){ isEnter = evt.keyCode == 13; }); search.on("select-result", searchboxResult); function searchboxResult(e) { alert(isEnter?"By Enter Selection": "By Suggestion Selection"); // determine "Enter" key versus "Selection from auto-suggest" } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body, #map { height: 100%; width: 100%; margin: 0; padding: 0; } #search { display: block; position: absolute; z-index: 2; top: 20px; left: 74px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/themes/calcite/dijit/calcite.css"&gt; &lt;link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/themes/calcite/esri/esri.css"&gt; &lt;script src="https://js.arcgis.com/3.18/"&gt;&lt;/script&gt; &lt;body class="calcite"&gt; &lt;div id="search"&gt;&lt;/div&gt; &lt;div id="map"&gt;&lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p> <p><strong><em>Hoping this will help you :)</em></strong></p>
How to solve : "Unsupported class version number[52.0] maximum 51.0, Java1.7"? <p>Can't read </p> <blockquote> <p>[C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\MonoAndroid\v7.0\mono.android.jar] (Can't process class [android/app/ActivityTracker.class] (Unsupported class version number [52.0] (maximum 51.0, Java 1.7)))</p> </blockquote> <p>how to solve this issue..?? </p>
<p>Had this error too. Which JDK Version do you have installed? I had no problems after upgrading it to version 1.8</p> <p>Alright, if somebody else is reading this with the same problem, upgrading ProGuard seems to fix this problem too. Just try that! :)</p>
selenium python webscrape fails after first iteration <p>Im iterating through tripadvisor to save comments(non-translated, original) and translated comments (from portuguese to english). So the scraper first selects portuguese comments to be displayed , then as usual it converts them into english one by one and saves the translated comments in com_, whereas the expanded non-translated comments in expanded_comments.</p> <p>The code works fine with first page but from second page onward it fails to save translated comments. Strangely it just translates only first comment from each of the pages and doesnt even save them.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import time from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC com_=[] expanded_comments=[] date_=[] driver = webdriver.Chrome("C:\Users\shalini\Downloads\chromedriver_win32\chromedriver.exe") driver.maximize_window() from bs4 import BeautifulSoup def expand_reviews(driver): # TRYING TO EXPAND REVIEWS (&amp; CLOSE A POPUP) try: driver.find_element_by_class_name("moreLink").click() except: print "err" try: driver.find_element_by_class_name("ui_close_x").click() except: print "err2" try: driver.find_element_by_class_name("moreLink").click() except: print "err3" def save_comments(driver): expand_reviews(driver) # SELECTING ALL EXPANDED COMMENTS #xpanded_com_elements=driver.find_elements_by_class_name("entry") time.sleep(3) #or i in expanded_com_elements: # expanded_comments.append(i.text) spi=driver.page_source sp=BeautifulSoup(spi) for t in sp.findAll("div",{"class":"entry"}): if not t.findAll("p",{"class":"partial_entry"}): #print t expanded_comments.append(t.getText()) # Saving review date for d in sp.findAll("span",{"class":"recommend-titleInline"}) : date=d.text date_.append(date_) # SELECTING ALL GOOGLE-TRANSLATOR links gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation&gt;.link") # NOW PRINTING TRANSLATED COMMENTS for i in gt: try: driver.execute_script("arguments[0].click()",i) #com=driver.find_element_by_class_name("ui_overlay").text com= driver.find_element_by_xpath(".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']") com_.append(com.text) time.sleep(5) driver.find_element_by_class_name("ui_close_x").click().perform() time.sleep(5) except Exception as e: pass # ITERATING THROIGH ALL 200 tripadvisor webpages and saving comments &amp; translated comments for i in range(200): page=i*10 url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or"+str(page)+"-TAP-Portugal#REVIEWS" driver.get(url) wait = WebDriverWait(driver, 10) if i==0: # SELECTING PORTUGUESE COMMENTS ONLY # Run for one time then iterate over pages try: langselction = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.sprite-date_picker-triangle"))) langselction.click() driver.find_element_by_xpath("//div[@class='languageList']//li[normalize-space(.)='Portuguese first']").click() time.sleep(5) except Exception as e: print e save_comments(driver) </code></pre>
<p>There are 3 problems in your code</p> <ol> <li>Inside method <code>save_comments()</code>, at the <code>driver.find_element_by_class_name("ui_close_x").click().perform()</code>, the method <code>click()</code> of a webelement is not an ActionChain so you cannot call <code>perform()</code>. Therefore, that line should be like this:</li> </ol> <pre><code>driver.find_element_by_class_name("ui_close_x").click() </code></pre> <ol start="2"> <li>Inside method <code>save_comments()</code>, at the <code>com= driver.find_element_by_xpath(".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")</code>, you find the element when it doesn't appear yet. So you have to add wait before this line. Your code should be like this:</li> </ol> <pre><code>wait = WebDriverWait(driver, 10) wait.until(EC.element_to_be_clickable((By.XPATH, ".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']"))) com= driver.find_element_by_xpath(".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']") </code></pre> <ol start="3"> <li>There are 2 buttons which can open the review, one is displayed and one is hidden. So you have to skip the hidden button.</li> </ol> <pre><code>if not i.is_displayed(): continue driver.execute_script("arguments[0].click()",i) </code></pre>
Extending my own controller in Symfony <p>I am creating a webapp that has some common functions. So I figured the easiest way to do this would be to make a base controller and just extend that. So in the base controller I have (similar to):</p> <pre><code>namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class BaseController extends Controller { protected function dosomething($data) { return $data; } } </code></pre> <p>And then in the default controller:</p> <pre><code>namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class DefaultController extends BaseController { /** * @Route("/", name="homepage") */ public function indexAction() { $data = "OK"; $thedata = $this-&gt;dosomething($data); } } </code></pre> <p>And then for the Admin Controller: namespace AppBundle\Controller;</p> <pre><code>use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class AdminController extends BaseController { /** * @Route("/", name="homepage") */ public function indexAction() { $data = "OK"; $thedata = $this-&gt;dosomething($data); } } </code></pre> <p>However, I am getting errors like "Compile Error: Access level to AppBundle\Controller\AdminController::dosomething() must be protected (as in class AppBundle\Controller\BaseController) or weaker", not just when I load the admin controller function, but default as well. When I stop the admin controller extending base controller, this error goes (seems to work on default but not admin).</p> <p>I'm guessing somewhere I have to let Symfony know that the admin controller is safe or something?</p>
<p>It has nothing to do with Symfony, it's PHP.</p> <p>Obviously, you're trying to redefine <code>dosomething</code> method in your Admin Controller, and trying to make this method private.</p> <p>It's not allowed. It may be either <code>protected</code> or <code>public</code>.</p> <p>It's principle of OOP. Because if you would have a class <code>SubAdminController</code>, then instance of it would be also instance of both <code>AdminController</code> and <code>BaseController</code>. And PHP must definitely know if the method <code>dosomething</code> from parent class is accessible from <code>SubAdminController</code>.</p>
How can i use multiple url eg. www.example.com,www.example1.com,www.example2.com, to point same project directory? <p>I want to use different view along with data for different URL . For example use view1, view1, view2 for www.example.com, www.example1.com and www.site2.example.com respectively.I have managed this making server alias in wamp. How can i do this in real hosting. e.g my registered domain is www.example.com</p>
<p>When you create URLs like "Site1.example.com" or "site2.example.com", you are effectively creating sub-domains on the server. Each sub-domain require separate deployment/installation (unless, you have enabled wildcard setting in sub-domain where all the domains are pointing to single sub-domain/address).</p>
Angular2 router with param reload page change get CSS file directory <p>Normally if I click link on home link to detail link, like <code>&lt;a routerLink="/detail/{{record.TA001}}"&gt;</code>,it work well and css file got very well.</p> <p>As only I refresh this detail page, like <code>localhost:3000/detail/0006</code> it got data ok, but get CSS file change the directory to the detail instead root directory, could not get the CSS file. My detail component is in <code>app/content</code> directory.</p> <p><img src="https://i.stack.imgur.com/BxrdM.jpg" alt="enter image description here"></p> <p>My <code>index.html</code> and CSS file in project root directory. router :</p> <pre><code>const appRoutes: Routes = [ { path: 'contact', component: Contactcomponent }, { path: 'detail/:id', component: Detailcomponent }, { path: '', component: Contentcomponent } </code></pre> <p><em>My project directory is like this:</em></p> <p><img src="https://i.stack.imgur.com/ap4Eh.jpg" alt="enter image description here"></p>
<p>i have known how to resolve this problem ,just router directive /detail/0005 change /0005, it woke fine . i think it was if router for root so you just can use one level just fine .it could not use two level approch , if u router not for root ,it can use it .</p>
Getting improper array in the recursive function for generating a random number <p>I have one requierment in which it should generate two to three random numbers whose summation should not have a carry over. I have made the below code with some more reference from the stackoverflow but I am getting some empty arrays. The flow is working perfect. </p> <p>I just need 2 digits numbers whose summation should not be carryover. like 25 +24 = 49 and not 25 + 25 which provides a carry over 1.</p> <pre><code>function print_questions1($i){ if($i &lt; 3){ $m = 1; $n = 9; $number1 = rand($m,$n); $number2 = rand($m,$n); if (($number1+$number2)&lt;10) { ${'final_num1_'.$i} = $number1; ${'final_num2_'.$i} = $number2; ${'final_num3_'.$i} = 0; $final_array = array( 'number1_'.$i=&gt; $number1, 'number2_'.$i =&gt; $number2, 'number3_'.$i =&gt; 0 ); return $final_array; } else { $this-&gt;print_questions1($i); } } elseif ($i &gt; 2 &amp;&amp; $i &lt; 7) { $m = 10; $n = 99; $number1 = rand($m,$n); $number2 = rand($m,$n); $value1 = str_split($number1,1); $value2 = str_split($number2,1); if (($value1[0]+$value2[0])&lt;9 &amp;&amp; ($value1[1]+$value2[1])&lt;9) { ${'final_num1_0_'.$i} = $value1[0]; ${'final_num1_1_'.$i} = $value1[1]; ${'final_num2_0_'.$i} = $value2[0]; ${'final_num2_1_'.$i} = $value2[1]; ${'final_num3_0_'.$i} = 0; ${'final_num3_1_'.$i} = 0; $final_array = array( 'number1_0_'.$i=&gt; ${'final_num1_0_'.$i}, 'number1_1_'.$i=&gt; ${'final_num1_1_'.$i}, 'number2_0_'.$i=&gt; ${'final_num2_0_'.$i}, 'number2_1_'.$i=&gt; ${'final_num2_1_'.$i}, 'number3_0_'.$i=&gt; 0, 'number3_1_'.$i=&gt; 0 ); return $final_array; } else { $this-&gt;print_questions1($i); } } elseif($i &gt; 6 &amp;&amp; $i &lt; 10 ){ $m = 10; $n = 99; $number1 = rand($m,$n); $number2 = rand($m,$n); $number3 = rand($m,$n); $value1 = str_split($number1,1); $value2 = str_split($number2,1); $value3 = str_split($number3,1); if (($value1[0]+$value2[0]+$value3[0])&lt;9 &amp;&amp; ($value1[1]+$value2[1]+$value3[1])&lt;9) { ${'final_num1_0_'.$i} = $value1[0]; ${'final_num1_1_'.$i} = $value1[1]; ${'final_num2_0_'.$i} = $value2[0]; ${'final_num2_1_'.$i} = $value2[1]; ${'final_num3_0_'.$i} = $value3[0]; ${'final_num3_1_'.$i} = $value3[1]; $final_array = array( 'number1_0_'.$i=&gt; ${'final_num1_0_'.$i}, 'number1_1_'.$i=&gt; ${'final_num1_1_'.$i}, 'number2_0_'.$i=&gt; ${'final_num2_0_'.$i}, 'number2_1_'.$i=&gt; ${'final_num2_1_'.$i}, 'number3_0_'.$i=&gt; ${'final_num3_0_'.$i}, 'number3_1_'.$i=&gt; ${'final_num3_1_'.$i} ); return $final_array; } else { $this-&gt;print_questions1($i); } } } function print_questions($question_type) { $data = array(); for ($i=0; $i &lt;10 ; $i++) { if ($i &lt; 3) { $value = $this-&gt;print_questions1($i); array_push($data, $value); }elseif ($i &gt; 2 &amp;&amp; $i &lt; 7 ) { $value = $this-&gt;print_questions1($i); array_push($data, $value); }else { $value = $this-&gt;print_questions1($i); array_push($data, $value); } } </code></pre> <p>Output of the above function gives few empty values like the below array</p> <pre><code>Array ( [0] =&gt; [1] =&gt; Array ( [number1_1] =&gt; 1 [number2_1] =&gt; 2 [number3_1] =&gt; 0 ) [2] =&gt; [3] =&gt; [4] =&gt; [5] =&gt; [6] =&gt; [7] =&gt; Array ( [number1] =&gt; 82 [number2] =&gt; 83 [number3] =&gt; 48 ) [8] =&gt; Array ( [number1] =&gt; 31 [number2] =&gt; 46 [number3] =&gt; 39 ) [9] =&gt; Array ( [number1] =&gt; 25 [number2] =&gt; 13 [number3] =&gt; 90 ) ) </code></pre> <p>Please let me know my mistake or where I am lagging behind.</p>
<p>I made a mistake in the else part I forgot to return the function. Problem solved</p> <pre><code> function print_questions1($i){ if($i &lt; 3){ $m = 1; $n = 9; $number1 = rand($m,$n); $number2 = rand($m,$n); if (($number1+$number2)&lt;10) { ${'final_num1_'.$i} = $number1; ${'final_num2_'.$i} = $number2; ${'final_num3_'.$i} = 0; $final_array = array( 'number1_'.$i=&gt; $number1, 'number2_'.$i =&gt; $number2, 'number3_'.$i =&gt; 0 ); return $final_array; } else { return $this-&gt;print_questions1($i); } } elseif ($i &gt; 2 &amp;&amp; $i &lt; 7) { $m = 10; $n = 99; $number1 = rand($m,$n); $number2 = rand($m,$n); $value1 = str_split($number1,1); $value2 = str_split($number2,1); if (($value1[0]+$value2[0])&lt;9 &amp;&amp; ($value1[1]+$value2[1])&lt;9) { ${'final_num1_0_'.$i} = $value1[0]; ${'final_num1_1_'.$i} = $value1[1]; ${'final_num2_0_'.$i} = $value2[0]; ${'final_num2_1_'.$i} = $value2[1]; ${'final_num3_0_'.$i} = 0; ${'final_num3_1_'.$i} = 0; $final_array = array( 'number1_0_'.$i=&gt; ${'final_num1_0_'.$i}, 'number1_1_'.$i=&gt; ${'final_num1_1_'.$i}, 'number2_0_'.$i=&gt; ${'final_num2_0_'.$i}, 'number2_1_'.$i=&gt; ${'final_num2_1_'.$i}, 'number3_0_'.$i=&gt; 0, 'number3_1_'.$i=&gt; 0 ); return $final_array; } else { return $this-&gt;print_questions1($i); } } elseif($i &gt; 6 &amp;&amp; $i &lt; 10 ){ $m = 10; $n = 99; $number1 = rand($m,$n); $number2 = rand($m,$n); $number3 = rand($m,$n); $value1 = str_split($number1,1); $value2 = str_split($number2,1); $value3 = str_split($number3,1); if (($value1[0]+$value2[0]+$value3[0])&lt;9 &amp;&amp; ($value1[1]+$value2[1]+$value3[1])&lt;9) { ${'final_num1_0_'.$i} = $value1[0]; ${'final_num1_1_'.$i} = $value1[1]; ${'final_num2_0_'.$i} = $value2[0]; ${'final_num2_1_'.$i} = $value2[1]; ${'final_num3_0_'.$i} = $value3[0]; ${'final_num3_1_'.$i} = $value3[1]; $final_array = array( 'number1_0_'.$i=&gt; ${'final_num1_0_'.$i}, 'number1_1_'.$i=&gt; ${'final_num1_1_'.$i}, 'number2_0_'.$i=&gt; ${'final_num2_0_'.$i}, 'number2_1_'.$i=&gt; ${'final_num2_1_'.$i}, 'number3_0_'.$i=&gt; ${'final_num3_0_'.$i}, 'number3_1_'.$i=&gt; ${'final_num3_1_'.$i} ); return $final_array; } else { return $this-&gt;print_questions1($i); } } } </code></pre>
Filtering duplicate records from temporary table from `regexp_split_to_table` <p>I have got the following table datas.. Table name is category</p> <pre><code>| ID | CATEGORY | +----------------+--------------------------+ | 1 | Apple,Orance-........... | | 2 | Apple,Grapes-........... | | 3 | Juice,Apple,Cucumber-... | </code></pre> <p>Im trying to create the temporary table by parsing comma seperated values as individual rows as follows </p> <pre><code>| ID | split_categori +-------------+------------------- | 1 | Apple | 2 | Orange | 3 | Grapes | 4 | Juice | 5 | Cucumber </code></pre> <p>Im using the following code to do that.</p> <pre><code>SELECT CATEGORI.ID, regexp_split_to_table(CATEGORI.CATEGORY, E',') AS split_categori FROM CATEGORI; </code></pre> <p><code>CATEGORI</code> is the table name. <code>ID</code> and <code>CATEGORY</code> are column names</p> <p>It can successfully be able to get all comma seperated values as individual rows but then it is not filtering the duplicate elements so my new temporary table <code>split_categori</code> consists of duplicate records rows. </p> <p>How can I be able to filter these duplicate records? Is there any ways to do that using query or should I rely on ResultSet?</p>
<p>As you don't seem to care about the ID you pick for duplicate categories, you can use:</p> <pre><code>select min(c.id) as id, t.name from categori c cross join regexp_split_to_table(c.category, E',') AS t(name) group by t.name order by 1; </code></pre> <p>Note that using a set returning function in the <code>select</code> list is discouraged and should not be used any more, that's why I moved <code>regexp_split_to_table()</code> into the <code>from</code> clause.</p> <p>But <code>regexp_split_to_table()</code> is an extremely slow function and should only be used if you <em>really</em> need to split on a regular expression. Using <code>string_to_array()</code> would be <strong>much</strong> more efficient:</p> <pre><code>select min(c.id) as id, t.name from categori c cross join unnest(string_to_array(c.category, ',')) AS t(name) group by t.name order by 1 </code></pre> <p>Here is a running example: <a href="http://rextester.com/YSHT62551" rel="nofollow">http://rextester.com/YSHT62551</a></p>
White Spaces can't store in a variable <p>I'm try to set feature in replace(-(Hyphen)). But it could not be set as feature value in replace.</p> <pre><code>DECLARE RE_HyphenSpace(STRING replace); DECLARE Replace_HyphenSpace; RETAINTYPE(SPACE); SPACE @NEWHYPHEN SPACE{-&gt; MARK(RE_HyphenSpace,1,3),MARK(Replace_HyphenSpace,2,2)}; RETAINTYPE; BLOCK(foreach) RE_HyphenSpace{} { STRING hyphenrepl; Replace_HyphenSpace{-&gt;MATCHEDTEXT(hyphenrepl)}; RE_HyphenSpace{-&gt;RE_HyphenSpace.replace=hyphenrepl}; } </code></pre>
<p>The block is not executed because RE_HyphenSpace annotations are not visible because SPACE annotations are invisible again after the RETAINTYPE. You need to remove or move the <code>RETAINTYPE;</code> line, e.g., to the end of the block.</p> <p><em>DISCLAIMER: I am a developer of UIMA Ruta</em></p>
XSD from XML with data validations <p>I have a simple xml,</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Metadata&gt; &lt;Data Name="Title" Value="This is a new title." /&gt; &lt;Data Name="Licensing_Window_Start" Value="2016-09-01" /&gt; &lt;Data Name="Licensing_Window_End" Value="2016-09-14" /&gt; &lt;Data Name="Preview_Period" Value="60" /&gt; &lt;/Metadata&gt; </code></pre> <p>I'm able to generate xsd online for the above xml like this,</p> <pre><code>&lt;xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt; &lt;xs:element name="Metadata"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="Data" maxOccurs="unbounded" minOccurs="0"&gt; &lt;xs:complexType&gt; &lt;xs:simpleContent&gt; &lt;xs:extension base="xs:string"&gt; &lt;xs:attribute type="xs:string" name="Name" use="required"/&gt; &lt;xs:attribute type="xs:string" name="Value" use="required"/&gt; &lt;/xs:extension&gt; &lt;/xs:simpleContent&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre> <p>But what I'm trying to validate is, for <code>&lt;Data&gt;</code> tag, for the attribute <code>Name</code> the value <code>Title</code> is mandatory and need to define minlength and maxlength for the value of <code>Value</code>.</p> <p>Is it possible to create the xsd with the type of validations I mentioned above?</p>
<p>Yes, it's possible, but it may depend on the XML Schema version you're using.</p> <p><strong>Attribute Name the value Title is mandatory</strong></p> <p>This can not be achieved with XSD 1.0, but with XSD 1.1 you can rely on assertions (<code>&lt;xs:assert&gt;</code>):</p> <pre><code>&lt;xs:assert test="Data[@Name = 'Title']"/&gt; </code></pre> <p>can be added in the <code>complexType</code> defining the content model of <code>&lt;Metadata&gt;</code>; an error will be raised if no <code>&lt;Data&gt;</code> with <code>Name="Title"</code> is found.</p> <p><strong>Setting minlength/maxlength for <code>'Value'</code></strong></p> <p>You need to define and use a type with an <code>&lt;xs:restriction&gt;</code> (even if you could also embed the following snippet as a child of the <code>&lt;xs:attribute name="Value"&gt;</code>:</p> <pre><code> &lt;xs:simpleType name="value-attr"&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:minLength value="1"/&gt; &lt;xs:maxLength value="200"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; </code></pre> <p>and change your declaration of the attribute like so:</p> <pre><code>&lt;xs:attribute type="value-attr" name="Value" use="required"/&gt; </code></pre> <hr> <p>Finally you'll end up with the following schema:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1"&gt; &lt;xs:element name="Metadata"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="Data" maxOccurs="unbounded" minOccurs="0"&gt; &lt;xs:complexType&gt; &lt;xs:simpleContent&gt; &lt;xs:extension base="xs:string"&gt; &lt;xs:attribute type="xs:string" name="Name" use="required"/&gt; &lt;xs:attribute type="value-attr" name="Value" use="required"/&gt; &lt;/xs:extension&gt; &lt;/xs:simpleContent&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;xs:assert test="Data[@Name = 'Title']"/&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:simpleType name="value-attr"&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:minLength value="1"/&gt; &lt;xs:maxLength value="200"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;/xs:schema&gt; </code></pre>
How to login with a user with role userAdmin in mongodb <p>I have <strong>mongod</strong> server up and running as a service on ubuntu 14.04, i started <strong>mongo</strong> shell and created a user.</p> <pre><code>db.createUser( { user: "testAdmin", pwd: "12345678", roles: [ { role: "userAdmin", db: "students" } ] } ) </code></pre> <p>after that I changed edit the <strong>mongod.conf</strong> and set <strong>auth=true</strong> and restarted the <strong>mongod</strong> server as a service.</p> <p>After all this, when I want to start the <strong>mongo shell</strong> with user <strong>testAdmin</strong> .</p> <pre><code>mongo -u testAdmin -p 12345678 --authenticationDatabase students </code></pre> <p>But I am not able to login and it is giving me error.</p> <pre><code>MongoDB shell version: 3.2.10 connecting to: 127.0.0.1:25018/test 2016-10-13T05:56:27.500+0000 W NETWORK [thread1] Failed to connect to 127.0.0.1:25018, reason: errno:111 Connection refused 2016-10-13T05:56:27.500+0000 E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:25018, connection attempt failed : </code></pre> <p>First when I am specifying database <strong>students</strong> why it is trying to connect to <strong>test</strong>? Second I know that userAdmin role in mongodb is not for read/write in database with userAdmin I can only manage user roles. But to manage other users i still need to login in mongo shell.</p> <p>It is working when I turn off the auth in mongod.conf, so other things are fine, only authentication is not working.</p>
<blockquote> <blockquote> <p>First when I am specifying database students why it is trying to connect to test? </p> </blockquote> </blockquote> <p>You are not specifying the database (students) you want to connect to here. </p> <p>The <code>--authenticationDatabase</code> is used to specify the database where the user had been created and which is used for the authentication process.</p> <p>You should also specify students as the db option you want to connect to. If you omit it, the shell automatically tries to connect to <code>test</code> database:</p> <p><code>mongo students -u testAdmin -p 12345678 --authenticationDatabase students</code></p> <p>Note the addition of <code>students</code> just after <code>mongo</code>.</p> <p>This is assuming the user has been created in the <code>students</code> database (and not <code>admin</code> or other). Note that in that case the <code>db</code> declaration within <code>role</code> is redundant:</p> <p><code>roles: [ { role: "userAdmin", db: "students" } ]</code></p> <p>could have also been specified as:</p> <p><code>roles: [ "userAdmin" ]</code></p>
WPF TextBlock TextTrimming Not Working Inside a Grid With GridSplitter <p>I have the following structure in my XAML code:</p> <pre><code> &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="200" MinWidth="200"/&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="*" MinWidth="100"/&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="Auto" MinWidth="150"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;ListBox ItemsSource="{Binding MessagesCollectionView}" Margin="0"&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel Orientation="Vertical"&gt; &lt;Label Foreground="Black" FontSize="14"&gt; &lt;TextBlock Text="{Binding Title}" TextTrimming="CharacterEllipsis"/&gt; &lt;/Label&gt; &lt;Label Foreground="Gray" FontSize="12"&gt; &lt;TextBlock Text="{Binding Content}" TextTrimming="CharacterEllipsis"/&gt; &lt;/Label&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; &lt;GridSplitter Width="5" Grid.Column="1" HorizontalAlignment="Stretch"/&gt; &lt;!--More stuff here......--&gt; </code></pre> <p>I made the XAML code short here or it just clutter the whole question. I have 5 columns, on this order, left to right: <code>ListBox</code>, <code>GridSplitter</code>, <code>RichTextBox</code>, <code>GridSplitter</code>, <code>ListView</code>. I am just showing the first two columns since the rest is just about the same.</p> <p>When I load my program the <code>TextBoxes</code> aren't showing any Ellipsis, never. I even tried giving the <code>ListBox</code> a fixed size. </p> <p><strong>Does anyone knows how to fix Ellipsis to be shown?</strong> I believe this might be involved on how the controls inside a <code>Grid</code> are informed about their sizes when there is a <code>GridSplitter</code>.</p> <p>I am aiming for a UI where the middle view has a <code>* width</code> and the left and right ones are fixed size at first but can be stretched if the user wants to.</p> <hr> <h2>EDIT:</h2> <h1>This is what I want:</h1> <p><a href="https://i.stack.imgur.com/oRaQz.png" rel="nofollow"><img src="https://i.stack.imgur.com/oRaQz.png" alt="Text with Ellipsis"></a></p> <h1>This is what I am getting:</h1> <p><a href="https://i.stack.imgur.com/OiGRG.png" rel="nofollow"><img src="https://i.stack.imgur.com/OiGRG.png" alt="Text without Ellipsis"></a></p>
<p>I'm not sure, if you've found an solution yet, but I think the following could help you (see my comments inline):</p> <pre><code>&lt;Window x:Class="SO40013780.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:SO40013780" mc:Ignorable="d" Title="MainWindow" Height="350" Width="200"&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition /&gt; &lt;ColumnDefinition Width="Auto" /&gt; &lt;ColumnDefinition /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;ListBox Name="TheList" Grid.Column="0"&gt; &lt;ListBox.Template&gt; &lt;!-- Override the default controll template for the listbox --&gt; &lt;ControlTemplate TargetType="{x:Type ListBox}"&gt; &lt;Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="True"&gt; &lt;!-- OBS: HorizontalScrollBarVisibility="Disabled" is the CHANGE --&gt; &lt;ScrollViewer Focusable="False" Padding="{TemplateBinding Padding}" HorizontalScrollBarVisibility="Disabled"&gt; &lt;ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /&gt; &lt;/ScrollViewer&gt; &lt;/Border&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsEnabled" Value="False"&gt; &lt;Setter Property="Background" TargetName="Bd" Value="White"/&gt; &lt;Setter Property="BorderBrush" TargetName="Bd" Value="#FFD9D9D9"/&gt; &lt;/Trigger&gt; &lt;MultiTrigger&gt; &lt;MultiTrigger.Conditions&gt; &lt;Condition Property="IsGrouping" Value="True"/&gt; &lt;Condition Property="VirtualizingPanel.IsVirtualizingWhenGrouping" Value="False"/&gt; &lt;/MultiTrigger.Conditions&gt; &lt;Setter Property="ScrollViewer.CanContentScroll" Value="False"/&gt; &lt;/MultiTrigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/ListBox.Template&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding}" TextTrimming="CharacterEllipsis" Background="Yellow" Foreground="Red" /&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; &lt;GridSplitter Width="5" HorizontalAlignment="Center" VerticalAlignment="Stretch" Grid.Column="1" /&gt; &lt;Border Background="Blue" Grid.Column="2" /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>It has nothing to do with the colums and splitters as I thought in the first place. </p> <p>The magic in the above xaml is the HorizontalScrollBarVisibility="Disabled" on the scroll viewer in the template. With this setting horizontal scrolling in the listbox is disabeled, and therefore the text trimming in the inline text blocks should take over when the listbox becomes narrower than the text in the items.</p> <p><a href="https://i.stack.imgur.com/xbRjr.png" rel="nofollow"><img src="https://i.stack.imgur.com/xbRjr.png" alt="enter image description here"></a></p>
UWP Webview inside Scrollerview <p>I'm developing my first UWP app and I need some help. </p> <p>I have a Webview inside a Scrollerview in XAML and I'm using the webview NavigateToString() method to load some strings in HTML format. The problem is when I put the Webview inside a Scrollerview, either the Webview itself is not visible or the strings aren't loaded or both.</p> <p>I can confirm that the NavigateToString() method works fine with my strings because if I put the WebView outside the Scrollerview, I can see them. I've tried to use <a href="https://github.com/MyToolkit/MyToolkit/wiki/ScrollableHtmlView" rel="nofollow">ScrollableHtmlView</a> but this has some problems with bullets and numbering. </p> <p>The reason I'm using a Webview inside a ScrollerView is because I wanted to have an Image on top of the WebView and have them scroll together. </p> <p>Any help would be really appreciated. Thanks.</p>
<p>I tried to reproduce your issue to put a <code>WebView</code> inside a <code>ScrollerView</code> directly as you described like follows but I cannot reproduce:</p> <pre><code>&lt;ScrollViewer&gt; &lt;WebView Source="http://microsoft.com" x:Name="WebViewControl" &gt;&lt;/WebView&gt; &lt;/ScrollViewer&gt; </code></pre> <p>But I found I can reproduce your issue with code like follows:</p> <pre><code> &lt;StackPanel&gt; &lt;Image Source="Assets/caffe1.jpg" Stretch="None" &gt;&lt;/Image&gt; &lt;WebView Source="http://microsoft.com" x:Name="WebViewControl" &gt;&lt;/WebView&gt; &lt;/StackPanel&gt; </code></pre> <p>For this scenario, I resolved the issue which webview cannot visible by adding the <a href="https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.frameworkelement.minheight.aspx" rel="nofollow"><code>MinHeight</code></a> property of <a href="https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.webview.aspx" rel="nofollow">WebView</a> like follows:</p> <pre><code>&lt;WebView Source="http://microsoft.com" x:Name="WebViewControl" MinHeight="400"&gt;&lt;/WebView&gt; </code></pre> <p>If you try to get the <code>ActualHeight</code> in your scenario after the <code>WebView</code> navigation completed by the following code, you will find the result may be 0, which may be the reason the <code>WebView</code> cannot be visible. Since there is one more controls inside one container and we don't set height for these controls, height will be calculated automatically for each control. The height is set automatically by the content of the control. <code>WebView</code> need time to load content which may lead issues with height calculating. </p> <pre><code>WebViewControl.NavigationCompleted += WebViewControl_NavigationCompleted; private void WebViewControl_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args) { System.Diagnostics.Debug.WriteLine("Actual height of webview:" + WebViewControl.ActualHeight); } </code></pre> <p>By the way, if you want to set the height depended on the content you can reference <a href="http://stackoverflow.com/questions/29127890/windows-store-webview-rendered-html-size">this thread</a>.</p>
Throw error of TypeError:null is not an object (evaluating "$("body").append") while appending html content using jquery which is dynamically injected <p>I am developing safari extension and dynamically injecting the jquery and jqueryui as per my requirement . and after successfully injected and loaded i am trying to append html content to it. it throws me this kind of error.</p> <p><strong>TypeError: null is not an object (evaluating '$("body").append')</strong></p> <p>here is my function which inject the script after page is loaded</p> <pre><code>function injectFiles(files){ var filesLoaded = 0; for(type in files){ if(type=="css"){ files[type].forEach(function(v,k){ var linkTag = document.createElement('link'); linkTag.setAttribute("rel", "stylesheet"); linkTag.setAttribute("type", "text/css"); linkTag.setAttribute("href", safari.extension.baseURI +"Scripts/"+v); document.body.appendChild(linkTag); linkTag.onload = function(){ filesLoaded++; }; }); }else if(type == "js"){ files[type].forEach(function(v,k){ var scriptTag = document.createElement('script'); scriptTag.src = safari.extension.baseURI +"Scripts/"+ v; document.body.appendChild(scriptTag); scriptTag.onload = function(){ filesLoaded++; }; }); } } var interval = setInterval(function(){ if(filesLoaded == files.totalFiles){ clearInterval(interval); showDialog(); } },100); } </code></pre> <p>function to append html content</p> <pre><code>function showDialog(){ $("body").append( '&lt;div id="dialog-confirm" title="Question from university tool"&gt;&lt;p&gt;&lt;span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"&gt;&lt;/span&gt;Is this the right login page for your school?&lt;/p&gt;&lt;/div&gt;&lt;div id="dialog-form" title="Please enter your University URL"&gt;&lt;input type="text" size=60 name="txtUniversityUrl" id="txtUniversityUrl" value="" class="text ui-widget-content ui-corner-all"&gt;&lt;/div&gt;'); } </code></pre>
<p>Created a Working Example that works in FireFox and tested in Safari on Windows. I can test on a Mac later.</p> <p>Example: <a href="https://jsfiddle.net/Twisty/nt0c320p/7/" rel="nofollow">https://jsfiddle.net/Twisty/nt0c320p/7/</a></p> <p><strong>JavaScript</strong></p> <pre><code>var cssnum = document.styleSheets.length; var jsnum = document.scripts.length; function injectFiles(files) { var filesLoaded = 0; var i = 0; for (type in files) { if (type == "css") { //files[type].forEach(function(v, k) { for (i = 0; i &lt; files[type].length; i++) { var linkTag = document.createElement('link'); linkTag.setAttribute("rel", "stylesheet"); linkTag.setAttribute("type", "text/css"); //linkTag.setAttribute("href", safari.extension.baseURI + "Scripts/" + v); linkTag.setAttribute("href", files[type][i]); document.head.appendChild(linkTag); //linkTag.onload = function() { if (cssnum &lt; document.styleSheets.length) { filesLoaded++; }; cssnum = document.styleSheets.length; } } else if (type == "js") { //files[type].forEach(function(v, k) { for (i = 0; i &lt; files[type].length; i++) { var scriptTag = document.createElement('script'); //scriptTag.src = safari.extension.baseURI + "Scripts/" + v; scriptTag.src = files[type][i]; document.head.appendChild(scriptTag); //scriptTag.onload = function() { if (jsnum &lt; document.scripts.length) { filesLoaded++; }; jsnum = document.scripts.length; } } } console.log("Files Loaded: " + filesLoaded); var interval = setInterval(function() { if (filesLoaded == files.totalFiles) { clearInterval(interval); showDialog(); } }, 100); } function showDialog() { var diag1 = $("&lt;div&gt;", { id: "dialog-confirm", title: "Question from university tool" }); diag1.html('&lt;p&gt;&lt;span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"&gt;&lt;/span&gt;Is this the right login page for your school?&lt;/p&gt;'); var diag2 = $("&lt;div&gt;", { id: "dialog-form", title: "Please enter your University URL" }); diag2.html('&lt;input type="text" size=60 name="txtUniversityUrl" id="txtUniversityUrl" value="" class="text ui-widget-content ui-corner-all"&gt;'); $("body").append(diag1).append(diag2); diag1.dialog({ autoOpen: true, buttons: [{ text: "Yes", click: function() { $(this).dialog("close"); diag2.dialog("open"); } }, { text: "No", click: function() { $(this).dialog("close"); } }] }); diag2.dialog({ autoOpen: false, width: "75%" }); } var myFiles = { "css": [ "https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" ], "js": [ "https://code.jquery.com/jquery-1.12.4.js", "https://code.jquery.com/ui/1.12.1/jquery-ui.js" ], totalFiles: 3 }; injectFiles(myFiles); </code></pre> <p>Based on my research, Safari does not fire events when new items are loaded, but does update the <code>document.styleSheets</code> and <code>document.scripts</code> count. So I adjusted the script to look for this activity and update <code>filesLoaded</code> when this count grows.</p> <p>For my testing, I did not have access to your local files, so I called in jQuery and jQuery UI files from CDNs. I also added a test object, <code>myFiles</code>, containing the URLs for those files.</p> <p>Now that the jQuery files are loaded, we can make use of them to create the Dialog elements. Appending the raw HTML to the body might work out, yet I find it better to build the elements in jQuery, append them, and then initialize <code>dialog()</code>. I made some guesses at how you might want them to work.</p> <p>Let me know if you have questions.</p>
How to Improve TEXT_DETECTION of Google Vision API for specific language <p>I am interested in TEXT_DETECTION of Google Vision API, it works impressively. But it seems that TEXT_DETECTION only gives exactly result when the text is in English. In my case, i want to use TEXT_DETECTION in a quite narrow context, for example detection text on ads banners in specific language (in Vietnamese for my case). Can i train the machine on my own data collection to get more exactly result? And how to implement this? </p> <p>Beside TEXT_DETECTION of Google Vision API, Google also has Google's Optical Character Recognition (OCR) software using dependencies of Tesseract. As i known, they have different algorithms to detect text. I used both Google Docs and TEXT_DETECTION of Google Vision API to read text (in Vietnamse) from a picture. Google Docs gave a good result but Vision API didn't. Why Google Vision API does not inherit advantages of Google OCR?</p> <p><strong>I want to say something more about Google Vision API Text Detection, maybe any Google Expert here and can read this</strong>. As Google announced, their TEXT_DETECTION was fantastic: "<em>Even though the words in this image were slanted and unclear, the OCR extracts the words and their positions correctly. It even picks up the word "beacon" on the presenter's t-shirt</em>". But for some of my pics, what happened was really funny. For example with <a href="http://rongbay2.vcmedia.vn/thumb_max/up_new/2012/10/01/521383/201210095217_sam_2028.jpg" rel="nofollow">this pic</a>, even the words "Kem Oxit" are very big in center of pic, it was not recognized. Or in <a href="http://rongbay2.vcmedia.vn/thumb_max/up_new/2012/10/01/521383/201210095204_sam_2026.jpg" rel="nofollow">this pic</a>, the red text "HOA CHAT NGOC VIET" in center of pic was not recognized too. There must be something wrong with the text detection algorithm. </p>
<p>Did you experiment with LanguageHints (<a href="https://cloud.google.com/vision/reference/rest/v1/images/annotate#imagecontext" rel="nofollow">link to documentation</a>)?</p> <p>Vietnamese is in the list of <a href="https://cloud.google.com/translate/v2/translate-reference#supported_languages" rel="nofollow">supported languages</a>, if the text is always in Vietnamese, this should improve the quality of text detection.</p> <p>If this wouldn't help, you cannot improve the quality of text detection by giving it your own training examples.</p>
how to call controller method from javascript in rails <p>I am new in ruby on rails, I want to call controller method from javascript with multiple parameters. I tried but didn't got output. <strong>_applied_candidate.html.erb</strong></p> <pre><code>&lt;p&gt;Next Status: &lt;span class="fontstyle3"&gt; &lt;select name="workflow_id" id="workflow_id" onchange="updateItem('workflow_id', &lt;%= applied_candidate.id %&gt;, &lt;%= job.id %&gt;)"&gt; &lt;% data.each do | d | %&gt; &lt;option value=""&gt;Please select&lt;/option&gt; &lt;% d.next_step.split(',').each do | s | %&gt; &lt;% data1 = CandidateWorkFlow.select(:workflow_step).where("step_id = ?",s) %&gt; &lt;% data1.each do |l| %&gt; &lt;option value=&lt;%= s%&gt;&gt; &lt;%= l.workflow_step %&gt; &lt;/option&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;/select&gt; &lt;/span&gt; &lt;/p&gt; &lt;script type="text/javascript"&gt; function updateItem(item, userID, jobID) { var e = document.getElementById(item); var val = e.options[e.selectedIndex].value; new Ajax.Request('/jobs/update_work_flow', { method: 'post', parameters: { selected_id: item, u_id: userID, job_id: jobID } }); };&lt;/script&gt; </code></pre> <p><strong>routes.rb</strong></p> <pre><code>resources :jobs do get :update_work_flow, on: :collection </code></pre> <p>end</p> <p><strong>jobs_controller.rb</strong></p> <pre><code>def update_work_flow redirect_to root_path </code></pre> <p>end</p> <p>How to check controller method called or not</p>
<p>On routes.rb, Please make the following change,</p> <pre><code>resources :jobs do post :update_work_flow, on: :collection </code></pre> <p>In Js, you have specified as 'post' method, while in routes, you have specified a 'get' method. Try changing to post and the code should work.</p>
How to redirect guest to login page, after redirect back after login in laravel 5.2 <p>I use php artisan <code>make:auth</code> function in Laravel 5.2.</p> <p>I want to redirect guest to login page if guest clicks link that only for user not guest.</p> <p>And I want to redirect users to back page after login.</p> <p>How can I do this? Please show some examples with file name in detail.</p> <p>///////edit</p> <p>Route</p> <pre><code>// Routes for logged in users Route::group(['middleware' =&gt; 'auth'], function() { //write Route::get('board/create', ['as' =&gt; 'board.create', 'uses' =&gt;'BoardController@create']); }); </code></pre> <p>Controller</p> <pre><code>public function create() { return view('board.create'); } </code></pre> <p>Kernel.php</p>
<p>This is achieved using Middleware. By default the <code>App\Http\Middleware\RedirectIfAuthenticated</code> and the <code>\Illuminate\Auth\Middleware\Authenticate</code> middleware are loaded. (Check your <code>app/Http/Kernel.php</code> file to check which middleware are loaded.</p> <p>So with route groups : </p> <pre><code>// Routes for anyone Route::get('guest-or-user', 'SomeController@action'); // Routes for guests only Route::group(['middleware' =&gt; 'guest'], function() { Route::get('user-not-logged-in', 'SomeController@guestAction'); }); // Routes for logged in users Route::group(['middleware' =&gt; 'auth'], function() { Route::get('user-logged-in', 'SomeController@userAction'); // ... other routes }); </code></pre> <p>You can also do this in your controller:</p> <pre><code>// SomeController.php public function __construct() { $this-&gt;middleware('guest', ['only' =&gt; 'guestAction']); $this-&gt;middleware('auth', ['only' =&gt; 'userAction']); } public function action() { // ... } public function guestAction() { // ... } public function userAction() { // ... } </code></pre> <p>Read the doc: <a href="https://laravel.com/docs/5.3/authentication#protecting-routes" rel="nofollow">Protecting Routes</a></p>
How to trigger an INSERT function after all rows have TRUE value in MySQL? <p>here is the problem. I am working on a website which will help people share chapters of a book. The book has 30 chapters and after every chapter is marked as read, I want my database to create next sets of chapters in the chapters table. I don't know if this is an efficient way to do it or should I use PHP if conditions. </p> <p>Here is my chapters table:</p> <pre><code>CREATE TABLE `chapters` ( `chapter_id` int(11) NOT NULL, `chapter_no` int(11) NOT NULL, `completion_cycle` int(11) NOT NULL, `user_id` int(11) NOT NULL, `read` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; </code></pre> <p>When all the read values of 30 chapters for first completion cycle is TRUE (or equal to 1), I want my MySQL to add 30 more rows to chapters table with a new completion cycle id. Any help is appreciated. </p>
<p>First, create the table</p> <pre><code>CREATE TABLE `chapters` ( `chapter_id` int(11) NOT NULL, `chapter_no` int(11) NOT NULL, `completion_cycle` int(11) NOT NULL, `user_id` int(11) NOT NULL, `read` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; </code></pre> <p>In your PHP or in a cron job you can now check if the chapters are completed by using:</p> <pre><code>SELECT COUNT(*) FROM chapters WHERE completion_cycle=0 AND read=0; </code></pre> <p>If the above query returns 0 results, that means all chapters are completed and read. So you can insert the next one.</p> <pre><code>INSERT INTO chapters (chapter_no, completion_cycle, user_id, read) VALUES ('...', 0, '...', 0); </code></pre> <p>The next chapter is now inserted</p>
Receiving empty form values using php and post <p><strong>I am making a insertion form to add a product to the mysql database. I am using echo command to print the query. The printed query is showing empty values like this:</strong></p> <p>*Notice: Undefined index: product_cat in F:\Apache24\htdocs\Site1\admin\product_add.php on line 40</p> <p>Notice: Undefined index: product_brand in F:\Apache24\htdocs\Site1\admin\product_add.php on line 41</p> <p>Notice: Undefined index: product_title in F:\Apache24\htdocs\Site1\admin\product_add.php on line 42</p> <p>Notice: Undefined index: product_price in F:\Apache24\htdocs\Site1\admin\product_add.php on line 43</p> <p>Notice: Undefined index: product_description in F:\Apache24\htdocs\Site1\admin\product_add.php on line 44</p> <p>Notice: Undefined index: product_keywords in F:\Apache24\htdocs\Site1\admin\product_add.php on line 45</p> <p>Notice: Undefined index: product_images in F:\Apache24\htdocs\Site1\admin\product_add.php on line 48</p> <p>Notice: Undefined index: product_images in F:\Apache24\htdocs\Site1\admin\product_add.php on line 49</p> <p>insert into products ('product_cat', 'product_brand', 'product_title', 'product_price', 'product_desc', 'product_image', 'product_keywords') values( '', '', '', '', '', '', '')*</p> <p><strong>This is the html form. It is also the action page:</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Admin Panel - Add Products&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="../styles/admin-style.css"&gt; &lt;script src="//cdn.tinymce.com/4/tinymce.min.js"&gt;&lt;/script&gt; &lt;script&gt;tinymce.init({ selector:'textarea' });&lt;/script&gt; &lt;?php include("../includes/connect.php"); function getcats_add_products(){ global $con; $get_cats="select * from categories"; $run_cats=mysqli_query($con, $get_cats); echo "&lt;option&gt;Select Category&lt;/option&gt;"; while($row_cats = mysqli_fetch_array($run_cats)){ $cat_id = $row_cats['cat_id']; $cat_title = $row_cats['cat_title']; echo "&lt;option value='$cat_id'&gt;$cat_title&lt;/option&gt;"; } } function getbrands_add_products(){ global $con; $get_brands="select * from brands"; $run_brands=mysqli_query($con, $get_brands); echo "&lt;option&gt;Select Brand&lt;/option&gt;"; while($row_brands = mysqli_fetch_array($run_brands)){ $brand_id = $row_brands['brand_id']; $brand_title = $row_brands['brand_title']; echo "&lt;option value='$brand_id'&gt;$brand_title&lt;/option&gt;"; } } if(isset($_POST['submit'])){ $product_cat = $_POST['product_cat']; $product_brand = $_POST['product_brand']; $product_title = $_POST['product_title']; $product_price = $_POST['product_price']; $product_desc = $_POST['product_description']; $product_keywords = $_POST['product_keywords']; $product_images = $_FILES['product_images']['name']; $product_images_temp = $_FILES['product_images']['tmp_name']; $product_query = "insert into products ('product_cat', 'product_brand', 'product_title', 'product_price', 'product_desc', 'product_image', 'product_keywords') values( '$product_cat', '$product_brand', '$product_title', '$product_price', '$product_desc', '$product_images', '$product_keywords') "; echo $product_query; } ?&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="wrapper"&gt; &lt;header&gt; &lt;/header&gt; &lt;div class="heading"&gt;Add New Product&lt;/div&gt; &lt;div class="product-table-div"&gt; &lt;form method="POST" action="" enctype="multipart/form-data"&gt; &lt;table class="product-table" border="1"&gt; &lt;tr&gt; &lt;td id="product-add-label"&gt;Product Category&lt;/td&gt; &lt;td&gt; &lt;select id="product-table-input" name="product-cat"&gt; &lt;?php getcats_add_products(); ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id="product-add-label"&gt;Product Brand&lt;/td&gt; &lt;td&gt; &lt;select id="product-table-input" name="product-brand"&gt; &lt;?php getbrands_add_products(); ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id="product-add-label"&gt;Product title&lt;/td&gt; &lt;td&gt; &lt;input type="text" name="product-title" id="product-table-input"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id="product-add-label"&gt;Product Price&lt;/td&gt; &lt;td&gt; &lt;input type="number" name="product-price" id="product-table-input"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id="product-add-label"&gt;Product description&lt;/td&gt; &lt;td&gt; &lt;textarea rows="10" cols="30" name="product-description"&gt;&lt;/textarea&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id="product-add-label"&gt;Product image&lt;/td&gt; &lt;td&gt; &lt;input type="file" name="product-images" id="product-table-input"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td id="product-add-label"&gt;Product Keywords&lt;/td&gt; &lt;td&gt; &lt;input type="text" name="product-keywords" id="product-table-input"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2"&gt; &lt;div id="product-submit-div"&gt; &lt;input type="reset" name="submitreset" id="product-submit" value="Clear"&gt; &lt;input type="submit" name="submit" id="product-submit" value="Add"&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This location of this page is root>admin>product_add.php. What seems to be the problem? Oh, I have also used tinymce text editor in the textarea.</p>
<p>You are using Hyphen <code>-</code> signs in the HTML form for the field names; but when you try to read in PHP, you are using underscores.</p> <pre><code>$product_cat = $_POST['product_cat']; $product_brand = $_POST['product_brand']; $product_title = $_POST['product_title']; $product_price = $_POST['product_price']; $product_desc = $_POST['product_description']; $product_keywords = $_POST['product_keywords']; </code></pre> <p>Use below code instead of above</p> <pre><code>$product_cat = $_POST['product-cat']; $product_brand = $_POST['product-brand']; $product_title = $_POST['product-title']; $product_price = $_POST['product-price']; $product_desc = $_POST['product-description']; $product_keywords = $_POST['product-keywords']; </code></pre>
Initialize variable depending on another variables type <p>In Python 2.7 I want to intialize a variables type depending on another variable.</p> <p>For example I want to do something like:</p> <pre><code>var_1 = type(var_2) </code></pre> <p>Is there a simple/fast way to do that?</p>
<p>Just create another instance</p> <pre><code>var_1 = type(var_2)() </code></pre> <p>Note that if you're not sure whether the object has a non-default constructor, you cannot rely on the above, but you can use <code>copy</code> or <code>deepcopy</code> (you get a "non-empty" object.</p> <pre><code>import copy var_1 = copy.copy(var_2) # or copy.deepcopy </code></pre> <p>You could use both combined with the latter as a fallback mechanism</p> <p>Note: <code>deepcopy</code> will ensure that your second object is completely independent from the first (If there are lists of lists, for instance)</p>
How do I merge the audited fpr file with the newly scanned fpr file using the command line? <p>I want to merge an audited fortify .fpr file with the newly scanned .fpr file so that all audits and comments get reflected even in the new file. How do I merge the files using command line? Thanks in advance. </p>
<p><code>fprutility -merge -&lt;project old.fpr&gt; -source &lt;new.fpr&gt; -f &lt;merged.fpr&gt;</code></p>
Two DataTable in One Page - Second one initialising weird <p>I have two <code>dataTable</code> in my page and I have a method like below:</p> <pre><code>function ToDataTable() { $(".dataTable").css("width", "100%"); $(".dataTable").each(function () { var $that = $(this); /* Start of method */ function ToDataTableInternal() { var table = $that.DataTable({ responsive: { details: { type: "column", target: -1 }, }, columnDefs: [{ className: "control", orderable: !1, targets: -1, }, { orderable: !1 }], "paging": false, "ordering": false, "info": false, "searching": false, retrieve: true }); } /* End of method */ if ($that.is(":visible")) { ToDataTableInternal() } else { // Observe all invisible parents or table to trigger // ToDataTableInternal method if made visible var $arr = $(this).parentsUntil(":visible").filter(function () { return $(this).css("display") === "none"; }).add($(this)); var observers = []; $arr.each(function () { var observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { if ((mutation.attributeName === 'style' || mutation.attributeName === 'class') &amp;&amp; $that.is(":visible")) { ToDataTableInternal(); for (var i = 0; i &lt; observers.length; i++) { // Disconnect observers observers[i].disconnect(); } } }); }); observers.push(observer); observer.observe(this, { attributes: true }); }); } }); } </code></pre> <p>The reason I have this method is that when table's display is <code>none</code>, it really lags browser(especially IE, where I cannot do anything for minimum of 5 seconds) which is the reason of that I'm changing the table to DataTable after it made visible.</p> <p>But the problem with calling methods individually is the second DataTable doesn't have the same settings which I passed on.(The first one has) Instead, second one has filters, paging, sort elements in it too. </p> <p>If I call both at the same time, nothing out of ordinary happens. What may be the problem?</p> <p>EDIT: I can't reproduce the same behaviour in fiddles.</p>
<p>you can add following properties of dataTable in your datatable configuration to remove filtering, pageing and sorting:</p> <h2>Datatable 1.9</h2> <ul> <li>"bPaginate":false, //Enable or disable pagination.</li> <li>"bFilter": false, //Enable or disable filtering of data</li> <li>"bLengthChange": false, //Enable or disable the size dropdown</li> <li>"bSort": false, //Enable or disable sorting of columns.</li> <li>"bInfo": false, //Enable or disable the table information display.</li> </ul> <p><strong>Update</strong></p> <h2>Datatable 1.10</h2> <p>Option name update in datatable 1.10</p> <ul> <li>bPaginate -> paging </li> <li>bFilter -> searching</li> <li>bLengthChange -> lengthChange</li> <li>bSort -> ordering</li> <li>bInfo -> info</li> </ul>
Ensure that a bloc of text will be displayed on the same page <p>I'm generating reports from a <code>.docx</code> document using <code>HtmlToOpenXml</code>.</p> <p>I <strong>need</strong> to ensure that a particular html block will be displayed on the <strong>same page</strong>, for example:</p> <pre><code>&lt;p&gt;Video provides a powerful way to help [...]&lt;/p&gt; &lt;br /&gt; &lt;br /&gt; &lt;p&gt;To make your document look professionally [...]&lt;/p&gt; </code></pre> <p>I took a look around the web:</p> <ul> <li><a href="http://stackoverflow.com/questions/36439159/open-xml-table-header-same-page">Open XML Table Header Same page</a></li> <li><a href="http://stackoverflow.com/questions/2795315/create-page-break-using-openxml">Create page break using OpenXml</a></li> </ul> <p><code>&lt;w:pPr&gt;&lt;w:keepNext/&gt;&lt;/w:pPr&gt;</code> had my attention but I'm not sure that I can put two paragraphs inside a larger one.</p> <p>I'm aware that it will depend of the font, size and so on but it will not change.</p>
<p>Use "page-break-inside" style in your first block surrounding content to move it to new page. Then try to keep other blocks small enough to fit page (no matter how hard you will try, if the content is too big, it won't fit on one page). Like in example:</p> <pre><code>&lt;div style="page-break-inside: avoid"&gt; &lt;p&gt;Video provides a powerful way to help [...]&lt;/p&gt; &lt;br /&gt; &lt;br /&gt; &lt;p&gt;To make your document look professionally [...]&lt;/p&gt; &lt;/div&gt; </code></pre> <p>Take a look at documentation here: <a href="http://www.w3schools.com/cssref/pr_print_pagebb.asp" rel="nofollow">CSS page-break-before Property</a></p>
How we can store values of variables across Bootstrapper and MSIs getting called from that Bootstrapper <p>I have created a Wix Installer which has following structure</p> <ul> <li>It has Bootstrapper</li> <li>It has MSI1</li> <li>It has MSI2</li> <li>The task of Bootstrapper is to provide options to user as which application he wants to install. Based on his selection MSI1 or MSI2 will be launched.</li> </ul> <p>Now both MSIs need to collect information of Database.</p> <p>My requirement is that if I collect DB information from MSI1, I want to pass that information to MSI2 from Bootstrapper(as after MSI1 user will choose MSI2 from Bootstrapper)</p> <p>We don't want the end user to provide this database information again and again.</p> <p>Please note that we cannot collect the database information from Bootstrapper itself, as the user may go to installer source and execute MSI1 or MSI2 directly.</p> <p>Any one has idea how we can store values of variables across Bootstrapper and MSIs getting called from that Bootstrapper?</p>
<p>Write that information to a well-known registry location during the installation.</p> <p><a href="http://robmensching.com/blog/posts/2010/5/2/the-wix-toolsets-remember-property-pattern/" rel="nofollow">Here's</a> a resource to the "remember me pattern" blog post that Rob has written. I know it's bad practice to just link a blog post that may not exist in the future but I also don't want to just copy most of it.</p> <p>The basic idea is to save properties that may be defined by the user at run-time into the registry. When you run the installer again, you can try to read that registry location and load up the properties from a previous run of the installer so you already know what the user is going to write. </p> <p>In this case, your 2nd installer will know about the well know registry location that the first installer will write the db information to. Now the 2nd installer can read this information when it is run afterwards and use it during hte installation which means the customer doesn't have to re-enter the same information for both installs.</p> <p>You can combine this with custom actions to encode sensitive information and decode it at run time. This is also a very commonly used technique for remembering the install directory of a product as this is something that is commonly changed by the user at run-time.</p> <p><HR/> I reread the question and realized that getting the information from the bootstrapper is not something you can do but I'll leave this part of my answer here anyways. <em>[I think you could gather the information in the bootstrapper and pass it to the MSIs. Just write that information during the install to a registry location and you can read it if it exists when installing if the user runs just from the MSI]</em> <HR/></p> <p>Alternatively you can update your bootstrapper's UI to gather this information and pass it in to both installers. This requires a bit of research into how the bootstrapper application works and how it generates its UI and stores properties. And again, you should use the remember me technique to read the already entered properties from the registry if they exist so you can pre-populate fields with the previous values on subsequent runs of your installation.</p>
Using RTL direction in closeButton of android.support.v7.widget.SearchView <p>I'm trying to change direction of SearchView in toolbar, and this is my try</p> <p><strong>layout.xml</strong></p> <pre><code>android:layoutDirection="rtl" </code></pre> <p><strong>menu.xml</strong></p> <pre><code>&lt;item android:id="@+id/action_search" android:title="@string/search_hint" android:icon="@mipmap/ic_search_icon" app:showAsAction="ifRoom|collapseActionView" app:actionViewClass="android.support.v7.widget.SearchView" /&gt; </code></pre> <p><strong>Java code:</strong></p> <pre><code> MenuItem searchItem = menu.findItem(R.id.action_search); SearchView mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem); getSupportActionBar().setCustomView(MenuItemCompat.getActionView(searchItem)); mSearchView.setInputType(InputType.TYPE_CLASS_TEXT); mSearchView.setQueryHint(getString(R.string.search_hint)); mSearchView.setGravity(Gravity.RIGHT); mSearchView.setTextDirection(View.TEXT_DIRECTION_RTL); mSearchView.setTextAlignment(View.TEXT_ALIGNMENT_GRAVITY); mSearchView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL); mSearchView.setLayoutParams(new ActionBar.LayoutParams(Gravity.RIGHT)); </code></pre> <p><a href="https://i.stack.imgur.com/4Yn5a.png" rel="nofollow"><img src="https://i.stack.imgur.com/4Yn5a.png" alt="SearchView in actionBar"></a> <a href="https://i.stack.imgur.com/WKfxJ.png" rel="nofollow"><img src="https://i.stack.imgur.com/WKfxJ.png" alt="Wrong position of closeButton"></a></p> <p>And this is the result, I success added the SearchView to toolbar and is RTL now. But the issue is position of "X" (closeButton) is wrong, the position must be at left.</p>
<p>To Support <code>Rtl</code> in your App. you have to set <code>android:supportsRtl="true"</code> in your manifest.xml.</p> <p><strong>And Most Important point keep in Mind</strong></p> <p>Change all of your app's <code>"Left/Right"</code> layout properties to <code>Start/End</code>.</p> <p>In you case you are setting.</p> <pre><code>mSearchView.setGravity(Gravity.RIGHT); </code></pre> <p>so change it to </p> <pre><code>mSearchView.setGravity(Gravity.END); </code></pre> <p>and also change here this</p> <pre><code>mSearchView.setLayoutParams(new ActionBar.LayoutParams(Gravity.RIGHT)); </code></pre> <p>to </p> <pre><code> mSearchView.setLayoutParams(new ActionBar.LayoutParams(Gravity.END)); </code></pre>
Format HKBiologicalSex object returned by healthkit to NSString <pre><code>NSLog(@"gender %@", [[GSHealthKitManager sharedManager] readGender]); </code></pre> <p>The function as defined in <code>GSHealthKitManager.m</code> file</p> <pre><code>- (NSString *)readGender { NSError *error; NSString *gender=[self.healthStore biologicalSexWithError:&amp;error]; return gender; } </code></pre> <p><strong>Log</strong></p> <pre><code>2016-10-13 12:37:50.938 random[1712:58930] gender &lt;HKBiologicalSexObject: 0x7b781320&gt; </code></pre> <p>I want to display the biological sex in <code>UILabel</code></p>
<pre><code>NSLog(@"gender %@", [[GSHealthKitManager sharedManager] readGender]); </code></pre> <p>The function is redefined in GSHealthKitManager file as</p> <pre><code>- (NSString *)readGender { NSError *error; HKBiologicalSexObject *gen=[self.healthStore biologicalSexWithError:&amp;error]; if (gen.biologicalSex==HKBiologicalSexMale) { return(@"Male"); } else if (gen.biologicalSex==HKBiologicalSexFemale) { return (@"Female"); } else if (gen.biologicalSex==HKBiologicalSexOther) { return (@"Other"); } else{ return (@"Not Set"); } } </code></pre>
UIToolbar with background colour clear turns white in iOS 10 <p>I have a <code>UIView</code> inside which I added a <code>UIToolBar</code>. </p> <p>I have given background colour as clear colour. It works fine in iOS 9 but in iOS 10 it changes to white. Any other colour than clear colour is working fine in iOS 10.</p> <p>I am using Xcode 7.3, storyboard and swift.</p>
<p>Try this:</p> <pre><code> @IBOutlet var mytab: UIToolbar! override func viewDidLoad() { super.viewDidLoad() let myImage = UIImage() mytab.setBackgroundImage(myImage, forToolbarPosition: .any, barMetrics: .default) mytab.isTranslucent = true } </code></pre>
how to iterate csv file in ansible <p>i have a jinja2 template including a section that need data from a csv file how can i read a csv file and split it into a list then iterate it in the jinja2 template? sth. like this:</p> <pre><code>{% for line in csv_data %} {{ line[0] }} = {{ line[1] }} {% endfor %} </code></pre> <p>in my task file, i am trying to use lookup to read the csv file into csv_data, but it seems lookup can only query and get one line not the whole file, or just the whole file in raw format</p> <pre><code>vars: csv_data: "{{ lookup('file', 'test.csv') }}" </code></pre>
<p>figured a not so good method:</p> <pre><code>{% for line in csv_data.split("\n") %} {% set list = line.split(",") %} {{ list[0] }}={{ list[1] }} {% endfor %} </code></pre>
How to pass instance variables from controller to render partial in Ruby <p>I am having trouble passing an instance variables (@article) from a controller (articles_controller.rb) to a partial render (_form.html.erb) in Ruby.</p> <p>Here is the error from being sent back: </p> <pre><code>`undefined method `errors' for nil:NilClass` </code></pre> <p><a href="https://i.stack.imgur.com/v97iq.png" rel="nofollow"><img src="https://i.stack.imgur.com/v97iq.png" alt="Error"></a></p> <p>articles_controller.rb:</p> <pre><code>class ArticlesController &lt; ApplicationController def new end def create @article = Article.new(article_params) if @article.save redirect_to @article else render 'new' end end def update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else render 'edit', :article =&gt; @article end end def show @article = Article.find(params[:id]) end def index @articles = Article.all end private def article_params params.require(:article).permit(:title, :text) end end </code></pre> <p>new.html.erb </p> <pre><code>&lt;h1&gt;New Article&lt;/h1&gt; &lt;%= form_for :article, url: articles_path do |f|%&gt; &lt;%= render partial: "form", :locals =&gt; {:article =&gt; @article} %&gt; &lt;% end %&gt; &lt;% link_to 'Back', articles_path %&gt; </code></pre> <p>_form.html.erb</p> <pre><code>&lt;% if @article.errors.any? %&gt; &lt;div id="error_explanation"&gt; &lt;h2&gt; &lt;%= pluralize(@article.errors.count, "error") %&gt; prohibited this article from being saved: &lt;/h2&gt; &lt;ul&gt; &lt;% @article.errors.full_messeages.each do |msg| %&gt; &lt;li&gt;&lt;%= msg %&gt;&lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/div&gt; &lt;% end %&gt; &lt;p&gt; &lt;%= f.label :title %&gt;&lt;br /&gt; &lt;%= f.text_field :title %&gt; &lt;/p&gt; &lt;p&gt; &lt;%= f.label :text %&gt;&lt;br /&gt; &lt;%= f.text_area :text %&gt; &lt;/p&gt; &lt;p&gt; &lt;%= f.submit %&gt; &lt;/p&gt; </code></pre> <p>Any help would be appreciated </p>
<pre><code>def new @article = Article.new end &lt;%= render partial: "form", collection: @article %&gt; </code></pre> <p>or even </p> <pre><code>&lt;%= form_for @article do |f|%&gt; &lt;%= render 'form' %&gt; &lt;% end %&gt; </code></pre> <p>depends on your needs</p>
mysql to mongodb database and query conversion <p>The following structure as defined in MySQL db<br/> 1. I have a one table for degree<br> contain two columns : degree_id ,degree_name<br/> 2.Another Table for branch<br/> branch_id,branch_name,degree_id<br/> 3.Subject table<br/> subject_id,subject_name,subject_code,degree_id,semester<br/> 4.syllabus<br/> syllabus_id,syllabus_name,sort_note,attachment,semester,degree_id,branch_id,subject_id<br/> Now i can easily fetch the syllabus of particuler degree,branch,semester using mysql but i am new in mongo db please help</p>
<p>In <code>MongoDb</code> you have to take the concept more general and include all the relation in it.</p> <p>Your database <code>Mysql</code>, looks like this on <code>mongodb</code>:</p> <pre><code> degree{ _id : ..., name : ..., branches :[ { _id: ... name: ...., syllabus : [ { _id: ..., name: ...., sort_note: .... attachment:... semetster,... } , .. ],...{ } ], subjects: [ { _id: .., name: ...., code: ....., semester: .... }, ...] } </code></pre> <p>If id_branch and id_degree are uniques like a contraint is an object else is an array.</p> <p>Regards</p>
Deleting a table row from button click <p>The following code that I typed is used to add or delete rows in an html table. When I click the add button without any problem, but when I click the delete button though I want to delete a particular row I am unable to. I get an alert message stating:</p> <blockquote> <p>"can not read property `onclick` of null "</p> </blockquote> <p>How can I rectify this issue?</p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt; Add/Remove dynamic rows in HTML table &lt;/TITLE&gt; &lt;SCRIPT language="javascript"&gt; function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for (var i = 0; i &lt; colCount; i++) { var newcell = row.insertCell(i); newcell.innerHTML = table.rows[0].cells[i].innerHTML; //alert(newcell.childNodes); switch (newcell.childNodes[0].type) { case "text": newcell.childNodes[0].value = ""; break; case "checkbox": newcell.childNodes[0].checked = false; break; case "select-one": newcell.childNodes[0].selectedIndex = 0; break; } } } function deleteRow(tableID) { try { var table = document.getElementById(tableID); var rowCount = table.rows.length; for (var i = 0; i &lt; rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if (document.getElementById('button').onclick == true) { if (rowCount &lt;= 1) { alert("Cannot delete all the rows."); break; } table.deleteRow(i); rowCount--; i--; } } } catch (e) { alert(e); } } &lt;/SCRIPT&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;INPUT type="button" value="Add Row" onclick="addRow('dataTable')" /&gt; &lt;TABLE id="dataTable" width="350px" border="1"&gt; &lt;TR&gt; &lt;TD&gt; &lt;INPUT type="button" name="button" value=delete id=delete onclick="deleteRow('dataTable')"&gt; &lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre>
<p>In your code you have <strong>document.getElementById('button')</strong>. But you don't have any element with id <strong>"button"</strong>. So, document.getElementById('button') returned null and onclick event is checked on null . So, it gives the error <strong>can not read property "onclick" of null</strong></p>
elasticsearch fuzzy search ,just ten result <p>I am beginner with elasticsearch , i don't find to have all result with :</p> <p>{ "query":</p> <pre><code> { "match": { "message": { "query": "my ask" , "fuzziness": "AUTO" </code></pre> <p>}}}}</p> <p>do you know how to have all result ? Thanks a lot !</p>
<p>You cannot return all results like that... ElasticSearch is giving the total number of results but return the default value define on the elasticsearch.yml (or 20 by default )</p> <p>If you want to fetch all result use the scroll API: <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html</a></p> <p>And or the size param: <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-from-size.html" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-from-size.html</a></p> <p>HtH,</p>
how to convert html to plain text c#? <p>i am trying to get plain text from html website but i am getting html code instead of plain text.for example &lt; b > hello &lt; /b> &lt; p > its me &lt; / p> How can i convert it to hello its me . Any help is very much appreciated! here is my code . </p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(""https://www.dailyfx.com/real-time-news"); myRequest.Method = "GET"; WebResponse myResponse = myRequest.GetResponse(); StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8); string result = sr.ReadToEnd(); textBox1.Text = result; sr.Close(); myResponse.Close(); } } } </code></pre>
<p><strong>Short answer:</strong> No direct conversion; you're "screen-scraping" a website; parse the result string to extract what you need (or better yet, see if there is an API provided by the website in question).</p> <p>Websites render in HTML, not plain text. Although you're getting the result back as a string, you'll need to parse it to extract the text you are interested in. The actual extraction highly depends on what you are trying to accomplish. If the website is proper XHTML, you can load it into an <code>XDocument</code> as XML and traverse the tree to get the information you need; otherwise, the <a href="http://www.nuget.org/packages/HtmlAgilityPack" rel="nofollow">HTMLAgilityPack</a> suggested in one of the comments may be of help (not as magical as the comment is alluding to - it's a bit more work than <code>GetString</code>...)</p>
web2py prevent duplicates in many to many table <p>I have a table to manage many to many relationship (workers and skills) Workers can have multiple skills and one skill can be assigned to multiple workers</p> <p>What would be the best way to prevent duplicate entries so one skill is not assigned to the same worker twice?</p> <p>thank you</p>
<p>If you have something like:</p> <pre><code>db.define_table('worker_skill', Field('worker', 'reference worker'), Field('skill', 'reference skill')) </code></pre> <p>To prevent duplicates via form submissions, you could then add a validator to one of the fields, such as:</p> <pre><code>db.worker_skill.skill.requires = IS_NOT_IN_DB( db(db.worker_skill.worker == request.vars.worker), 'worker_skill.skill' ) </code></pre> <p>The above will ensure that the value being inserted in "skill" does not exist among the set of records where the value being inserted in "worker" matches the "worker" field.</p> <p>Another option for form validation is use of an <code>onvalidation</code> callback, as explained in the <a href="http://web2py.com/books/default/chapter/29/07/forms-and-validators" rel="nofollow">forms chapter</a> of the book.</p> <p>You can also set a unique constraint on the pair of columns directly in the database (web2py does not handle that, so you will have to do that via an external tool). That will not help with form validation, as a violation of the constraint will simply result in the database driver throwing an exception (rather than presenting a friendly error message to the end user), but it will be useful if you are making inserts via means other than a web2py form.</p>
function with dataTask returning a value <p>I wan't to check if my url statusCode equals to 200, I created a function returning a Boolean if the statusCode equals to 200, I'm using a dataTask, but I don't know how to return a value:</p> <pre><code>class func checkUrl(urlString: String) -&gt; Bool{ let urlPath: String = urlString var url: NSURL = NSURL(string: urlPath)! var request: NSURLRequest = NSURLRequest(url: url as URL) var response: URLResponse? let session = Foundation.URLSession.shared var task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in if let error = error { print(error) } if let data = data{ print("data =\(data)") } if let response = response { print("url = \(response.url!)") print("response = \(response)") let httpResponse = response as! HTTPURLResponse print("response code = \(httpResponse.statusCode)") if httpResponse.statusCode == 200{ return true } else { return false } } }) task.resume() } </code></pre> <p>The returns in <code>if else</code> are returning an error:</p> <blockquote> <p>Unexpected non-void return value in void function</p> </blockquote>
<p>You're returning a value from a <code>Void</code> function that is the <code>completionHandler</code> closure of <code>dataTask(_:, _:)</code></p> <p>Regarding your code, there is something wrong: you can't return that value because it's executed on a different thread, it's an asynchronous operation. Please take a look at this thread: <a href="http://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function">Returning data from async call in Swift function</a></p>
How to dispaly Json Formatted DateTime into Angular Data <p><strong>I have Datetime in my sqldb when im fetching data from database using Json formatted im Getting Datetime as a "/Date(820434600000)/"<br> Here im having some code which i copied from stackoverflow but not working please Guide me</strong></p> <pre><code> app.filter("DateFilter", function () { var re = /\/Date\(([0-9]*)\)\//; return function (x) { var m = x.match(re); if (m) return new Date(parseInt(m[1])); else return null; }; }); &lt;td&gt;{{eee.DataofJoin | DateFilter | date: 'yyyy-MM-dd HH:mm'}}&lt;/td&gt; </code></pre>
<p>So you are getting from database a instance of Date object, so if you bind the date to new Date got from DB as follows:</p> <p><code>$scope.date = new Date(820434600000);</code></p> <p>(will result in this "1995-12-31T18:30:00.000Z") and using angular filters for date you can display in any format you want;</p> <p>In HTML you do this:</p> <pre><code>&lt;p&gt;{{date | date: 'yyyy-MM-dd HH:mm'}}&lt;/p&gt; </code></pre> <p>This will result in displaying </p> <p><code>1995-12-31 20:30</code></p> <p>Angular takes care of that with built-in filters, no need for custom one. Though it's not best practice what you do, try using only the timestamp stored in DB.</p>
HTML form with two actions <p>I have these two forms, one for movies and one for pictures... </p> <p>Its not the same script handling both categories, I have two scripts here</p> <p>Is there anyway to join both search in one form but with two options (movies and pictures) and working in most browsers?? also, The button must be able to switch both searches</p> <pre><code>MOVIES: &lt;form action="/search_movies.php" target="_self"&gt; &lt;input name="q" type="text" placeholder="Search videos..." /&gt; &lt;input name="savesearch" value="1" type="hidden"&gt; &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt; PICTURES: &lt;form action="/search_photos.php" target="_self"&gt; &lt;input type="hidden" name="show" value="thumbs"&gt; &lt;input type="text" name="search" value=""&gt; &lt;select name="group"&gt; &lt;option value="group_5"&gt;Pictures&lt;/option&gt; &lt;/select&gt; &lt;input type="submit" value="Search"&gt; </code></pre>
<p>You should consider using a single form with an input and a select (All/Movies/Pictures), and merge your target script. I think it's the easiest way to proceed as it will just consist in examining the selected option and choosing to execute the search_movies script, the search_photos script or both ones (it's up to you how to display it).</p>
How to properly assign row names to ("mts", "ts", "matrix") object in R? <p>I want to assign row names to a ("mts", "ts", "matrix") object:</p> <pre><code>library(lubridate) library(zoo) myVAR &lt;- cbind(ts(rnorm(64,0,1)),ts(rnorm(64,0,1)),ts(rnorm(64,0,1)), ts(rnorm(64,0,1))) class(myVAR) # "mts" "ts" "matrix" dim(myVAR) # 64x4 as.yearmon(seq(ymd('2010-09-01'), by = '1 month', length.out=(64))) # "Sep 2010" "Oct 2010" ...."Dec 2015"; I wanna assign these as row names row.names(myVAR) &lt;- as.yearmon(seq(ymd('2010-09-01'), by = '1 month', length.out=(64))) </code></pre> <p>The last assginment results in almost nothing:</p> <pre><code>myVAR # Time Series: Start = 1 End = 64 Frequency = 1 ts(rnorm(64, 0, 1)) ts(rnorm(64, 0, 1)) ts(rnorm(64, 0, 1)) ts(rnorm(64, 0, 1)) 1 0.082237617 0.18201849 0.54350780 -0.09849474 2 -0.471237861 0.82705042 0.72799739 0.68516426 3 -0.258811941 0.36791007 -1.68230838 0.35263624 .................................................................... 64 -0.663503979 -0.06671596 0.16724293 -0.12728622 </code></pre> <p>But, interestingly:</p> <pre><code>row.names(myVAR) [1] "2010.66666666667" "2010.75" "2010.83333333333" "2010.91666666667" ............................................................ [61] "2015.66666666667" "2015.75" "2015.83333333333" "2015.91666666667" </code></pre> <p>As far as I see, this shows R made the rownames assignment, but wrongly. Why? Any idea?</p>
<p>J_F solved my problem:</p> <p>In my case, there were stationary and nonstationary variables. The nonstationary variables were made stationary upon differencing. These resulted in NAs at the beginning of the differenced series when these series are thought together with the already stationary ones. I applied:</p> <pre><code>ts(ts.intersect(kur1f, lnbist1f, lnaltin, mfaiz1f), start = c(2010, 9), frequency = 12) </code></pre> <p>and now rownames are just I want. Many many thanks to J_F again.</p> <p>For those who interested:<br> kur1f: 1st difference of exchange rate<br> lnbist1f: 1st difference of ln of BIST100 Stock Exchange<br> lnaltin: ln of Gold prices<br> mfaiz1f: 1st difference of interest rates</p>
Powershell build step Team city <p>I'm trying to set up teamcity and have come across a problem when adding a powershell build step. I am getting the following error when trying to run the build, however if I remove this build step the build runs.</p> <p>"Warning: No enabled compatible agents for this build configuration. Please register a build agent or tweak build configuration requirements."</p> <p>Below is a screen shot of the build step configuration. If anyone has any ideas how to fix this please let me know.</p> <p>Thanks</p> <p><a href="https://i.stack.imgur.com/xkixP.png" rel="nofollow"><img src="https://i.stack.imgur.com/xkixP.png" alt="enter image description here"></a></p>
<p>There may be two reasons :</p> <ol> <li>Check PowerShell is installed on machine where TeamCity server or Agent is installed</li> <li>If PowerShell is there then check TeamCity Agent is running under System profile or under particular user account</li> </ol> <p>This is occures when particular software is not installed on the TeamCity Agent server</p>
Store closed or open woocommerce <p>i have plugin Woo Shopping Hours</p> <p>I want at the end of working hours show the word closed the store and at the beginning of working hours show a word Open Store</p>
<p>Try the link</p> <p><a href="https://wordpress.org/plugins/woo-shopping-hours/screenshots/" rel="nofollow">https://wordpress.org/plugins/woo-shopping-hours/screenshots/</a></p> <p>Hope this will help you!!</p>
Deserialize multiple XML tags to single C# object <p>I have class structure as follows</p> <pre><code> public class Common { public int price { get; set; } public string color { get; set; } } public class SampleProduct:Common { public string sample1 { get; set; } public string sample2 { get; set; } public string sample3 { get; set; } } </code></pre> <p>I have XML file as follows</p> <pre><code>&lt;ConfigData&gt; &lt;Common&gt; &lt;price&gt;1234&lt;/price&gt; &lt;color&gt;pink&lt;/color&gt; &lt;/Common&gt; &lt;SampleProduct&gt; &lt;sample1&gt;new&lt;/sample1&gt; &lt;sample2&gt;new&lt;/sample2&gt; &lt;sample3&gt;new123&lt;/sample3&gt; &lt;/SampleProduct&gt; &lt;/ConfigData&gt; </code></pre> <p>Now I wanted to deserialize full XML data to SampleProduct object (single object).I can deserialize XML data to different object but not in a single object. Please help.</p>
<p>If you create the XML yourself Just do it like this:</p> <pre><code>&lt;ConfigData&gt; &lt;SampleProduct&gt; &lt;price&gt;1234&lt;/price&gt; &lt;color&gt;pink&lt;/color&gt; &lt;sample1&gt;new&lt;/sample1&gt; &lt;sample2&gt;new&lt;/sample2&gt; &lt;sample3&gt;new123&lt;/sample3&gt; &lt;/SampleProduct&gt; &lt;/ConfigData&gt; </code></pre> <p>Otherwise, if you get the XML from other sources, do what Kayani suggested in his comment:</p> <pre><code>public class ConfigData { public Common { get; set; } public SampleProduct { get; set; } } </code></pre> <p>But don't forget that the SampleProduct created in this manner don't have "price" and "color" properties and these should be set using created Common instance</p>
ng2-bootstrap issues with Typescript 2 <p>I have installed and added <strong>ng2-bootstrap</strong> in an <strong>angular2</strong> project, but I have compilation errors. It seemes to be linked to <strong>Typescript 2</strong> as if I had the bad version configured in my package.json, but it is not the case, look at it:</p> <p><strong>package.json</strong>:</p> <pre><code>{ "name": "angular-quickstart", "version": "1.0.0", "description": "QuickStart package.json from the documentation, supplemented with testing support", "scripts": { "start": "tsc &amp;&amp; concurrently \"tsc -w\" \"lite-server\" ", "docker-build": "docker build -t ng2-quickstart .", "docker": "npm run docker-build &amp;&amp; docker run -it --rm -p 3000:3000 -p 3001:3001 ng2-quickstart", "pree2e": "npm run webdriver:update", "e2e": "tsc &amp;&amp; concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first", "lint": "tslint ./app/**/*.ts -t verbose", "lite": "lite-server", "postinstall": "typings install", "test": "tsc &amp;&amp; concurrently \"tsc -w\" \"karma start karma.conf.js\"", "test-once": "tsc &amp;&amp; karma start karma.conf.js --single-run", "tsc": "tsc", "tsc:w": "tsc -w", "typings": "typings", "webdriver:update": "webdriver-manager update" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@angular/common": "2.0.2", "@angular/compiler": "2.0.2", "@angular/core": "2.0.2", "@angular/forms": "2.0.2", "@angular/http": "2.0.2", "@angular/platform-browser": "2.0.2", "@angular/platform-browser-dynamic": "2.0.2", "@angular/router": "3.0.2", "@angular/upgrade": "2.0.2", "angular2-in-memory-web-api": "0.0.21", "systemjs": "0.19.39", "core-js": "^2.4.1", "reflect-metadata": "^0.1.3", "rxjs": "5.0.0-beta.12", "zone.js": "0.6.25", "bootstrap": "^3.3.7", "ng2-bootstrap": "1.1.14-1", }, "devDependencies": { "concurrently": "^2.2.0", "lite-server": "^2.2.0", "typescript": "^2.0.2", "typings": "^1.0.4", "canonical-path": "0.0.2", "http-server": "^0.9.0", "tslint": "^3.7.4", "lodash": "^4.11.1", "jasmine-core": "~2.4.1", "karma": "^1.2.0", "karma-chrome-launcher": "^0.2.3", "karma-cli": "^0.1.2", "karma-htmlfile-reporter": "^0.2.2", "karma-jasmine": "^0.3.8", "protractor": "^3.3.0", "rimraf": "^2.5.2" }, "repository": {} } </code></pre> <p>Error example for line:</p> <pre><code>private readonly trueValue; </code></pre> <p>Errors:</p> <pre><code>Duplicate identifier 'readonly'. Cannot find name 'trueValue'. </code></pre> <p>Any idea of what I'm doing wrong?</p>
<p>I answer myself. It was a noob issue. Visual Studio 2015 was not up-to-date because I still was in TypeScript 1.8 version.</p> <p>After the update, everything rocks.</p>
Change color to an All Day Event in google calendar with Apps script <p>I've got a problem to change the color in an All Day Event in google calendar with google apps script. I tested a lot of way to go, but nothing works.</p> <p>var event = CalendarApp.getCalendarById(calendrierId).createAllDayEvent(title,date).addPopupReminder(1440);</p> <p>Does anyone has a solution</p> <p>Thanks</p>
<p>You need to use the <a href="https://developers.google.com/apps-script/advanced/calendar" rel="nofollow">Advanced Calendar Service</a> (That must be <a href="https://developers.google.com/apps-script/guides/services/advanced" rel="nofollow">enabled before use</a>. In the Script Editor select Resources > Advanced Google services... and then enable it in the Google Developers Console.)</p> <p>Once enabled you can create an event using the <a href="https://developers.google.com/google-apps/calendar/v3/reference/events/insert" rel="nofollow"> Events: insert</a> and use <strong>colorId</strong> to set the color of the event, here's an example:</p> <pre><code>function myFunction() { var calendarId = '{YOUR_CALENDAR_ID}'; var date = "2016-12-25"; var event = { summary: 'Christmas Day', location: 'Home', start: { date: date }, end: { date: date }, // Bold Red background. colorId: 11 }; Calendar.Events.insert(event, calendarId); } </code></pre> <p>As of today, there are 11 colors available for events, you can use <a href="https://developers.google.com/google-apps/calendar/v3/reference/colors/get" rel="nofollow">Calendar.Colors.get()</a> for the full list, but here's a table with the names used in the UI that you're probably more familiar with:</p> <pre><code>| name | colorId | background | |------------|---------|------------| | Blue | 1 | #a4bdfc | | Turquoise | 2 | #7ae7bf | | Purple | 3 | #dbadff | | Red | 4 | #ff887c | | Yellow | 5 | #fbd75b | | Orange | 6 | #ffb878 | | Turquoise | 7 | #46d6db | | Gray | 8 | #e1e1e1 | | Bold Blue | 9 | #5484ed | | Bold Green | 10 | #51b749 | | Bold Red | 11 | #dc2127 | </code></pre>
php - check internet connect and DNS resolution <p>I know this may have been asked before, but I can't find anything that quite matches my specific requirements.</p> <p>I'm loading a page on a local Linux server, when it loads I need to know does the server it is running on have Internet Access and is DNS resolving.</p> <p>I've got this working, BUT... if there is no Internet connection the page takes a very long time to load, if there is a connection then it loads instantly.</p> <p>I'm using the following to check for Internet Access:</p> <pre><code>$check1 = checkState('google-public-dns-a.google.com',53); $check2 = checkState('resolver1.opendns.com',53); if ($check1 == "YES" || $check2 == "YES"){ echo "Internet Available"; } function checkState($site, $port) { $state = array("NO", "YES"); $fp = @fsockopen($site, $port, $errno, $errstr, 2); if (!$fp) { return $state[0]; } else { return $state[1]; } } </code></pre> <p>and checking DNS resolution using:</p> <pre><code>$nameToIP = gethostbyname('www.google.com'); if (preg_match('/^\d/', $nameToIP) === 1) { echo "DNS Resolves"; } </code></pre> <p>Can anyone recommend a better way ? so if there is no connection the page doesn't stall for a long time. </p> <p>Thanks</p>
<p>You can use <code>fsockopen</code> </p> <p>Following example works well and tells you whether you are connected to internet or not</p> <pre><code>function is_connected() { $connected = @fsockopen("www.google.com", 80); //website, port (try 80 or 443) if ($connected){ fclose($connected); return true; } return false; } </code></pre> <p>Reference : <a href="http://stackoverflow.com/a/4860432/2975952">http://stackoverflow.com/a/4860432/2975952</a></p> <p>Check <code>DNS</code> resolves here </p> <pre><code>function is_site_alive(){ $response = null; system("ping -c 1 google.com", $response); if($response == 0){ return true; } return false; } </code></pre> <p>Reference : <a href="http://stackoverflow.com/a/4860429/2975952">http://stackoverflow.com/a/4860429/2975952</a></p>
Why meteor project update run endless? <p>I have installed meteor 1.4.1 and an older meteor project. If i try to update the project by running 'meteor update' 'Extracting templating@1.1.9...' runs endlessly. Does somebody has any idea what is the problem?</p>
<p>Add <code>54.192.225.217 warehouse.meteor.com</code> to your host file, meteor reset and try again</p>
What exactly is ICE when referring to the wix installer <p>Our solution has some wix installers in it. Most of the time I don't care about these but on occasion the build fails with this sort of error:</p> <p><a href="https://i.stack.imgur.com/UijRZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/UijRZ.png" alt="enter image description here"></a></p> <p>Some Google-fu later, <a href="http://stackoverflow.com/questions/14840233/error-lght0301-failed-to-open-the-database">this</a> helpful article details how to suppress the error but I'd like to understand exactly what ICE is before I'd consider making this a permanent change.</p> <p>All I can glean so far is that it stands for: <em>Internal Consistency Evaluator</em> but this doesn't really reveal much!</p>
<p>Your question is a little vague (because there is more than one ICE test), but generally speaking the ICE tests make sure you haven't built an MSI file that will cause problems at install or maintenance time. This is the full list:</p> <p><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa369206(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/windows/desktop/aa369206(v=vs.85).aspx</a></p> <p>and in the best practices for installs it mentions the validation tests:</p> <p><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb204770(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/windows/desktop/bb204770(v=vs.85).aspx</a></p>
How to install Notepad++ plugin offline? <p>I am trying to install Notepad++ plugin from <code>Plugins -&gt; Plugin Manager</code>, but my office firewall is restricting its download. Is there any alternate way to download plugin offline?</p>
<p><a href="http://docs.notepad-plus-plus.org/index.php/Plugin_Central" rel="nofollow">http://docs.notepad-plus-plus.org/index.php/Plugin_Central</a></p> <p>This site lists all plugins available with link to its sources. Also summarizes the process to install the downloaded plugin.</p>
joining two sql statements vertically <p>I want to join the following two sql statements into one so that I have total 23 rows( First sql has 23 rows and second has 20 rows out of this 20 rows are common with unique field location in each sql) with h3dac values in first sql and 2nd sql appear in columns.</p> <p>Any work around please ?</p> <pre><code>$sql_u1="select * from (select location1.location as locs, location1.elevation as elvn,location1.group as groups, shiftdata.location as loc1, shiftdata.date, shiftdata.shift, shiftdata.h3dac as h3dac1 from location1 inner join shiftdata on location1.location=shiftdata.location where shiftdata.unit= 1 ORDER BY shiftdata.date desc, shiftdata.shift desc, location1.loc_id limit 23) as a left JOIN (select location as loc1, date as date2, shift as shift2, h3dac as h3dac2 from shiftdata where unit= 1 ORDER BY date desc, shift desc limit 23 offset 23) as b on a.locs=b.loc1 left join (select location as loc3, date as date3, shift as shift3, h3dac as h3dac3 from shiftdata where unit= 1 ORDER BY date desc, shift desc limit 23 offset 46) as c on a.locs=c.loc3"; $sql_u2="select * from (select location2.location as locs,location2.elevation as elvn, location2.group as groups, shiftdata.location as loc1, shiftdata.date, shiftdata.shift, shiftdata.h3dac as h3dac1 from location2 inner join shiftdata on location2.location=shiftdata.location where shiftdata.unit= 2 ORDER BY shiftdata.date desc, shiftdata.shift desc, location2.loc_id limit 20) as a left JOIN (select location as loc1, date as date2, shift as shift2, h3dac as h3dac2 from shiftdata where unit= 2 ORDER BY date desc, shift desc limit 20 offset 20) as b on a.locs=b.loc1 left join (select location as loc3, date as date3, shift as shift3, h3dac as h3dac3 from shiftdata where unit= 2 ORDER BY date desc, shift desc limit 20 offset 40) as c on a.locs=c.loc3"; </code></pre>
<pre><code>$sql ="select * from (sel.... union select * from (sel.... </code></pre> <p>You can use union operation, it will return you the result without duplicates.</p>
css selectors not working as expected <p>I have the following HTML</p> <pre><code>&lt;dl&gt; &lt;dt&gt;A&lt;/dt&gt; &lt;dd&gt;B&lt;/dd&gt; &lt;dt&gt;C&lt;/dt&gt; &lt;dd&gt;D&lt;/dd&gt; &lt;dt&gt;E&lt;/dt&gt; &lt;dd&gt;F&lt;/dd&gt; &lt;/dl&gt; </code></pre> <p>and the following CSS</p> <pre><code>dt, dd { border-bottom: 1px solid #000; } dt:last-child, dd:last-child { border-bottom: none; } </code></pre> <p>The problem is that the last <code>dt</code> has a border.</p> <p>What is wrong? What am I missing?</p> <p>Here is the <a href="https://jsfiddle.net/bxf8v8mg/" rel="nofollow">jsfiddle</a>.</p>
<p>you need to target <code>dt:last-of-type</code> since the last <code>dt</code> is not the <code>last-child</code> of its parent (it is in fact followed by another <code>dd</code> element)</p> <blockquote> <p>Example: <a href="https://jsfiddle.net/bxf8v8mg/2/" rel="nofollow">https://jsfiddle.net/bxf8v8mg/2/</a></p> </blockquote> <hr> <p>As a side note you could optimize your code like so</p> <pre><code>dt:not(:last-of-type), dd:not(:last-child) { border-bottom: 1px solid #000; } </code></pre> <p>So you don't need to reset the border with a specific rule later.</p> <blockquote> <p>Example (optimized): <a href="https://jsfiddle.net/bxf8v8mg/5/" rel="nofollow">https://jsfiddle.net/bxf8v8mg/5/</a></p> </blockquote>
react-native app not generating icon (ANDROID) <p>After the install of the <strong>app-release.apk</strong> on my device the icon is not visible anywhere in my menu (even installing it through the play store).</p> <p>And also if I check it inside the settings>installed apps I can't launch the application by it's main activity. (I am able start the activity with adb shell) </p>
<p>If you intend on your application being available on a large range of devices, you should place your application icon into the different res/drawable... folders provided. In each of these folders, you should include a 48dp sized icon:</p> <ul> <li>drawable-ldpi (120 dpi, Low density screen) - 36px x 36px</li> <li>drawable-mdpi (160 dpi, Medium density screen) - 48px x 48px</li> <li>drawable-hdpi (240 dpi, High density screen) - 72px x 72px</li> <li>drawable-xhdpi (320 dpi, Extra-high density screen) - 96px x 96px</li> <li>drawable-xxhdpi (480 dpi, Extra-extra-high density screen) - 144px x 144px</li> <li>drawable-xxxhdpi (640 dpi, Extra-extra-extra-high density screen) - 192px x 192px</li> </ul> <p>You may then define the icon in your AndroidManifest.xml file as such:</p> <pre><code>&lt;application android:icon="@drawable/icon_name" android:label="@string/app_name" &gt; .... &lt;/application&gt; </code></pre>
How does React's createElement(...) work ? What are the props used for? <p>I read <a href="https://facebook.github.io/react/docs/top-level-api.html#react.createelement" rel="nofollow">this</a>:</p> <pre><code>ReactElement createElement( string/ReactClass type, [object props], [children ...] ) </code></pre> <blockquote> <p>Create and return a new ReactElement of the given type. The type argument can be either an html tag name string (eg. 'div', 'span', etc), or a ReactClass (created via React.createClass).</p> </blockquote> <p>This does not really explain to me what happens to <code>[object props]</code>. Why is it needed ? What is it used for ?</p> <p>Could someone explain what happens to <code>[object props]</code> when calling to <code>createElement</code> ? How are they used ? Will they be used to render the element ? Can they change later ? Are they mutable or immutable ?</p> <p>Reason for asking : I am trying to figure out <a href="https://github.com/jhegedus42/scalajs-react-playaround/wiki/ReactJS-----ScalaJS-React-Interop" rel="nofollow">how to use</a> scalajs-react.</p>
<p>for all those who ever wonder how react actually works ? checkout the below link which provides sneak peak into the react implementation</p> <p><a href="https://facebook.github.io/react/contributing/implementation-notes.html" rel="nofollow">How React Works - implementation notes</a> </p>
DES ECB encryption with PHP <p><a href="https://www.tools4noobs.com/online_tools/encrypt/" rel="nofollow">https://www.tools4noobs.com/online_tools/encrypt/</a> gives "a67a318c98a0307502ba81caade2f3a9" as a DES ECB result for the key "1234567890abcdef" and payload "encrypt this".</p> <p>The PHP code</p> <pre><code>echo bin2hex(mcrypt_encrypt( MCRYPT_DES, hex2bin("1234567890abcdef"), "encrypt this", MCRYPT_MODE_ECB)) . "\n"; </code></pre> <p>prints out "1a29ee87f2ad67644ff28450c676a664".</p> <p>What's wrong with the code?</p>
<p>The <em>noobs4tools</em> website strips out the <code>hex2bin</code> function and truncates the key length to 8 characters(as Yoshi stated in comments).</p> <p>With a keysize of <code>12345678</code> the output of both the website and the PHP code is consistent. </p> <p>The DES keysize is stated in the manual as being 56 bits. Read below some useful background on DES specific keysizes.</p> <p><a href="http://stackoverflow.com/q/965500/3536236">How should I create my DES key? Why is an 7-character string not enough?</a> </p> <p>Key Used by the <em>noobs4tools</em> website:</p> <pre><code>"12345678" </code></pre> <p>Key Used by your code:</p> <pre><code> hex2bin("1234567890abcdef"); // 4Vx���� </code></pre> <p>This difference then gives you the different outputs.</p> <p>So the website does not translate the <em>key</em> into any other number- or data- form. It expects you to provide an already correctly formatted value in the page script. </p>
Correct query no longer working in SPROC <p>While testing an application that uses a stored procedure, I came upon an error that had actually been fixed some time before. When debugging the stored procedure, I found that the query which breaks is the following:</p> <pre><code>SET @LastSold = (SELECT last_sold_date FROM movement.dbo.dv_store_items WHERE Cast(store_number AS INT) = @Store AND vendor_number = @Vendor AND upc = @UPC AND store_number &lt;&gt; 'CMPNY'); </code></pre> <p>The error I receive for this is: </p> <pre><code>Conversion failed when converting the varchar value 'CMPNY' to data type int </code></pre> <p>The odd thing about this query is that when I run the same query outside of the stored procedure with the same criteria, it works perfectly fine. Even stranger is that this stored procedure was working just fine until I created an index on the table movement.dbo.dv_store_items:</p> <pre><code>CREATE NONCLUSTERED INDEX [NCIX1] ON [dbo].[dv_store_items] ( [upc] ASC, [vendor_number] ASC, [store_number] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO </code></pre> <p>I'm honestly at a loss for words as to how this makes any sense, so any help would be <em>very</em> much appreciated</p>
<p>The only fool-proof way to ensure you don't run into conversion problems (alpha to integer, like 'CMPY') is by using <a href="https://msdn.microsoft.com/en-us/library/hh974669.aspx" rel="nofollow">TRY_CAST</a>. This will return <code>NULL</code> if the cast cannot be made (ie, from 'CMPY' to INT). Available in SQL Server 2012+.</p> <hr> <pre><code>SET @LastSold = ( SELECT last_sold_date FROM movement.dbo.dv_store_items WHERE TRY_CAST(store_number AS INT)=@Store -- ensure you only select from actual integers AND vendor_number = @Vendor AND upc = @UPC ); </code></pre>