input
stringlengths
51
42.3k
output
stringlengths
18
55k
Disabling 'Submit' Button (while Processing on Server) without jQuery <p>I have an old legacy Web app where I can't add jQuery.</p> <p>When a form is submitted, a long server-side action takes place, and I need to disable 'Submit' until the response is rendered, or maybe the change the cursor.</p> <p>I found a solution here which shows the Loading banner on Submit, <a href="http://stackoverflow.com/a/30906566/1005607">http://stackoverflow.com/a/30906566/1005607</a></p> <p><strong>but it doesn't remove it when the page is rendered.</strong> There is a Forward action from my Struts Action class. How would I remove the banner once it's finished?</p> <pre><code>&lt;script type="text/javascript"&gt; function ShowLoading(e) { var div = document.createElement('div'); var img = document.createElement('img'); img.src = 'loading_bar.GIF'; div.innerHTML = "Loading...&lt;br /&gt;"; div.style.cssText = 'position: fixed; top: 5%; left: 40%; z-index: 5000; width: 422px; text-align: center; background: #EDDBB0; border: 1px solid #000'; div.appendChild(img); document.body.appendChild(div); return true; // These 2 lines cancel form submission, so only use if needed. //window.event.cancelBubble = true; //e.stopPropagation(); } &lt;/script&gt; &lt;form onsubmit="ShowLoading()"&gt; &lt;/form&gt; </code></pre>
<p>Target your button and set its disabled attribute to true.</p> <p><code>document.querySelector("button").setAttribute('disabled', true);</code></p> <p>I usually refer to this website when I need to make a change that isn't enough to require me to use jQuery. <a href="http://youmightnotneedjquery.com/" rel="nofollow">http://youmightnotneedjquery.com/</a></p>
Python Function Return Statement is Confusing and Complex <p>Could any body explain what do the 'and' and 'or' statements are doing in the return statement of the function below ? the function seems to be returning the largest common denominator of a and b. </p> <p> <code>def gcd(a,b): return b and gcd(b, a % b) or a</code></p> <p>Thank you !</p>
<p>The first thing we can do is put in some parenthesis:</p> <pre><code>((b and gcd(b, a % b)) or a) </code></pre> <p>Now lets take this piece by piece:</p> <pre><code>b and gcd(b, a % b) </code></pre> <p>This will give <code>b</code> if <code>b</code> is falsy. Otherwise it'll give you <code>gcd(b, a % b)</code>. In other words, it's equivalent to the following conditional expression:</p> <pre><code>b if not b else gcd(b, a % b) </code></pre> <p>The next part of the expression is:</p> <pre><code>(...) or a </code></pre> <p>Which will give you <code>a</code> if the previous expression has a falsy result, otherwise it'll give you the previous expression.</p> <p>Note that this <em>might</em> not be what you're expecting if you come from a language like <code>C</code> where boolean operations return booleans :-). In python, the only boolean operation that is <em>guaranteed</em> to return a boolean is <code>not</code>. This all tends to "just work" however because python knows how to get an object's "truth value" when it needs it. e.g.:</p> <pre><code>if obj: ... </code></pre> <p>will actually check <code>bool(obj)</code> implicitly.</p> <hr> <p>So, if I were to write out the whole thing using <code>if</code> suites, it would look like:</p> <pre><code>def gcd(a, b): if not b: # Likely `b == 0`. This is the recursion base-case. val = b else: val = gcd(b, a % d) if val: return val else: return a </code></pre>
How to Print Letters Out of CRM <p>I have a client that frequently response with "snail mail" for Cases. They want to be able to select a response letter type (they have around 50+ standard letter types they choose from) on the Case, and then at their leisure, go and print off the mailing labels, letters, and a pick list (like an actual pick list, not a CRM PickList/OptionSet) that matches the letter to the mailing label, and anything else they need to send to the customer (coupon, rebate, etc.).</p> <p>Whats the best way to handle this with minimal code?</p>
<p>If they have the budget I would say buy a product specifically for this purpose. Your client will gain a significant feature set for their investment. For example; <a href="http://www.mscrm-addons.com/Products/DocumentsCorePack" rel="nofollow">DCP</a> or <a href="http://www.xperido.com/" rel="nofollow">XperiDo</a>.</p>
Wordpress - Disable and hide all controls on video <p>How to disable and hide all controls on Wordpress 4.6.1 videos?</p> <p>Following my actual code inside a WordPress page:</p> <pre><code>[video width="560" height="320" mp4="example.com/test.mp4" loop="true" autoplay="true" preload="auto"][/video] </code></pre>
<p>Hi you need to override the inline styles applied to .mejs-controls div for that video shortcode. You can: </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-css lang-css prettyprint-override"><code>.mejs-controls { display: none !important; visibility: hidden !important; }</code></pre> </div> </div> </p> <p>These controls normally only show on hover unless you tell them to do otherwise. I would ask why you want to disable the controls, taking this ability away from the user can result in her being frustrated with this restriction. </p> <p>I found a bit more information here on this post: <a href="http://wordpress.stackexchange.com/questions/130402/hide-default-video-shortcode-controls-on-pageload">http://wordpress.stackexchange.com/questions/130402/hide-default-video-shortcode-controls-on-pageload</a></p>
JAVA 2D String array column numbers <p>I have a CSV file which I have to read to a 2D string array (it must be a 2D array)</p> <p>However it has different column number, like: </p> <blockquote> <p>One, two, three, four, five</p> <p>1,2,3,4</p> </blockquote> <p>So I want to read those into an array. I split it everything is good, however I don't know how not to fill the missing columns with NULLs.</p> <p>The previous example is:</p> <blockquote> <p>0: one,two,three,four,five (length 5)</p> <p>1: 1,2,3,4,null (length 5)</p> </blockquote> <p>However I want the next row's length to be 4 and not 5 without null.</p> <p>Is this possible?</p> <p>This is where I've got so far (I know it's bad):</p> <pre><code>public static void read(Scanner sc) { ArrayList&lt;String&gt; temp = new ArrayList&lt;&gt;(); while(sc.hasNextLine()) { temp.add(sc.nextLine().replace(" ", "")); } String[] row = temp.get(0).split(","); data = new String[temp.size()][row.length]; for (int i = 0; i &lt; temp.size(); ++i) { String[] t = temp.get(i).split(","); for (int j = 0; j &lt; t.length; ++j) { data[i][j] = t[j]; } } } </code></pre>
<p>Sounds like you want a non-rectangular 2-dimensional array. You'll want to avoid defining the second dimension on your 2D array. Here's an example:</p> <pre><code>final Path path = FileSystems.getDefault().getPath("src/main/resources/csvfile"); final List&lt;String&gt; lines = Files.readAllLines(path); final String[][] arrays = new String[lines.size()][]; for (int i = 0; i &lt; lines.size(); i++) { arrays[i] = lines.get(i).split(","); } </code></pre> <p>All lines are read into a List so that we know the first dimension of the 2D array. The second dimension for each row is determined by the result of the split operation.</p>
Trouble getting object from parsed JSON output <p>I'm playing around with the twitter API and i'm trying to parse the json output. However somehow i'm doing something wrong and I'm not getting what I would like to get. </p> <p>In this case i'm writing in PHP. Started looping thru the array and screen_name and text are working accordingly. </p> <pre><code>foreach ($statuses as $obj) { $screen_name = filter_var($obj-&gt;user-&gt;screen_name, FILTER_SANITIZE_STRING); $text = filter_var($obj-&gt;text, FILTER_SANITIZE_STRING); $urls = filter_var($obj-&gt;entities-&gt;urls-&gt;url, FILTER_SANITIZE_URL); } </code></pre> <p>the JSON array output:</p> <pre><code>array ( 0 =&gt; stdClass::__set_state(array( 'created_at' =&gt; 'Fri Oct 07 15:31:01 +0000 2016', 'text' =&gt; 'test', 'entities' =&gt; stdClass::__set_state(array( 'hashtags' =&gt; array ( 0 =&gt; stdClass::__set_state(array( 'text' =&gt; '30Under30', 'indices' =&gt; array ( 0 =&gt; 36, 1 =&gt; 46, ), )), ), 'symbols' =&gt; array ( ), 'user_mentions' =&gt; array ( ), 'urls' =&gt; array ( 0 =&gt; stdClass::__set_state(array( 'url' =&gt; 'https://Forbes.com', 'expanded_url' =&gt; 'https://twitter.com/i/web/status/784415744427687936', 'display_url' =&gt; 'twitter.com/i/web/status/7…', 'indices' =&gt; array ( 0 =&gt; 117, 1 =&gt; 140, ), )), ), )), 'source' =&gt; 'Sprinklr', 'in_reply_to_screen_name' =&gt; NULL, 'user' =&gt; stdClass::__set_state(array( 'id' =&gt; 91478624, 'screen_name' =&gt; 'test', 'url' =&gt; 'http://Forbes.com', 'entities' =&gt; stdClass::__set_state(array( 'url' =&gt; stdClass::__set_state(array( 'urls' =&gt; array ( 0 =&gt; stdClass::__set_state(array( 'url' =&gt; 'http://Forbes.com', 'expanded_url' =&gt; 'http://forbes.com', 'display_url' =&gt; 'forbes.com', 'indices' =&gt; array ( 0 =&gt; 0, 1 =&gt; 22, ), )), ), )), 'description' =&gt; stdClass::__set_state(array( 'urls' =&gt; array ( 0 =&gt; stdClass::__set_state(array( 'url' =&gt; 'http://Forbes.com', 'expanded_url' =&gt; 'http://Forbes.com', 'display_url' =&gt; 'Forbes.com', 'indices' =&gt; array ( 0 =&gt; 28, 1 =&gt; 48, ), )), ), )), )), 'protected' =&gt; false, 'notifications' =&gt; false, )), 'geo' =&gt; NULL, 'lang' =&gt; 'en', )), ) </code></pre>
<p>Since <code>urls</code> is an array, you need to index it.</p> <pre><code>$urls = filter_var($obj-&gt;entities-&gt;urls[0]-&gt;url, FILTER_SANITIZE_URL); </code></pre>
d3.js reverse transition does not work <p>I am working on horizontal segment bar chart. I want to make it so that the bar chart will animate the colour transition between individual segments depending on the value that is generated randomly every few seconds. </p> <p>I also have a text box that at the moment says "hello" and it is moving simultaneously with the transition.It works only in one direction from left to right. I cannot make the colour transition between segments and translating the text box from left to right. From left to right I mean that the number generated last time is greater than the currently generated number. The bar chart should turn off the segments from right to left. But it does it from left to right also the text box is acting weirdly when it comes to reverse translation. </p> <p>I am also getting this error: g attribute transform: Expected transform function, "null". In my code I want to make a transition on my valueLabel and I think the way I am using is not correct. Despite this error the code gets executed. My fiddle code is <a href="https://jsfiddle.net/milka22/n9wnjbk5/7/" rel="nofollow">here</a></p> <p>Many thanks for suggestions</p> <pre><code>var configObject = { svgWidth : 1000, svgHeight : 1000, minValue : 1, maxValue : 100, midRange : 50, highRange : 75, numberOfSegments : 50 }; //define variables var newValue; var gaugeValue = configObject.minValue - 1; var mySegmentMappingScale; var rectArray=[]; //define svg var svg = d3.select("body").append("svg") .attr("width", configObject.svgWidth) .attr("height", configObject.svgHeight) .append("g") .attr("transform", 'translate(' + configObject.svgWidth/2 + ',' + configObject.svgHeight/2 + ')'); //var myG=svg.append('g'); var valueLabel= svg.append("text") .attr('x',0) .attr('y', (configObject.svgHeight/13)+15) .text("hello"); var backgroundRect=svg.append("rect") .attr("fill", "black") .attr("x",0) .attr("y", 0) .attr("width", (configObject.svgWidth/3)) .attr("height", configObject.svgHeight/13); for(i = 0; i &lt;= configObject.numberOfSegments; i++){ var myRect=svg.append("rect") .attr("fill", "#2D2D2D") .attr("x",i * ((configObject.svgWidth/3)/configObject.numberOfSegments)) .attr("y", 0) .attr("id","rect"+i) .attr("width", ((configObject.svgWidth/3)/configObject.numberOfSegments)-3) .attr("height", configObject.svgHeight/13); rectArray.push(myRect); } //define scale function setmySegmentMappingScale(){ var domainArray = []; var x=0; for(i = configObject.minValue; i &lt;= configObject.maxValue+1; i = i + (configObject.maxValue - configObject.minValue)/configObject.numberOfSegments){ if(Math.floor(i) != domainArray[x-1]){ var temp=Math.floor(i); domainArray.push(Math.floor(i)); x++; } } var rangeArray = []; for(i = 0; i &lt;= configObject.numberOfSegments+1; i++){// &lt;= rangeArray.push(i); } mySegmentMappingScale = d3.scale.threshold().domain(domainArray).range(rangeArray); } //generate random number function generate(){ var randomNumber = Math.random() * (configObject.maxValue - configObject.minValue) + configObject.minValue; newValue = Math.floor(randomNumber); setmySegmentMappingScale(); animateSVG(); } function animateSVG(){ var previousSegment = mySegmentMappingScale(gaugeValue) -1; var newSegment = mySegmentMappingScale(newValue) -1; if(previousSegment &lt;= -1 &amp;&amp; newSegment &gt; -1){ for(i = 0; i &lt;= newSegment; i++){ rectArray[i].transition() .ease("linear") .duration(50) .delay(function(d){return i * 90}) .styleTween("fill", function() { return d3.interpolate( "#2D2D2D","red"); }); valueLabel .transition().ease("linear") .duration(50) .delay(function(d){return i * 90}) .attr("transform","translate(" + (i * ((configObject.svgWidth/3)/configObject.numberOfSegments)+((configObject.svgWidth/3)/configObject.numberOfSegments)) + "," + 0 + ")") } } else if(newSegment &gt; previousSegment){ for(i = previousSegment; i &lt;= newSegment; i++){ rectArray[i].transition() .ease("linear") .duration(50) .delay(function(d){return i * 90}) .styleTween("fill", function() { return d3.interpolate( "#2D2D2D","red"); }); //console.log(temp); valueLabel .transition() .ease("linear") .duration(50) .delay(function(d){return i * 90}) .attr("transform","translate(" + (i * ((configObject.svgWidth/3)/configObject.numberOfSegments)+((configObject.svgWidth/3)/configObject.numberOfSegments)) + "," + 0 + ")") } } else if(newSegment &lt; previousSegment){ for(i = previousSegment; i &gt; newSegment; i--){ rectArray[i].transition() .ease("linear") .duration(50) .delay(function(d){return i * 90}) .styleTween("fill", function() { return d3.interpolate( "red","#2D2D2D"); }); valueLabel .transition() .ease("linear") .duration(50) .delay(function(d){return i * 90}) .attr("transform","translate(" + (i * ((configObject.svgWidth/3)/configObject.numberOfSegments)-((configObject.svgWidth/3)/configObject.numberOfSegments)) + "," + 0 + ")") } } gaugeValue = newValue; } setInterval(function() { generate() }, 8000); </code></pre>
<p>The problem is just the <code>delay</code>.</p> <p>When <code>newSegment &gt; previousSegment</code>, you set the delay like this:</p> <pre><code>.delay(function(d){return i * 90}) </code></pre> <p>Which makes sense, because <code>i</code> is an increasing variable. But, when <code>newSegment &lt; previousSegment</code> the same math doesn't work anymore: <code>i</code> is a decreasing variable, and the delay has to increase as <code>i</code> <em>decreases</em>, not the other way around.</p> <p>This is what you need:</p> <pre><code>.delay(function(d){return Math.abs(i -previousSegment)*90}) </code></pre> <p>Here is your updated fiddle: <a href="https://jsfiddle.net/b7usw2nr/" rel="nofollow">https://jsfiddle.net/b7usw2nr/</a></p>
ConcurrentModificationException - HashMap <p>Consider the following code.</p> <pre><code>Map&lt;Integer,String&gt; map = new HashMap&lt;Integer, String&gt; (5); map.put(1, "a"); map.put(2, null); map.put(3, "b"); map.put(4, "e"); for (String str : map.values()) { if ("b".equals(str)) { map.put(5, "f"); } } System.out.println(map.get(5)); </code></pre> <p>It is gonna occurred ConcurrentModificationException. In this situation, I understood that we can not modify the collections which we're iterating. <br> However, Please Consider the following code. I only remove one line which is <code>map.put(4,"e");</code> <br>It will work!<br> </p> <pre><code>Map&lt;Integer,String&gt; map = new HashMap&lt;Integer, String&gt; (5); map.put(1, "a"); map.put(2, null); map.put(3, "b"); for (String str : map.values()) { if ("b".equals(str)) { map.put(5, "f"); } } System.out.println(map.get(5)); </code></pre> <p><br></p> <p>Any tips? why this is happening? </p>
<p>"b" become last element. </p> <p>The check is performed in <code>next</code> method of iterator and it is not called anymore. </p>
PHP Sleep Function 2 days time? <p>I'm trying to find a way to execute a function (send some emails), 2 days after a new table is inserted into the database. I would like to do this without cron if possible, so I was wondering if is too wrong to use the sleep function, with 2 days time? Or any other suggestion.. </p>
<p>You can use <strong>SCHEDULE</strong> to set schedule for database query.</p> <p>Maybe this question is already solved <a href="http://stackoverflow.com/questions/13872598/autorunning-query-in-mysql">here</a></p>
Why do both insertion and extraction into/from a std::priority_queue take logarithmic time? <blockquote> <p>A [<a href="http://en.cppreference.com/w/cpp/container/priority_queue" rel="nofollow"><code>std::priority_queue</code></a>] is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of <strong>logarithmic insertion and extraction</strong>.</p> </blockquote> <p>Why is that? I think the sorting either happens on insertion or extraction. For example, if the sorting happens on insertion and the internal container remains sorted, wouldn't the extraction be able to happen in constant time? The top element to be removed is know and so is the next smaller one.</p> <p>However, both <a href="http://en.cppreference.com/w/cpp/container/priority_queue/push" rel="nofollow"><code>std::priority_queue::push</code></a> and <a href="http://en.cppreference.com/w/cpp/container/priority_queue/pop" rel="nofollow"><code>std::priority_queue::pop</code></a> mention in their complexity descriptions:</p> <blockquote> <h2>Complexity</h2> <p>Logarithmic number of comparisons</p> </blockquote> <p>Why would <strong>both</strong> have to perform comparisons? With an internal container that stays sorted, extraction should be easy or vice versa, with sorting upon extraction, insertion should be easy.</p> <p>I guess my assumption about when and how the sorting happens (or if there's any sorting happening at all) is just wrong. Could somebody please shed some light on this?</p>
<blockquote> <p>For example, if the sorting happens on insertion and the internal container remains sorted, wouldn't the extraction be able to happen in constant time? </p> </blockquote> <p>Extract could happen in constant time, but insertion would become <code>O(n)</code>. You'd have to search for the place in the list to insert the new element and then shift all the other elements. <code>O(1)</code> extraction and <code>O(n)</code> insertion might be good for some use-cases, but not the problem that <code>priority_queue</code> is trying to solve.</p> <p>If sorting, on the other hand, happened on extraction, then you'd have <code>O(n lg n)</code> extraction and <code>O(1)</code> insertion. Which, again, is good for some use-cases, but that's not what <code>priority_queue</code> does.</p> <hr /> <p>Rather than sorting elements, <code>std::priority_queue</code> stores its elements<sup>&dagger;</sup> in a <a href="https://en.wikipedia.org/wiki/Binary_heap" rel="nofollow">heap</a>, which by construction has <code>O(lg n)</code> insertion and extraction. The structure is a tree, and insertion/extraction simply maintain the tree invariant. For some problems (like, say, search), in cases where we need to insert and extract many nodes, having <code>O(lg n)</code> for both operations is far superior than <code>O(n)/O(1)</code>. </p> <p>As an example, and stealing images from Wikipedia, inserting the element 15 into the heap would initially place it at position <code>x</code>:</p> <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/Heap_add_step1.svg/225px-Heap_add_step1.svg.png" alt="init"></p> <p>then swap it with the <code>8</code> (because the sorted invariant is broken):</p> <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/16/Heap_add_step2.svg/225px-Heap_add_step2.svg.png" alt="2nd step"></p> <p>then finally swap it with the <code>11</code>:</p> <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Heap_add_step3.svg/225px-Heap_add_step3.svg.png" alt="final step"></p> <p>In array form, the initial heap would be stored as:</p> <pre><code>[11, 5, 8, 3, 4] </code></pre> <p>and we would end up at:</p> <pre><code>[15, 5, 11, 3, 4, 8] </code></pre> <p>Extraction is just the reverse operation - bubbling down instead of bubbling up. As you see, there's no explicit "sorting" going on. We're not even touching most of the elements most of the time. </p> <hr /> <p><sup>&dagger;</sup><code>std::priority_queue</code> is a container adapter, but the container you provide should be a random access container with <code>O(1)</code> complexities for indexing, <code>push_back</code>, <code>pop_back</code>, <code>front</code>, <code>back</code>, etc. So the choice of container (unless you make a bad one) does not affect the overall complexity of <code>priority_queue</code>'s operations. </p>
Swift3 CoreData crash on iOS9 device <p>I have CoreData app that is perfectly working on iOS10, written in Swift3, supporting iOS 8.4 and above.</p> <p>When I try to run it on iOS 9.3.5 I'm getting error:</p> <pre><code>2016-10-07 17:47:20.596 FormApp[710:179733] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSSet intersectsSet:]: set argument is not an NSSet' </code></pre> <p>crashing on line:</p> <pre><code>form.addToOpenQuestions(openQuestion) </code></pre> <p>I have added @objc() to managed object classes. Then I'm getting new error:</p> <pre><code>CoreData: warning: Unable to load class named 'FormApp.Form' for entity 'Form'. Class not found, using default NSManagedObject instead. </code></pre> <p>It is happening on line:</p> <pre><code>let form = NSEntityDescription.insertNewObject(forEntityName: "Form", into: managedObjectContext) as! Form </code></pre> <p>My config:</p> <p><a href="http://i.stack.imgur.com/AzSZq.png" rel="nofollow"><img src="http://i.stack.imgur.com/AzSZq.png" alt="Settings of enity"></a></p> <p><a href="http://i.stack.imgur.com/784v2.png" rel="nofollow"><img src="http://i.stack.imgur.com/784v2.png" alt="Class"></a></p> <p><a href="http://i.stack.imgur.com/GOitj.png" rel="nofollow"><img src="http://i.stack.imgur.com/GOitj.png" alt="Model"></a></p> <p><a href="http://i.stack.imgur.com/Xp4HL.png" rel="nofollow"><img src="http://i.stack.imgur.com/Xp4HL.png" alt="Properties extension"></a></p> <p>All classes were generated by Xcode. I have tried deleting Module and all configurations. Anyone have idea how to make it work?</p>
<p>For some reason NSSet is expected, but your NSManagedObject code has NSOrderedSet, which is a subclass of NSObject. Try to remove "Arrangment: Ordered" checkmark in your core data model and refactor those relationships to NSSet. Not sure why this happens in iOS 10 but not in iOS 9 though.</p> <p>P.S. Perhaps you should reconsider your Core Data model? It looks like your Open/Closed questions are going to change their status. If so, I would recommend to make one Question entity with <code>closed</code> bool or <code>status</code> int.</p>
How to remove the border of a Tkinter OptionMenu Widget <p>I have been looking through multiple websites, which only give me a half satisfactory answer, how would I colour each part of of a Tkinter OptionMenu Widget?</p> <p>Code Snippet:</p> <pre><code>from tkinter import * root = Tk() text = StringVar() fr = Frame (root,bg="yellow") fr.grid() menu = OptionMenu (fr, text, "hi", "there") menu.grid (pady=50, padx=50) # Pretty colouring goes here # Or ugly yellow, I don't mind menu ["menu"] ["bg"] = "yellow" menu ["bg"] = "yellow" menu ["activebackground"] = "green" root.mainloop() </code></pre> <p>Or should I just give up and settle for grey?</p>
<p>I don't understand your problem.</p> <p>menu["menu"] is a tkinter.Menu object, so you can set others options.</p> <p>Possible colors options are :</p> <ul> <li>activebackground -> that you want </li> <li>activeforeground -> that you want</li> <li>background</li> <li>bg</li> <li>disabledforeground</li> <li>fg</li> <li>foreground </li> <li>selectcolor</li> </ul>
How to Grab data from database using JQuery Sortable <p>I am attempting to create a menu that allows the user to click and drag the list items into a new order. The list data is pulled from a database. I've managed to code the click and drag feature for my menu however, I am struggling to then save the data in the new order after the user has clicked and dragged. </p> <p>This is my code for the sortable, it all works except for the line with var objmodel. When this variable is created it manages to grab an empty object from the database and populate the empty object with the new shuffle function value. What i need it to do is to grab the object that the user has clicked on to then populate that object with the new order.</p> <p>Data Example:</p> <ol> <li>cookie 2.biscuit 3.chocolate.</li> </ol> <p>after re order by user:</p> <p>1.chocolate 2.biscuit 3.cookies</p> <pre><code> $(document).ready(function () { $('#MenuItem tbody').sortable({ axis: 'y', update: function (event, ui) { var order = 1; var model = []; $("#MenuItem tbody tr").each(function () { var objModel = { id: $(this).find("#MenuItem").data("model"), ShuffleFunction: order }; model.push(objModel); order++; }); } }); }); &lt;table id = "MenuItem" class="promo full-width alternate-rows" style="text-align: center;"&gt; &lt;!-- Cedric Kehi DEMO CHANGE --&gt; &lt;tr&gt; &lt;th&gt;Product Code &lt;/th&gt; &lt;th&gt;Product Template &lt;/th&gt; @*&lt;th&gt; @Html.DisplayNameFor(model =&gt; model.IndexList[0].Priority) &lt;/th&gt; &lt;th&gt; @Html.DisplayNameFor(model =&gt; model.IndexList[0].WindowProduct) &lt;/th&gt;*@ &lt;th&gt;Description &lt;!-- JACK EDIT --&gt; &lt;/th&gt; &lt;th&gt;Actions&lt;/th&gt; &lt;/tr&gt; &lt;tbody &gt; @foreach (var item in Model.IndexList) { &lt;tr id ="trendingDisplay"&gt; &lt;td class="center-text"&gt; @Html.DisplayFor(modelItem =&gt; item.ProductCode) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.ProductTemplate.Description) &lt;/td&gt; @*&lt;td class="center-text"&gt; @Html.DisplayFor(modelItem =&gt; item.Priority) &lt;/td&gt; &lt;td class="center-text"&gt; @Html.Raw(item.WindowProduct ? "Yes" : "No") &lt;/td&gt;*@ &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.Description) &lt;/td&gt; </code></pre> <p> @Html.ActionLink(" ", "Edit", new { id = item.ProductID }, new { title = "Edit", @class = "anchor-icon-no-text edit" }) @Html.ActionLink(" ", "Details", new { id = item.ProductID }, new { title = "Details", @class = "anchor-icon-no-text details" }) @Html.ActionLink(" ", "Delete", new { id = item.ProductID }, new { title = "Delete", @class = "anchor-icon-no-text delete" }) </p> <pre><code> &lt;/td&gt; &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; </code></pre>
<p>Please Review: <a href="http://api.jqueryui.com/sortable/#event-update" rel="nofollow">http://api.jqueryui.com/sortable/#event-update</a></p> <blockquote> <p><strong>update( event, ui )</strong></p> <p>This event is triggered when the user stopped sorting and the DOM position has changed.</p> <p><strong>ui</strong></p> <ul> <li>item</li> </ul> <p>Type: jQuery</p> <p>The jQuery object representing the current dragged element.</p> </blockquote> <p>If you wish to make use of the item that the user grabbed and moved, you would use <code>ui.item</code>. From your example. This may look like:</p> <pre><code>var objModel = { id: ui.item.data("model"), ShuffleFunction: order }; </code></pre> <p>Since you did not provide any HTML or working example of the items, I cannot confirm if this would work.</p>
Python Threading: Making the thread function return from an external signal <p>Could anyone please point out whats wrong with this code. I am trying to return the thread through a variable flag, which I want to control in my main thread. </p> <h1>test27.py</h1> <pre><code>import threading import time lock = threading.Lock() def Read(x,y): flag = 1 while True: lock.acquire() try: z = x+y; w = x-y print z*w time.sleep(1) if flag == 0: print "ABORTING" return finally: print " SINGLE run of thread executed" lock.release() </code></pre> <h1>test28.py</h1> <pre><code>import time, threading from test27 import Read print "Hello Welcome" a = 2; b = 5 t = threading.Thread(target = Read, name = 'Example Thread', args = (a,b)) t.start() time.sleep(5) t.flag = 0 # This is not updating the flag variable in Read FUNCTION t.join() # Because of the above command I am unable to wait until the thread finishes. It is blocking. print "PROGRAM ENDED" </code></pre>
<p>Regular variables should not be tracked in threads. This is done to prevent race condition. You must use thread-safe constructs to communicate between threads. For a simple flag use <code>threading.Event</code>. Also you cannot access local variable <code>flag</code> via thread object. It is local, and is only visible from scope. You must either use a global variable, as in my example below or create an Object before calling your thread and use a member variable.</p> <pre><code>from threading import Event flag = Event() def Read(x,y): global flag flag.clear() ... if flag.is_set(): return </code></pre> <p>main thread:</p> <pre><code>sleep(5) flag.set() </code></pre> <p>P.S.: I just noticed that you attempted to use lock() in the thread, but failed to use it in the main thread. For a simple flag go with Event. For a lock() you need to lock both parts and mitigate a risk of a deadlock. </p>
Calling updateDateRangeInput within a Shiny module <p>I have a Shiny application with multiple <code>plot_ly</code> charts on a single page using the same date range. For complicated reasons, I would like each chart in a separate module and be reactive to <code>plot_ly</code> zooms.</p> <p>The way I did this pre-module was to capture <code>plotly_relayout</code> and have it call <code>updateDateRangeInput</code> to set the entire page to that range, which then cascaded through my other <code>plot_ly</code> charts. Now that we're modularizing these charts, I'm unable to have the same behavior. I capture the redraw event, but calling <code>updateDateRangeInput</code> on the parent date range seems to have no effect.</p> <p>I've tried using the namespace's session as well as passing the parent's session and calling with it.</p> <h2>Very simplified code:</h2> <p>app.R:</p> <pre><code>library(shiny) source("mod.R", local = TRUE) ui &lt;- shinyUI(fluidPage( chartTimeseriesUI("myseries") , dateRangeInput("dateRange", "Select Date Range:" , start = Sys.Date() - 600 , end = Sys.Date() , min = Sys.Date() - 1200 , max = Sys.Date() ) )) server &lt;- shinyServer(function(input, output, session) { callModule(chartTimeseries, id = "myseries", reactive(input$dateRange), session) }) shinyApp(ui = ui, server = server) </code></pre> <p>mod.R:</p> <pre><code>chartTimeseriesUI &lt;- function(id) { ns &lt;- NS(id) plotlyOutput(outputId = ns("timeseries")) } chartTimeseries &lt;- function(input, output, session, dateRange, psession) { regionRedraw &lt;- reactive({ print("I'm in redraw") d &lt;- event_data("plotly_relayout", source = "timeseries") if(is.null(d)) { # double click startdate &lt;- Sys.Date() - 600 enddate &lt;- Sys.Date() } else { xstart &lt;- d$`xaxis.range[0]` xend &lt;- d$`xaxis.range[1]` if (is.null(xstart)) { startdate &lt;- Sys.Date() - 600 enddate &lt;- Sys.Date() } else { # Take our X time and convert it out of milliseconds startdate &lt;- as.POSIXlt(xstart/1000, origin="1970-01-01", tz="America/New_York") enddate &lt;- as.POSIXlt(xend/1000, origin="1970-01-01", tz="America/New_York") } } absmindate &lt;- Sys.Date() - 1200 absmaxdate &lt;- Sys.Date() updateDateRangeInput(psession, dateRange, label="Now for a new range:", start=startdate, end=enddate, min=absmindate, max=absmaxdate) }) observe({ print("date range changed!") d &lt;- regionRedraw() }) output$timeseries &lt;- renderPlotly({ rangestart &lt;- dateRange()[1] rangeend &lt;- dateRange()[2] diff_in_days = as.numeric(difftime(rangeend, rangestart, units = "days")) tm &lt;- seq(0, diff_in_days, by = 10) x &lt;- rangeend - tm y &lt;- rnorm(length(x)) p &lt;- plot_ly(x = ~x , y = ~y , type = "scatter" , mode = "markers" , text = paste(tm, "days from today") , source = "timeseries") }) } </code></pre> <h2>Output</h2> <pre><code>[1] "date range changed!" [1] "I'm in redraw" </code></pre> <p>And then when I select a region, I get:</p> <pre><code>[1] "date range changed!" [1] "I'm in redraw" </code></pre> <p>And the plot zooms in, the date range does not change to the new selection and the <code>dateRangeInput</code> label does not change.</p> <p>I appreciate any help! </p>
<p>I was able to get this to work by updating the date range outside of the module: The module:</p> <pre><code>chartTimeseriesUI &lt;- function(id) { ns &lt;- NS(id) plotlyOutput(outputId = ns("timeseries")) } chartTimeseries &lt;- function(input, output, session, dateRange) { regionRedraw &lt;- reactive({ print("I'm in redraw") d &lt;- event_data("plotly_relayout", source = "timeseries") if(is.null(d)) { # double click startdate &lt;- Sys.Date() - 600 enddate &lt;- Sys.Date() } else { xstart &lt;- d$`xaxis.range[0]` xend &lt;- d$`xaxis.range[1]` if (is.null(xstart)) { startdate &lt;- Sys.Date() - 600 enddate &lt;- Sys.Date() } else { # Take our X time and convert it out of milliseconds startdate &lt;- as.POSIXlt(xstart/1000, origin="1970-01-01", tz="America/New_York") enddate &lt;- as.POSIXlt(xend/1000, origin="1970-01-01", tz="America/New_York") } } absmindate &lt;- Sys.Date() - 1200 absmaxdate &lt;- Sys.Date() # reactive list instead of update list(dateRange=dateRange(),start=startdate, end=enddate-1, min=absmindate, max=absmaxdate) }) observe({ print("date range changed!") d &lt;- regionRedraw() }) output$timeseries &lt;- renderPlotly({ rangestart &lt;- dateRange()[1] rangeend &lt;- dateRange()[2] diff_in_days = as.numeric(difftime(rangeend, rangestart, units = "days")) tm &lt;- seq(0, diff_in_days, by = 10) x &lt;- rangeend - tm y &lt;- rnorm(length(x)) p &lt;- plot_ly(x = ~x , y = ~y , type = "scatter" , mode = "markers" , text = paste(tm, "days from today") , source = "timeseries") }) # return list to update date input later return(reactive(regionRedraw())) } </code></pre> <p>Example App:</p> <pre><code>library(shiny) library(plotly) source("mod.R", local = TRUE) ui &lt;- shinyUI(fluidPage( chartTimeseriesUI("myseries") , dateRangeInput("dateRange", "Select Date Range:" , start = Sys.Date() - 600 , end = Sys.Date()-1 , min = Sys.Date() - 1200 , max = Sys.Date() ) )) server &lt;- shinyServer(function(input, output, session) { # receive return z &lt;- callModule(chartTimeseries, id = "myseries", reactive(input$dateRange)) observe({ vals &lt;- z() # update date updateDateRangeInput(session, "dateRange",start=vals$start,end=vals$end) }) }) shinyApp(ui = ui, server = server) </code></pre>
search by class in string javascript <p>Let's suppose I have this string:</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 myhtml= "&lt;html&gt;&lt;body&gt;&lt;div class='header'&gt;Welcome&lt;/div&gt;&lt;div class='news' id='new_1'&gt;Lorem ipsum....&lt;/div&gt;&lt;div class='news' id='new_2'&gt;dolor sit amet...&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;";</code></pre> </div> </div> </p> <p>Well, if this was on a normal website I could use "getElementsbyClassName" to get all elements with the class I want to select (In my case, "news"). But... If it's like this case, when you have all the html in a variable, how can I get them? Is there a way to get all the divs with class is "news"?</p>
<p>You can use <a href="https://github.com/cheeriojs/cheerio">cheerio</a> for that:</p> <pre><code>var cheerio = require('cheerio'); var myhtml = "&lt;html&gt;&lt;body&gt;&lt;div class='header'&gt;Welcome&lt;/div&gt;&lt;div class='news' id='new_1'&gt;Lorem ipsum....&lt;/div&gt;&lt;div class='news' id='new_2'&gt;dolor sit amet...&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;"; var $ = cheerio.load(myhtml); console.log($('.header').html() );//Welcome </code></pre>
autoit.pixel_search returning color is not found <p>I'm trying to grab the coordinates for a specific pixel value on the screen, but I can't seem to get any results. The error I get is "autoit.autoit.AutoItError: color is not found".</p> <p>To verify my code I have the mouse move the the pixel that has the colour I want. This is not necessary, it was just part of a test. I have two monitors and my fear was that the pixel search couldn't distinguish what monitor I wanted. So to test autoit knew where to look I did a basic "move mouse". Sure enough it moved to my image on monitor one, so I know it has the right monitor.</p> <p>Second I tested if the "autoit.pixel_get_color" could grab the value I wanted, it does (65281).Thought I might have to use the decimal instead of the HEX provided from the Windows Info application.</p> <p>I tested with the code below, this is the code using SciTE - light (.au3 file) and it works fine.</p> <pre><code>$coord = PixelSearch(0, 0, 1434, 899, 0x00FF02) If Not @error Then MsgBox(0, "X and Y are:", $coord[0] &amp; "," &amp; $coord[1]) EndIf </code></pre> <p>I tested grabbing the pixel with pyautogui and ultimately I can do it, but it is not as "clean" as autoit, so I'm trying to avoid it if possible. Autoit has that nice Window info screen that shows me the color, so it is really easy to just plug numbers into my script.</p> <p>Here is the code I have written currently in Python.</p> <pre><code>import autoit import pyautogui pyautogui.confirm('Press OK to start running script') autoit.mouse_move(374,608,10) # move mouse to where the color I want is located. pixelcolor = autoit.pixel_get_color(374,608) #get color of pixel pixelsearch = autoit.pixel_search(0,0,1434,899,0x00FF02) # search entire screen for color pixelsearch = autoit.pixel_search(0,0,1434,899,65281) # Tried using the value from the get_color, still same error. </code></pre> <p>Any Ideas?</p>
<p>So I figured out how to resolve my problem. I don't know why it works or what caused the problem, but for now here is the solution</p> <p>The correct formula for PixelSearch is PixelSearch(left, top, right, bottom). </p> <p>After playing around with the numbers it appears pyautoit is using (right, top, left, bottom). If I plug in my numbers with that formula it works perfectly, EXCEPT on my third monitor. </p> <p>My third monitor seems to work with (left, top, right, bottom). I am wondering if it has something to do with negative numbers (-1680, 0, -3, 1050), not 100% sure.</p> <p>I tested this on my work computer (two monitors), home computer, (three monitors), and my laptop. In all scenarios the (right, top, left, bottom) worked, except home computer on the third monitor.</p> <p>Hope this helps someone else out in the future.</p>
please explain "#variable" vs "let variable" in angular 2 <p><a href="http://i.stack.imgur.com/whQUr.png" rel="nofollow">Code Snapshot</a></p> <p>In the above picture when i use <code>#course of courses</code> in <code>*ngFor</code> it does not work. If i use <code>let course of courses</code> it works. Please explain this</p>
<p>This changed from the <code>Beta</code> version of Angular 2 to the <code>RC</code> version.</p> <p>Now it's <code>let</code> instead of <code>#</code> to not mix up with template variables.</p>
Why can't I use moment as an import in my TypeScript React native project? <p>I want to use <a href="http://momentjs.com" rel="nofollow">MomentJS</a> in my ReactNative component using TypeScript. My project is configured to pull in the <a href="https://github.com/moment/moment/blob/develop/moment.d.ts" rel="nofollow">library's d.ts file</a> from the <em>node_modules</em> directory.</p> <p>This is how I am importing the library and using it:</p> <pre><code>import * as moment from "moment"; const time = moment(); </code></pre> <p>My typescript compiles but when I run the app ReactNative errors as so:</p> <p><a href="http://i.stack.imgur.com/CTqEI.png" rel="nofollow"><img src="http://i.stack.imgur.com/CTqEI.png" alt="ReactNative error"></a></p> <p>This is my <em>tsconfig.json</em> file:</p> <pre><code>{ "compilerOptions": { "target": "es6", "moduleResolution": "node", "jsx": "react", "outDir": "build/", "sourceMap": true, "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true } } </code></pre> <p>If I change my tsconfig 'target' to es5 I have problems with a number of other modules.</p> <p>I think it is related to <a href="http://stackoverflow.com/questions/36893165/importing-moment-into-typescript-project">this question</a> but I am doing as suggested in that question's answer. </p>
<p>Quoting from <a href="http://stackoverflow.com/questions/36893165/importing-moment-into-typescript-project?noredirect=1&amp;lq=1#comment61356347_36893860">@DavidD's comment in the linked answer</a>:</p> <blockquote> <p>Be careful if you use babel on top of the above syntax, babel will prevent the function <code>moment()</code> from work as expected, due to how it associates with the spec. You can add <code>"allowSyntheticDefaultImports": true</code> to your tsconfig.json to allow <code>import moment from "moment";</code> to no longer throw an error.</p> </blockquote> <p>The underlying issue is that <code>moment</code> exports a function as the default, but when using Babel (as you are in React Native) this will get wrapped in an object by Babel.</p> <p>I'm not sure if TypeScript is aware of this wrapping or if the definitions for momentjs need an update.</p>
NotImplementedException but already call the method in C# <p>I would like to know, why did the NotImplementedException(); still appear even though I'm pretty sure that I have called the method?</p> <p>this is the throw exception in my dsNBC.xsd designer:</p> <pre><code>internal int getLastIDbyMaxPeg() { throw new System.NotImplementedException(); } </code></pre> <p>and this is how I called the method in PegawaiControl.cs in a folder named Control :</p> <pre><code>public int getNumID() { return Peg.getLastIDbyMaxPeg(); } public string generateIDPeg() { string id = "PEG"; return id + Convert.ToString(getNumID() + 1); } </code></pre> <p>and in the boundary layout I just called the generateIDPeg() into a local variable like this : <code>string idPegw = PC.generateIDPeg();</code> </p> <p>Well, getLastIDbyMaxPeg() is a name of method in the query dataset of dsNBC.xsd that I created. So the actual implementation code for that method is the query in dataset. I got consufed here how can I implement the query as the actual implementation in the throw exception? <a href="http://i.stack.imgur.com/tKrnw.png" rel="nofollow">You can see the StackTrace here</a></p> <p>Can you help me? </p>
<p>You have to remove that code and replace it with your actual implementation.<br> The method has not been implemented (i.e. made to actually <em>do</em> something, rather than throwing the <code>NotImplementedException</code>), only called. </p> <p>It will not just automatically remove itself because you <em>call</em> the method, you must supply the implementation. </p> <p>Place your logic inside of the method and remove the current line to fix your situation: </p> <pre><code>internal int getLastIDbyMaxPeg() { //Do some things //return some int value } </code></pre>
Python list out of function <p>I Need <code>['1', '2', '3']</code> to become this <code>[1, 2, 3]</code></p> <p>This is my actual code:</p> <pre><code>def chain_a_list_int(p_chain :str): tab_chain=[] # [str] tab_int=[] # [int] (list to return) tab_chain = p_chain.split(",") tab_chain = [int(i) for i in tab_chain] tab_int.append(tab_chain) return tab_int </code></pre> <p>and return it to use it like that: </p> <pre><code>chain_a_list_int(input("enter the number to conserve: ")) </code></pre> <p>but it give me this error when i print it out of the function:</p> <pre><code>&lt;function chain_a_list_int at 0x000000000349FEA0&gt; </code></pre> <p>when i try to print i use this: </p> <pre><code> print(chaine_a_liste_entier) </code></pre> <p>when i print <code>tab_int</code> <strong>in the function</strong> it work pretty well but it's not when i'm out of it...</p> <pre><code>print(tab_int) </code></pre> <p>Result...</p> <pre><code>[1, 2, 3] </code></pre>
<p>That's not an error, but an indication that Python doesn't think that you have asked it to call <code>chain_a_list_int</code>. The minimal tweak to your code is:</p> <pre><code>the_list = chain_a_list_int(input("enter the number to conserve: ")) print(the_list) </code></pre> <p>or</p> <pre><code>print(chain_a_list_int(input("enter the number to conserve: "))) </code></pre> <p>A reference to the name of the function <code>chain_a_list_int</code>, without a <code>(</code> after it, does not actually cause the function's code to run. This distinction will be useful to you later on &mdash; for now, make sure any time you type the name of a function, you put a parenthesized expression after that name. (If @ForceBru posts an answer, you'll see a counterexample :) .)</p>
symfony user query return fields I don't specify when I am logged In <p>In my symfony app, using fosuserbundle too, this is a <strong>DQL</strong> query I create to recover all data I need concerning user:</p> <pre><code>public function getAlluserNeedlesInfo() { return $this-&gt;getEntityManager() -&gt;createQuery( 'SELECT partial u.{id, username, email, roles, enabled, createdAt, updatedAt}, partial c.{id, companySiret, companyName, professional, firstName, lastName, slug, createdAt, updatedAt} FROM AppBundle:User u JOIN u.consumer c ORDER BY u.id ASC' ) -&gt;getResult(); } </code></pre> <p>This is my controller method code:</p> <pre><code>public function usersAction() { $em = $this-&gt;getDoctrine()-&gt;getManager(); $users = $em-&gt;getRepository('AppBundle:User')-&gt;getAlluserNeedlesInfo(); $serializedEntity = $this-&gt;container-&gt;get('serializer')-&gt;serialize($users, 'json'); return new Response($serializedEntity); } </code></pre> <p>For now all works well, this is the results in json format returning by my controller method:</p> <pre><code>[{ "id": 1, "username": "test", "email": "test@test.com", "enabled": true, "roles": [], "consumer": { "id": 1, "professional": false, "last_name": "TEST", "first_name": "test", "slug": "test-test", "created_at": "2016-10-07T03:22:32+0200", "updated_at": "2016-10-07T17:42:17+0200" }, "created_at": "2016-10-02T07:28:28+0200", "updated_at": "2016-10-09T01:05:04+0200" }, { "id": 2, "username": "admin", "email": "admin@test.com", "enabled": true, "roles": ["ROLE_ADMIN"], "consumer": { "id": 2, "company_name": "admin", "company_siret": "01234567890006", "professional": true, "last_name": "ADMIN", "first_name": "Admin", "slug": "admin-admin", "created_at": "2016-10-06T08:45:23+0200", "updated_at": "2016-10-07T07:59:34+0200" }, "created_at": "2016-09-04T12:14:03+0200", "updated_at": "2016-10-09T03:03:00+0200" }, { "id": 3, "username": "test2", "email": "test2@test.com", "enabled": false, "roles": [], "consumer": { "id": 3, "company_name": "test2", "company_siret": "02896452300006", "professional": true, "last_name": "TEST2", "first_name": "test2", "slug": "test2-test2", "created_at": "2016-10-07T03:22:32+0200", "updated_at": "2016-10-07T17:42:17+0200" }, "created_at": "2016-10-07T17:28:08+0200", "updated_at": "2016-10-07T17:28:08+0200" }, { "id": 4, "username": "ju", "email": "j.val@gmail.com", "enabled": true, "roles": [], "consumer": { "id": 4, "professional": false, "last_name": "Val", "first_name": "ju", "slug": "val-ju", "created_at": "2016-10-07T18:07:06+0200", "updated_at": "2016-10-07T18:07:06+0200" }, "created_at": "2016-10-07T18:07:06+0200", "updated_at": "2016-10-07T18:07:06+0200" }] </code></pre> <p>All works well, but I notice that If I am logged in with one of these users (for example <strong>Val-Ju</strong>), the query returns me <strong>some other credentials and data</strong> I don't specify in, for example:</p> <pre><code>[{ "id": 1, "username": "test", "email": "test@test.com", "enabled": true, "roles": [], "consumer": { "id": 1, "professional": false, "last_name": "TEST", "first_name": "test", "slug": "test-test", "created_at": "2016-10-07T03:22:32+0200", "updated_at": "2016-10-07T17:42:17+0200" }, "created_at": "2016-10-02T07:28:28+0200", "updated_at": "2016-10-09T01:05:04+0200" }, { "id": 2, "username": "admin", "email": "admin@test.com", "enabled": true, "roles": ["ROLE_ADMIN"], "consumer": { "id": 2, "company_name": "admin", "company_siret": "01234567890006", "professional": true, "last_name": "ADMIN", "first_name": "Admin", "slug": "admin-admin", "created_at": "2016-10-06T08:45:23+0200", "updated_at": "2016-10-07T07:59:34+0200" }, "created_at": "2016-09-04T12:14:03+0200", "updated_at": "2016-10-09T03:03:00+0200" }, { "id": 3, "username": "test2", "email": "test2@test.com", "enabled": false, "roles": [], "consumer": { "id": 3, "company_name": "test2", "company_siret": "02896452300006", "professional": true, "last_name": "TEST2", "first_name": "test2", "slug": "test2-test2", "created_at": "2016-10-07T03:22:32+0200", "updated_at": "2016-10-07T17:42:17+0200" }, "created_at": "2016-10-07T17:28:08+0200", "updated_at": "2016-10-07T17:28:08+0200" }, { "id": 4, "username": "ju", "username_canonical": "ju", "email": "j.val@gmail.com", "email_canonical": "j.val@gmail.com", "enabled": true, "salt": "5ng0rXXXXXXXXXXccwowscs4s", "password": "$2yXXXXXXXXXXXXXXXXXXXXXXXXXX1HgIHe42rz\/agpB.0fC", "last_login": "2016-10-07T18:15:32+0200", "locked": false, "expired": false, "roles": [], "credentials_expired": false, "consumer": { "id": 4, "professional": false, "last_name": "Val", "first_name": "ju", "slug": "val-ju", "created_at": "2016-10-07T18:07:06+0200", "updated_at": "2016-10-07T18:07:06+0200" }, "created_at": "2016-10-07T18:07:06+0200", "updated_at": "2016-10-07T18:15:32+0200" }] </code></pre> <p>Of course, this is a thing I don't want, and it's a non-desired behavior.</p> <blockquote> <p>Why this behavior ocurred ?</p> </blockquote>
<p>It's the default serialization configuration for FOSUserBundle, if you're logged in, it will serialize all your stuff.</p> <p>What you need is to override this configuration. It can be done by adding</p> <pre><code># src/MyBundle/Resources/config/serialization/Model.User.yml FOS\UserBundle\Model\User: exclusion_policy: ALL properties: username: expose: true groups: ["aGroupIfNeeded"] #... </code></pre> <p>If you want more informations about <a href="http://symfony.com/doc/current/serializer.html#using-serialization-groups-annotations" rel="nofollow">serialization groups</a>.</p>
Query Left Join with OR Inefficiency <p>I have a table (200K rows) with a field called "Campaign". I have a separate table list of campaigns with additional information. I want to join on <code>where (campaign_id = campaign) OR (cid.spend_source = a.Traffic_Source AND a.Campaign = cid.Campaign_Name)</code>.</p> <p>The problem I'm facing is that the OR statement is killing efficiency, causing a nested loop with 400 million rows.</p> <p>What's a better method?</p> <pre><code>UPDATE a SET a.campaign_name = cid.Campaign_Name, a.Campaign_ID = cid.Campaign_ID FROM database.dbo.table a LEFT JOIN carb.dbo.carb_lookup_campaignid cid ON cid.Campaign_ID = a.Campaign OR ( cid.spend_source = a.Traffic_Source AND a.Campaign = cid.Campaign_Name ) </code></pre>
<p>Do two separate <code>left join</code>s:</p> <pre><code>UPDATE a SET a.campaign_name = coalesce(cidss.Campaign_Name, cidlc.Campaign_Name), a.Campaign_ID = coalesce(cidss.Campaign_ID, cidlc.Campaign_ID) FROM database.dbo.table a LEFT JOIN carb.dbo.carb_lookup_campaignid cidss ON cidss.Campaign_ID = a.Campaign and cidss.spend_source = a.Traffic_Source LEFT JOIN carb.dbo.carb_lookup_campaignid cidlc ON cidlc.Campaign_ID = a.Campaign and cidlc.Campaign_Name = a.Campaign and cidss.Campaign_ID is null WHERE cidss.Campaign_ID is not null or cidls.Campaign_ID is not null; </code></pre> <p>Each individual <code>LEFT JOIN</code> can take advantage of the appropriate index <code>(Campaign_ID, spend_source)</code> and <code>(Campaign_ID, Campaign_Name)</code>.</p>
Continue to next blob in the ForEach Block when there is an exception in the Catch block <p>I have many xmls in Azure Storage container. I wrote code to strip off unnecessary data elements from those xmls. To list all the xmls in different folder structures I used</p> <pre><code>var blobs = container.ListBlobs(prefix: &lt;Root Location of Blobs&gt;, useFlatBlobListing: true); foreach (CloudBlockBlob blob in blobs) </code></pre> <p>And to parse the xml I am using Linq.</p> <p>The problem I am facing is there are few xmls that are missing the proper format or few xmls that doesn't have closing literals. I want to catch the exception and skip that xml file from processing and proceed to the next one. How can I do that using the Try catch block ?</p> <p>The exception I get is <code>System.Xml.XmlException</code></p>
<p>Try</p> <pre><code> foreach (CloudBlockBlob blob in blobs){ bool isError = false; try { // do your code here; }catch(Exception ex){ isError = true; } if(isError) continue; } </code></pre> <p>Update: </p> <pre><code>void Main() { string[] list = new string[]{"bob", "jack", "tom", "sparrow"}; foreach(string li in list){ try{ if(String.Equals(li, "tom")){ throw new Exception("Fault"); } Debug.WriteLine(li); }catch(Exception ex){ Debug.WriteLine(ex.Message); continue; } } } </code></pre> <p>Prints:</p> <pre><code>bob jack Fault sparrow </code></pre>
Swift: How to make a change to a variable load next time the application is opened <p>I have some global settings variables that are occasionally changed by the user during the apps runtime. I want to make the users change permanent, but at the moment every time the app is then reloaded it reverts to the original values e.g. user changes SettingsVariables.settingTwo to false, but then when the app is rerun the variables value changes back to true (the original value).</p> <pre><code>import UIKit struct SettingsVariables { static var settingOne = 0 static var settingTwo = true } </code></pre>
<p>What you need is to create <code>UserDefaults</code> values these will be in the memory even when you close and restart your app.</p> <pre><code>// Set UserDefaults.standard.set(123, forKey: "key") // Get UserDefaults.standard.integer(forKey: "key") </code></pre> <p>So basically you could do this in your <code>AppDeletegates</code> <code>applicationWillTerminate</code>.</p> <pre><code>UserDefaults.standard.set(SettingsVariables.settingOne, forKey: "settingOne") </code></pre> <p>and then when your app start again you can do</p> <p><code>SettingsVariables.settingOne = UserDefaults.standard.integer(forKey: "settingOne")</code></p> <p>If you want to use your <code>Struct</code>.</p> <p><strong>Update</strong><br> For Swift 2 as you are using, the syntax is this:</p> <pre><code>// Set NSUserDefaults.standardUserDefaults().setInteger(123, forKey: "key") // Get NSUserDefaults.standardUserDefaults().integerForKey("key") </code></pre>
mySQL empty SELECT in SELECT shouldn't return null for the whole query <p>I'm using a select in a select, like this : </p> <pre><code>SELECT id, ( SELECT name FROM xxx WHERE xxx ) as y FROM xxx </code></pre> <p>But this y is null. And because of this, the whole query is returning null. I want this y to be a 0 if it is equal to null so not to change the result of the whole query which should return several tuples.</p> <p>Here my full query : </p> <pre><code> SELECT id, begin, end, location_id, out_location_id, lat, lng, out_lat, out_lng, LEFT(TIMEDIFF(end, begin), 5) as duration, ( SELECT LEFT(TIMEDIFF(end, begin), 5) FROM timeslots l WHERE user_id = '.$userId.' AND type = '.Timeslot::LUNCH.' AND parent_id = t.id ) as lunch, ( SELECT LEFT(TIMEDIFF(end, begin), 5) FROM timeslots o WHERE user_id = '.$userId.' AND type = '.Timeslot::OVERTIME.' AND parent_id = t.id ) as overtime FROM timeslots t WHERE user_id = '.$userId.' AND approved = 1 AND type = '.Timeslot::DAY.' AND DATE(begin) &gt;= "'.$startDay.'" AND DATE(end) &lt;= "'.$endDay.'" ORDER BY begin </code></pre> <p>I tried COALESC(y, 0) and IFNULL(y, 0) but it doesn't work :/</p> <p>thanks for you help</p> <h1>UPDATE</h1> <p>I just noticed that when I remove the first subquery, it works ! So it means that the issues comes from this first subquery and not both of them. What's changing the result of the whole query is the line type = Timeslot::LUNCH (which is 2). But on the second subquery I have Timeslot::OVERTIME which is 3 so it's the same thing but it's working...</p>
<p>This is too long for a comment.</p> <p>Subqueries in the <code>SELECT</code> are called <em>scalar</em> subqueries. These always return one column and at most one row. If they return no rows, then the value is <code>NULL</code>.</p> <p>They <em>do not</em> filter rows out of the result set. It is as simple as that.</p> <p>In other words, <em>nothing</em> you do in the two subqueries in the <code>SELECT</code> will affect the number of rows returned. They only affect the value for that particular column.</p>
No resource found that matches the given name: attr 'andr oid:textColor <p>I get this error:</p> <blockquote> <p>Error:(2118, 21) No resource found that matches the given name: attr 'andr oid:textColor'.</p> </blockquote> <p>On this line in the file values.xml: </p> <pre><code>&lt;item name="andr oid:textColor"&gt;@color/menu_section_header&lt;/item&gt; </code></pre> <p>(note the spaces after "andr")</p> <p>The file is app\build\intermediates\res\merged\debug\values\values.xml</p> <p>I just added this dependency to the app build.gradle file:</p> <pre><code>compile 'com.android.support:preference-v7:24.2.1' </code></pre> <p>Also in there are:</p> <pre><code>compile 'com.android.support:appcompat-v7:24.2.0' compile compile 'com.android.support:design:24.2.0' </code></pre> <p>This existing solutions to this error involve conflicting SDKs (e.g. compiled SDK version is 23 and support library is 24). This does not appear to be the case here.</p> <p>Project Structure settings:</p> <blockquote> <p>The following SDKs installed:<br> Android 7.0 (Nougat) 24 2 Installed<br> Android 6.0 (Marshmallow) 23 3 Installed<br> Android 5.1 (Lollipop) 22 2 Installed<br> Android 5.0 (Lollipop) 21 2 Installed<br> Android 4.4W (KitKat Wear) 20 2 Installed<br> Android 4.4 (KitKat) 19 4 Installed </p> </blockquote> <pre><code>Compile SDK Verson: API 24: Android 7.0 (Nougat) Min Sdk Version: API 19: Android 4.4 (KitKat) Target SDK Verson: API 24: Android 7.0 (Nougat) </code></pre> <p>What am I missing?</p> <p>Edit:</p> <p>I've found the problem thanks to @BlackBelt and @LahruiPinto.</p> <p>What I didn't understand about the build process is that apparently all values from all files in the "res/values" are put into a intermediate file called "values.xml". In my file res/values/styles.xml, I had a CR/LF after "item name="andr" which presented itself as spaces in the values.xml file. I'm not sure why it didn't flag the error in the styles.xml file. After fixing the styles.xml, the project built correctly.</p>
<p>I think the error because of the space in the below line.</p> <p>change </p> <pre><code>&lt;item name="andr oid:textColor"&gt;@color/menu_section_header&lt;/item&gt; </code></pre> <p>to</p> <pre><code>&lt;item name="android:textColor"&gt;@color/menu_section_header&lt;/item&gt; </code></pre>
jQuery hiding group of containers that don't match index <p>I have multiple containers like this, each with a string of text within them. However, these containers may have the same string of text as another.</p> <pre><code>&lt;div class="main"&gt;one&lt;/div&gt; &lt;div class="main"&gt;two&lt;/div&gt; &lt;div class="main"&gt;one&lt;/div&gt; &lt;div class="main"&gt;three&lt;/div&gt; &lt;div class="main"&gt;two&lt;/div&gt; &lt;div class="main"&gt;one&lt;/div&gt; &lt;button class="example" id="one"&gt;One&lt;/button&gt; &lt;button class="example" id="two"&gt;Two&lt;/button&gt; &lt;button class="example" id="three"&gt;Three&lt;/button&gt; </code></pre> <pre class="lang-js prettyprint-override"><code>$(".example").click(function(){ var index = $(this).attr("id"); $(".main").each(function(){ var example = $(this).find(".example").text(); if( example.indexOf(index) &gt;= 0 ){ // hide every .main container that doesn't contain matching index } }); }); </code></pre> <p>For this example, I just want to toggle one at a time and show only the selected container based on the button id. </p> <p>I'm having trouble working out the <em>not</em> logic part of hiding all other containers that don't match the index, its the <code>$(this)</code> part that's stumping me.</p>
<p>You can use simpler code. <a href="https://api.jquery.com/contains-selector/" rel="nofollow"><code>:contains()</code></a> select element has spesific text. Use it in <a href="https://api.jquery.com/not-selector/" rel="nofollow"><code>:not()</code></a> selector.</p> <pre><code>$(".example").click(function(){ $(".main").show(); $(".main:not(:contains("+ this.id +"))").hide(); }); </code></pre> <p>Or show/hide in one line:</p> <pre><code>$(".example").click(function(){ $(".main").show().filter(":not(:contains("+ this.id +"))").hide(); }); </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(".example").click(function(){ $(".main").show(); $(".main:not(:contains("+ this.id +"))").hide(); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="main"&gt;one&lt;/div&gt; &lt;div class="main"&gt;two&lt;/div&gt; &lt;div class="main"&gt;one&lt;/div&gt; &lt;div class="main"&gt;three&lt;/div&gt; &lt;div class="main"&gt;two&lt;/div&gt; &lt;div class="main"&gt;one&lt;/div&gt; &lt;button class="example" id="one"&gt;One&lt;/button&gt; &lt;button class="example" id="two"&gt;Two&lt;/button&gt; &lt;button class="example" id="three"&gt;Three&lt;/button&gt;</code></pre> </div> </div> </p>
Using .asof and MultiIndex in Pandas <p>I've seen this question asked a few times but with no answer. The short version:</p> <p>I have a pandas <code>DataFrame</code> with a two-level <code>MultiIndex</code> index; both levels are integers. How can I use <code>.asof()</code> on this <code>DataFrame</code>?</p> <p>Long version:</p> <p>I have a <code>DataFrame</code> with some time series data:</p> <pre><code>&gt;&gt;&gt; df A 2016-01-01 00:00:00 1.560878 2016-01-01 01:00:00 -1.029380 ... ... 2016-01-30 20:00:00 0.429422 2016-01-30 21:00:00 -0.182349 2016-01-30 22:00:00 -0.939461 2016-01-30 23:00:00 0.009930 2016-01-31 00:00:00 -0.854283 [721 rows x 1 columns] </code></pre> <p>I'm then constructing a weekly model of that data:</p> <pre><code>&gt;&gt;&gt; df['weekday'] = df.index.weekday &gt;&gt;&gt; df['hour_of_day'] = df.index.hour &gt;&gt;&gt; weekly_model = df.groupby(['weekday', 'hour_of_day']).mean() &gt;&gt;&gt; weekly_model A weekday hour_of_day 0 0 0.260597 1 0.333094 ... ... 20 0.388932 21 -0.082020 22 -0.346888 23 1.525928 [168 rows x 1 columns] </code></pre> <p>That's what gives me a <code>DataFrame</code> with the index described above.</p> <p>I'm now trying to extrapolate that model into an annual time series:</p> <pre><code>&gt;&gt;&gt; dates = pd.date_range('2015/1/1', '2015/12/31 23:59', freq='H') &gt;&gt;&gt; annual_series = weekly weekly weekly_model &gt;&gt;&gt; annual_series = weekly_model.A.asof((dates.weekday, dates.hour)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/core/series.py", line 2657, in asof locs = self.index.asof_locs(where, notnull(values)) File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/indexes/base.py", line 1553, in asof_locs locs = self.values[mask].searchsorted(where.values, side='right') ValueError: operands could not be broadcast together with shapes (8760,) (2,) &gt;&gt;&gt; dates = pd.date_range('2015/1/1', '2015/12/31 23:59', freq='H') &gt;&gt;&gt; annual_series = weekly_model.A.asof((dates.weekday, dates.hour)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/core/series.py", line 2657, in asof locs = self.index.asof_locs(where, notnull(values)) File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/indexes/base.py", line 1553, in asof_locs locs = self.values[mask].searchsorted(where.values, side='right') ValueError: operands could not be broadcast together with shapes (8760,) (2,) </code></pre> <p>What does this error mean, and what's the best way of doing this?</p> <p>The best I've come up with so far is this:</p> <pre><code>&gt;&gt;&gt; annual_series = weekly_model.A.loc[list(zip(dates.weekday, dates.hour))] </code></pre> <p>It works, but it means turning the <code>zip</code> iterator into a list first, which is not exactly memory-friendly. Is there a way of avoiding this?</p>
<p>I read your post multiple times and I think I finally get what you are trying to achieve.</p> <p>try this:</p> <pre><code>df['weekday'] = df.index.weekday df['hour_of_day'] = df.index.hour weekly_model = df.groupby(['weekday', 'hour_of_day']).mean() dates = pd.date_range('2015/1/1', '2015/12/31 23:59', freq='H') </code></pre> <p>then use merge like this:</p> <pre><code>annual_series = pd.merge(df.reset_index(), weekly_model.reset_index(), on=['weekday', 'hour_of_day']).set_index('date') </code></pre> <p>now you can use asof since you have dates as index</p> <pre><code>annual_series.asof(dates) </code></pre> <p>is that what you were looking for?</p>
Bitbake does not install my files in my rootfs <p>My aim is to create Bitbake recipe, that will install config file in /etc directory, and script, that will apply this config into /ect/init.d directory (and invoke update-rc-d). I already saw another similar question (<a href="http://stackoverflow.com/questions/34067897/bitbake-not-installing-my-file-in-the-rootfs-image">Bitbake not installing my file in the rootfs image</a>). I did almost exactly what this guy did, but unfortunately it didn't work. The problem is that Bitbake does not complain on anything, but just not adds these files to rootfs. Here is my current recipe. I also put my script and config files to two directories: files, and alsa-config, which resides inside recipe directory. </p> <pre><code>SUMMARY = "Alsa Config" DESCRIPTION = "Adds alsa configuration file, and startup script that applies it." LICENSE = "MIT" LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302" SRC_URI += " \ file://my-alsa-config \ file://asound.state \ " PACKAGE_ARCH = "${MACHINE_ARCH}" S = "${WORKDIR}" INITSCRIPT_NAME = "my-alsa-config" INITSCRIPT_PARAMS = "defaults 99 01" inherit autotools update-rc.d do_install() { install -m 0644 ${WORKDIR}/asound.state ${D}${sysconfdir} } FILES_${PN} += "${sysconfdir}/asound.state" </code></pre> <p>In my local.conf I added line:</p> <pre><code>CORE_IMAGE_EXTRA_INSTALL += "alsa-config " </code></pre> <p>Please, can anybody help?</p>
<p>Fortunately, I was able to solve the problem. Here is the solution:</p> <pre><code>SUMMARY = "Alsa Config" DESCRIPTION = "Adds alsa configuration file, and startup script that applies it." LICENSE = "MIT" LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302" SRC_URI += " \ file://my-alsa-config \ file://asound.state \ " PACKAGE_ARCH = "${MACHINE_ARCH}" S = "${WORKDIR}" INITSCRIPT_NAME = "my-alsa-config" INITSCRIPT_PARAMS = "defaults 99 01" inherit autotools update-rc.d do_install() { install -d ${D}${sysconfdir}/init.d/ install -m 0755 ${WORKDIR}/my-alsa-config ${D}${sysconfdir}/init.d/ install -m 0644 ${WORKDIR}/asound.state ${D}${sysconfdir}/ } FILES_${PN} += "${sysconfdir}/asound.state \ ${sysconfdir}/my-alsa-config" </code></pre> <p>A little bit of comments:</p> <ol> <li>PACKAGE_ARCH has to be set properly. In my case, when I didn't have it, execute permissions for script file were not set for some reason.</li> <li>do_install() has to create every directory, that is needed. Even if I know, that in my rootfs there will be /etc directory, I have to create it. And I'm not sure if it is necessary, but it's better to have slash at the end of install directory, just in case.</li> <li>Init scripts that are to be installed to launch at startup has to be installed too;)</li> <li>Scripts must have proper permissions set.</li> </ol>
Why are the old bars still visible after transition <p>I have a D3 barchart which has 5 bars. When I update it I can see it transitioning to the correct 3 bars but some of the original bars are left visible - how do I make them exit?</p> <p>This is what it initially looks like:</p> <p><a href="http://i.stack.imgur.com/G0yFC.png" rel="nofollow"><img src="http://i.stack.imgur.com/G0yFC.png" alt="enter image description here"></a></p> <p>This is what it ends up looking like:</p> <p><a href="http://i.stack.imgur.com/C57dL.png" rel="nofollow"><img src="http://i.stack.imgur.com/C57dL.png" alt="enter image description here"></a></p> <p>The dark blue bars are correct. The current code for updating the "rect" objects is the following:</p> <pre><code>var plot = d3.select("#barChartPlot") .datum(currentDatasetBarChart); /* Note that here we only have to select the elements - no more appending! */ plot.selectAll("rect") .data(currentDatasetBarChart) .transition() .duration(750) .attr("x", function (d, i) { return xScale(i); }) .attr("width", width / currentDatasetBarChart.length - barPadding) .attr("y", function (d) { return yScale(+d.measure); }) .attr("height", function (d) { return height - yScale(+d.measure); }) .attr("fill", colorChosen); </code></pre>
<p>You only have 3 new bars, so the number of elements on your data has changed. You need to use the <a href="https://bl.ocks.org/mbostock/3808218" rel="nofollow">update pattern</a>.</p> <pre><code>var rects = plot.selectAll("rect") .data(currentDatasetBarChart); rects.enter() .append("rect") //Code to style and define new rectangles. //Update rects.update() .transition() .duration(750) .attr("x", function (d, i) { return xScale(i); }) .attr("width", width / currentDatasetBarChart.length - barPadding) .attr("y", function (d) { return yScale(+d.measure); }) .attr("height", function (d) { return height - yScale(+d.measure); }) .attr("fill", colorChosen); // Remove unused rects rects.exit().remove(); </code></pre>
Swift 3 error: Type 'Any' has no subscript members <p>So I know this question has been asked and answered numerous times before, but I just migrated my project to Swift 3 and Im getting a ton of these errors in my code that parses JSON and I couldn't quite find answers that made me understand how to resolve my specific issue. </p> <pre><code>guard let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] else { return } guard let responseData = result["Data"] else { return } guard let userData = responseData["UserProfile"] else { return } var userProfileFieldsDict = [String: String]() if let sessionToken = userData!["CurrentSessionToken"] as? NSString { userProfileFieldsDict["sessionToken"] = String(sessionToken) } } </code></pre> <p>The <code>if let sessionToken</code> line throws the aforementioned error, but not quite sure how you're supposed to deal with this in Swift 3? Could someone explain and suggest a best practice fix? </p> <p>Thanks a bunch!</p>
<p>If <code>responseData["UserProfile"]</code> is also a dictionary you'll probably want to cast it as such in you guard by saying <code>guard let userData = responseData["UserProfile"] as? [String : AnyObject] else { return }</code>. I suspect this will solve your problem.</p> <p>As a small aside, you don't need to force unwrap userData in your if let, because you've already unwrapped it in the guard.</p>
lodash filter on key with multiple values <p>I am trying to find out in <strong><code>lodash</code></strong> <code>javascript library</code>, how to find out filter array of objects multiple values of key. <em>something similar to SQL - WHERE KEY in (val1, val2) </em></p> <p>Having said, with following example : </p> <pre><code>var users = [ { 'user': 'barney', 'age': 36, 'active': true },   { 'user': 'fred',   'age': 40, 'active': false }, { 'user': 'Avding',   'age': 34, 'active': true } ]; _.filter(...) </code></pre> <p><strong>How can I find users, who's age in (34, 36) ??</strong> <em>numbers can also change runtime</em></p>
<p>Lodash's <a href="https://lodash.com/docs/4.16.4#filter" rel="nofollow">filter</a> accepts a predicate. You can create the predicate using partial application, so you can change the values easily:</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 users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }, { 'user': 'Avding', 'age': 34, 'active': true } ]; var predicate = function(start, end) { return function(user) { return _.inRange(user.age, start, end + 1); } } var result = _.filter(users, predicate(34, 36)); console.log('inRange', result); /** is equal predicate **/ var predicate = function() { var args = _.toArray(arguments); return function(user) { var equalToUserAge = _.partial(_.isEqual, user.age); return args.some(equalToUserAge); } } var result = _.filter(users, predicate(34, 40)); console.log('equals', result);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>You can also do this easily with vanilla JS as well (the example uses ES6):</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 users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false }, { 'user': 'Avding', 'age': 34, 'active': true } ]; const predicate1 = (start, end) =&gt; ({ age }) =&gt; age &gt;= start &amp;&amp; age &lt;= end; const result1 = users.filter(predicate1(34, 36)); console.log('in range', result1); const predicate2 = (...args) =&gt; ({ age }) =&gt; args.some((num) =&gt; age === num); const result2 = users.filter(predicate2(34, 40)); console.log('is equal', result2);</code></pre> </div> </div> </p>
Can someone help analyse my java code on an averaging program? <p>Hi so I've started learning java online for two weeks now, but as I watched those tutorials, I felt the only way I'd actually grasp that information was to practice it. My other programs worked great, but just when I decided to do something spectacular (for me only of course; a java expert would find creating this program mind-numbing), something went terribly wrong. I'd really appreciate if you could take a look at my code below of an averaging program that could average any amount of numbers you want, and tell me what in the world I did wrong.</p> <p>UPDATE: Eclipse just outputs a random number after typing in just one number and then shuts down the program. <a href="http://i.stack.imgur.com/HJWOW.png" rel="nofollow">Here is a snapshot where I type in the console to average 6 numbers and then start with the number 7, but for some reason, when I hit enter again, it outputs 8.</a></p> <pre><code>package justpracticing; import java.util.*; public class average{ int grade = 0; int average; Scanner notoaverage = new Scanner(System.in); System.out.println("Please enter the amount of numbers you'd like the average of! "); final int totalaverage = notoaverage.nextInt(); Scanner averagingno = new Scanner(System.in); System.out.println("Start typing in the " + totalaverage + " numbers"); int numbers = averagingno.nextInt(); int counter = 0; public void averagingnumbers(){ while(counter&lt;=totalaverage){ grade+=numbers; ++counter; } } public void printStatement(){ average = grade/totalaverage; System.out.println(average); } } </code></pre>
<p>It seems that you have created an <code>average</code> Object in another class, and are calling the methods given from a main class.</p> <p>I don't know what exactly you're having trouble with, but one problem is here: </p> <p><code>average = grade/totalaverage;</code> </p> <p>These 2 variables that you are dividing are both integers. That means that the result will also be an integer. This is called <a href="https://en.wikipedia.org/wiki/Truncation" rel="nofollow">truncation</a>. What you want to do is first convert at least one of the integers to a double: </p> <p><code>... = (grade * 1.0) / totalaverage;</code></p> <p>You also want your <code>average</code> variable to be a double instead of an integer so that it can be a lot more accurate.</p>
How do I build "gem install json"? <p>I’m using Rails 4.2.7. I’m trying to build this tutorial — <a href="https://github.com/webguyian/bookstore" rel="nofollow">https://github.com/webguyian/bookstore</a>, but getting a strange error, “An error occurred while installing json (1.8.0), and Bundler cannot continue.” So I tried “gem install json -v '1.8.0'”</p> <pre><code>localhost:bookstore-master davea$ gem install json -v '1.8.0' Building native extensions. This could take a while... ERROR: Error installing json: ERROR: Failed to build gem native extension. current directory: /Users/davea/.rvm/gems/ruby-2.3.0/gems/json-1.8.0/ext/json/ext/generator /Users/davea/.rvm/rubies/ruby-2.3.0/bin/ruby -r ./siteconf20161007-50119-1huurrz.rb extconf.rb creating Makefile current directory: /Users/davea/.rvm/gems/ruby-2.3.0/gems/json-1.8.0/ext/json/ext/generator make "DESTDIR=" clean current directory: /Users/davea/.rvm/gems/ruby-2.3.0/gems/json-1.8.0/ext/json/ext/generator make "DESTDIR=" compiling generator.c In file included from generator.c:1: ./../fbuffer/fbuffer.h:175:47: error: too few arguments provided to function-like macro invocation VALUE result = rb_str_new(FBUFFER_PAIR(fb)); ^ /Users/davea/.rvm/rubies/ruby-2.3.0/include/ruby-2.3.0/ruby/intern.h:797:9: note: macro 'rb_str_new' defined here #define rb_str_new(str, len) __extension__ ( \ ^ In file included from generator.c:1: ./../fbuffer/fbuffer.h:175:11: warning: incompatible pointer to integer conversion initializing 'VALUE' (aka 'unsigned long') with an expression of type 'VALUE (const char *, long)' (aka 'unsigned long (const char *, long)') [-Wint-conversion] VALUE result = rb_str_new(FBUFFER_PAIR(fb)); ^ ~~~~~~~~~~ 1 warning and 1 error generated. make: *** [generator.o] Error 1 make failed, exit code 2 Gem files will remain installed in /Users/davea/.rvm/gems/ruby-2.3.0/gems/json-1.8.0 for inspection. Results logged to /Users/davea/.rvm/gems/ruby-2.3.0/extensions/x86_64-darwin-14/2.3.0/json-1.8.0/gem_make.out </code></pre> <p>I don’t know what this means or how to correct it. Any ideas?</p>
<p>The version of the json gem you are using is not compatible with Ruby >= 2.2. Please use at least version 1.8.2 of the json gem with Ruby 2.3. </p> <p>See the <a href="https://github.com/flori/json/blob/master/CHANGES.md" rel="nofollow">Changelog</a> for details about changes in functionality and compatibility.</p> <p>That said, most of the time you don't even need an external gem to be able to work with JSON data in Ruby. The <a href="http://ruby-doc.org/stdlib-2.3.0/libdoc/json/rdoc/JSON.html" rel="nofollow">JSON module</a> shipped with Ruby's standard library is fully functional and compatible with Rails already.</p>
App freeze: Forcing zero-copy tile initialization as worker context is missing <p>I develop a cordova/phonegap application including several plugins. The App running on android with the cordova crosswalk plugin. After displaying the splash screen the app freezes sometimes on some special devices and produce the following error log msg: <code>E/chromium(11867): [ERROR:layer_tree_host_impl.cc(2263)] Forcing zero-copy tile initialization as worker context is missing</code></p> <p>The device list, configs and relevant logcat find above. I tried to cram the problem in different ways:</p> <ul> <li>tried different crosswalk versions, incl. latest beta</li> <li>tried different configs like hardwareAccelerated, L_DISABLE_3D, etc.</li> <li>removed several plugins</li> </ul> <p>But nothing seems to effect the problem. <strong>Any suggestions what else I could try?</strong></p> <hr> <p>Following devices affected:</p> <ul> <li>HTC One (4.4.3)</li> <li>HUAWEI Ascend P7 (4.4.2)</li> <li>ASUS Zenfone 4 (4.3)</li> </ul> <p>An example logcat:</p> <pre><code>10-07 12:42:07.362 I/ActivityManager( 757): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=***/.MainActivity} from pid 1084 10-07 12:42:07.362 D/PMS ( 757): acquireHCC(42a4e7e0): CPU_MIN_FREQ ActivityManager-MultiCore-Freq 0x100 757 1000 10-07 12:42:07.362 I/Intent ( 757): @test_code: getHtcIntentFlag: 0 obj: 1118425152 10-07 12:42:07.362 D/PMS ( 757): acquireHCC(42a146c0): CPU_MIN_FREQ PrismLaunchActivity_4 0x100 1084 10080 10-07 12:42:07.372 D/PMS ( 757): acquireWL(42858218): PARTIAL_WAKE_LOCK ActivityManager-Launch 0x1 757 1000 10-07 12:42:07.382 D/PMS ( 757): releaseHCC(42ad7ab0): CPU_MIN_NUM PrismScroll_2 0x400 10-07 12:42:07.382 D/PMS ( 757): releaseHCC(42ac3820): CPU_MIN_FREQ PrismScroll_2 0x100 10-07 12:42:07.392 I/FeedHostManager( 1084): [onPause] 10-07 12:42:07.392 I/FeedProviderManager( 1084): onPause 10-07 12:42:07.392 I/SocialFeedProvider( 1084): +onPause 10-07 12:42:07.392 I/SocialFeedProvider( 1084): -onPause 10-07 12:42:07.412 I/ActivityManager( 757): Start proc *** for activity ***/.MainActivity: pid=11867 uid=10195 gids={50195, 3003, 5012, 1028, 1015} 10-07 12:42:07.422 I/Launcher( 1084): updateWallpaperVisibility: true 10-07 12:42:07.492 I/TrimMemoryManager( 1084): [trimMemory] 20 10-07 12:42:07.492 W/ResourceType( 757): Skipping entry 0x7f04002b in package table 0 because it is not complex! 10-07 12:42:07.492 W/ResourceType( 757): Skipping entry 0x7f040029 in package table 0 because it is not complex! 10-07 12:42:07.542 W/dalvikvm(11867): VFY: unable to resolve static field 416 (SUPPORTED_ABIS) in Landroid/os/Build; 10-07 12:42:07.542 D/XWalkLib(11867): Pre init xwalk core in ***.MainActivity 10-07 12:42:07.552 D/XWalkLib(11867): Reserve class class org.xwalk.core.XWalkPreferences to ***.MainActivity 10-07 12:42:07.552 D/XWalkLib(11867): Reserve method setValue to ***.MainActivity 10-07 12:42:07.552 D/XWalkLib(11867): Reserve class class org.xwalk.core.XWalkPreferences to ***.MainActivity 10-07 12:42:07.552 D/XWalkLib(11867): Reserve method setValue to ***.MainActivity 10-07 12:42:07.552 D/XWalkLib(11867): Reserve class class org.xwalk.core.XWalkPreferences to ***.MainActivity 10-07 12:42:07.552 D/XWalkLib(11867): Reserve method setValue to ***.MainActivity 10-07 12:42:07.552 D/XWalkLib(11867): Reserve class class org.xwalk.core.XWalkPreferences to ***.MainActivity 10-07 12:42:07.552 D/XWalkLib(11867): Reserve method setValue to ***.MainActivity 10-07 12:42:07.552 D/XWalkLib(11867): Reserve object class org.crosswalk.engine.XWalkCordovaView to ***.MainActivity 10-07 12:42:07.562 D/XWalkLib(11867): Reserve object class org.crosswalk.engine.XWalkCordovaResourceClient to ***.MainActivity 10-07 12:42:07.562 D/XWalkLib(11867): Reserve method setResourceClient to ***.MainActivity 10-07 12:42:07.562 D/XWalkLib(11867): Reserve object class org.crosswalk.engine.XWalkCordovaUiClient to ***.MainActivity 10-07 12:42:07.562 D/XWalkLib(11867): Reserve method setUIClient to ***.MainActivity 10-07 12:42:07.562 W/dalvikvm(11867): VFY: unable to resolve virtual method 671: Landroid/content/Context;.getExternalMediaDirs ()[Ljava/io/File; 10-07 12:42:07.572 D/XWalkLib(11867): Reserve method setXWalkViewInternalVisibility to ***.MainActivity 10-07 12:42:07.572 D/XWalkLib(11867): Reserve method setSurfaceViewVisibility to ***.MainActivity 10-07 12:42:07.623 I/dalvikvm-heap(11867): Grow heap (frag case) to 14.256MB for 8294416-byte allocation 10-07 12:42:07.653 V/StatusBar(11867): StatusBar: initialization 10-07 12:42:07.653 D/XWalkActivity(11867): Initialize by XWalkActivity 10-07 12:42:07.653 D/XWalkLib(11867): DecompressTask started 10-07 12:42:07.653 W/ResourceType(11867): No package identifier when getting value for resource number 0x00000000 10-07 12:42:07.663 I/Adreno-EGL(11867): &lt;qeglDrvAPI_eglInitialize:381&gt;: EGL 1.4 QUALCOMM build: MINGHSUC_AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.047+PATCH[ES]_msm8960_refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.047__release_ENGG () 10-07 12:42:07.663 I/Adreno-EGL(11867): OpenGL ES Shader Compiler Version: 17.01.12.SPL 10-07 12:42:07.663 I/Adreno-EGL(11867): Build Date: 03/25/14 Tue 10-07 12:42:07.663 I/Adreno-EGL(11867): Local Branch: 10-07 12:42:07.663 I/Adreno-EGL(11867): Remote Branch: refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.047 10-07 12:42:07.663 I/Adreno-EGL(11867): Local Patches: c29912293421482fd51b7f36b91ae584f9993d66 Add support for KIT_KAT 10-07 12:42:07.663 I/Adreno-EGL(11867): 4b5d3e5bcfa9d9563f740840d7258e1c1efa6d5a egl14: add EGL_ANDROID_image_crop support 10-07 12:42:07.663 I/Adreno-EGL(11867): Recon 10-07 12:42:07.703 I/InputMethodManagerService( 757): Disable input method client, pid=1084 10-07 12:42:07.703 I/InputMethodManagerService( 757): Enable input method client, pid=11867 10-07 12:42:07.713 D/XWalkLib(11867): DecompressTask finished, 0 10-07 12:42:07.713 D/XWalkLib(11867): ActivateTask started 10-07 12:42:07.713 D/XWalkLib(11867): Attach xwalk core 10-07 12:42:07.713 D/XWalkLib(11867): [App Version] build:19.49.514.5, api:6, min_api:1 10-07 12:42:07.713 D/XWalkLib(11867): [Lib Version] build:19.49.514.5, api:6, min_api:5 10-07 12:42:07.713 D/XWalkLib(11867): XWalk core version matched 10-07 12:42:07.713 W/dalvikvm(11867): VFY: unable to resolve static field 416 (SUPPORTED_ABIS) in Landroid/os/Build; 10-07 12:42:07.713 I/System (11867): exec(getprop ro.product.cpu.abi @ org.xwalk.core.internal.XWalkViewDelegate.&lt;clinit&gt;:329) 10-07 12:42:07.743 D/XWalkLib(11867): Device ABI: armeabi-v7a 10-07 12:42:07.803 W/dalvikvm(11867): VFY: unable to resolve instance field 306 10-07 12:42:07.813 I/cr_LibraryLoader(11867): Time to load native libraries: 1 ms (timestamps 8975-8976) 10-07 12:42:07.813 I/cr_LibraryLoader(11867): Expected native library version number "", actual native library version number "" 10-07 12:42:07.813 D/XWalkLib(11867): Native library is built for ARM 10-07 12:42:07.813 D/XWalkLib(11867): XWalk core architecture matched 10-07 12:42:07.813 D/XWalkLib(11867): Running in embedded mode 10-07 12:42:07.833 D/XWalkLib(11867): Dock xwalk core 10-07 12:42:07.833 D/XWalkLib(11867): Init core bridge 10-07 12:42:07.833 D/XWalkLib(11867): Init xwalk view 10-07 12:42:07.833 W/XWalkInternalResources(11867): org.xwalk.core.R$styleable.ButtonCompat is not int. 10-07 12:42:07.833 I/ActivityManager( 757): Displayed ***/.MainActivity: +431ms 10-07 12:42:07.853 W/XWalkInternalResources(11867): org.xwalk.core.R$styleable.ButtonCompat is not int. 10-07 12:42:07.863 W/XWalkInternalResources(11867): org.xwalk.core.R$styleable.ButtonCompat is not int. 10-07 12:42:07.873 W/XWalkInternalResources(11867): org.xwalk.core.R$styleable.ButtonCompat is not int. 10-07 12:42:08.063 I/cr_LibraryLoader(11867): Expected native library version number "", actual native library version number "" 10-07 12:42:08.063 I/chromium(11867): [INFO:library_loader_hooks.cc(144)] Chromium logging enabled: level = 0, default verbosity = 0 10-07 12:42:08.063 I/cr_BrowserStartup(11867): Initializing chromium process, singleProcess=true 10-07 12:42:08.063 I/cr_base (11867): Extracting resource /data/data/***/app_xwalkcore/paks/xwalk.pak 10-07 12:42:08.103 I/cr_base (11867): Extracting resource /data/data/***/app_xwalkcore/icudtl.dat 10-07 12:42:08.133 I/GAV2 (11750): Thread[GAThread,5,main]: No campaign data found. 10-07 12:42:08.213 W/dalvikvm(11867): VFY: unable to resolve instance field 306 10-07 12:42:08.213 E/ApkAssets(11867): Error while loading asset assets/icudtl.dat: java.io.FileNotFoundException: assets/icudtl.dat 10-07 12:42:08.253 D/XWalkLib(11867): Post init xwalk core in ***.MainActivity 10-07 12:42:08.253 D/XWalkLib(11867): Init reserved class: class org.xwalk.core.XWalkPreferences 10-07 12:42:08.253 D/XWalkLib(11867): Call reserved method: public static void org.xwalk.core.internal.XWalkPreferencesBridge.setValue(java.lang.String,boolean) 10-07 12:42:08.253 D/XWalkLib(11867): Init reserved class: class org.xwalk.core.XWalkPreferences 10-07 12:42:08.253 D/XWalkLib(11867): Call reserved method: public static void org.xwalk.core.internal.XWalkPreferencesBridge.setValue(java.lang.String,boolean) 10-07 12:42:08.253 D/XWalkLib(11867): Init reserved class: class org.xwalk.core.XWalkPreferences 10-07 12:42:08.253 D/XWalkLib(11867): Call reserved method: public static void org.xwalk.core.internal.XWalkPreferencesBridge.setValue(java.lang.String,boolean) 10-07 12:42:08.263 D/XWalkLib(11867): Init reserved class: class org.xwalk.core.XWalkPreferences 10-07 12:42:08.263 D/XWalkLib(11867): Call reserved method: public static void org.xwalk.core.internal.XWalkPreferencesBridge.setValue(java.lang.String,boolean) 10-07 12:42:08.263 D/XWalkLib(11867): Init reserved object: class org.crosswalk.engine.XWalkCordovaView 10-07 12:42:08.263 W/cr_media(11867): Requires BLUETOOTH permission 10-07 12:42:08.273 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;) 10-07 12:42:08.273 W/dalvikvm(11867): VFY: unable to resolve interface method 12458: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z 10-07 12:42:08.273 W/dalvikvm(11867): VFY: unable to resolve interface method 12462: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode; 10-07 12:42:08.273 W/dalvikvm(11867): VFY: unable to resolve virtual method 310: Landroid/app/Activity;.requestPermissions ([Ljava/lang/String;I)V 10-07 12:42:08.273 W/dalvikvm(11867): VFY: unable to resolve virtual method 318: Landroid/app/Activity;.shouldShowRequestPermissionRationale (Ljava/lang/String;)Z 10-07 12:42:08.273 W/dalvikvm(11867): VFY: unable to resolve virtual method 807: Landroid/content/pm/PackageManager;.isPermissionRevokedByPolicy (Ljava/lang/String;Ljava/lang/String;)Z 10-07 12:42:08.283 E/chromium(11867): [ERROR:xwalk_platform_notification_service.cc(142)] Not implemented reached in virtual bool xwalk::XWalkPlatformNotificationService::GetDisplayedPersistentNotifications(content::BrowserContext*, std::__1::set&lt;std::__1::basic_string&lt;char, std::__1::char_traits&lt;char&gt;, std::__1::allocator&lt;char&gt; &gt; &gt;*) 10-07 12:42:08.283 E/chromium(11867): [ERROR:xwalk_browser_context.cc(80)] Failed to read preference, error num: 0 10-07 12:42:08.333 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/view/ViewStructure;) 10-07 12:42:08.333 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/view/ViewStructure;) 10-07 12:42:08.333 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/view/ViewStructure;) 10-07 12:42:08.333 W/dalvikvm(11867): VFY: unable to resolve virtual method 12425: Landroid/view/ViewStructure;.setClassName (Ljava/lang/String;)V 10-07 12:42:08.343 W/dalvikvm(11867): Unable to resolve superclass of Lorg/chromium/content/browser/FloatingWebActionModeCallback; (1751) 10-07 12:42:08.343 W/dalvikvm(11867): Link of class 'Lorg/chromium/content/browser/FloatingWebActionModeCallback;' failed 10-07 12:42:08.343 E/dalvikvm(11867): Could not find class 'org.chromium.content.browser.FloatingWebActionModeCallback', referenced from method org.chromium.content.browser.ContentViewCore.startFloatingActionMode 10-07 12:42:08.343 W/dalvikvm(11867): VFY: unable to resolve new-instance 2751 (Lorg/chromium/content/browser/FloatingWebActionModeCallback;) in Lorg/chromium/content/browser/ContentViewCore; 10-07 12:42:08.353 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/view/ViewStructure;) 10-07 12:42:08.353 W/dalvikvm(11867): VFY: unable to resolve virtual method 12424: Landroid/view/ViewStructure;.setChildCount (I)V 10-07 12:42:08.353 W/dalvikvm(11867): VFY: unable to resolve virtual method 12424: Landroid/view/ViewStructure;.setChildCount (I)V 10-07 12:42:08.353 W/dalvikvm(11867): Unable to resolve superclass of Lorg/chromium/content/browser/FloatingWebActionModeCallback; (1751) 10-07 12:42:08.353 W/dalvikvm(11867): Link of class 'Lorg/chromium/content/browser/FloatingWebActionModeCallback;' failed 10-07 12:42:08.363 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/view/inputmethod/CursorAnchorInfo;) 10-07 12:42:08.363 W/dalvikvm(11867): VFY: unable to resolve virtual method 12805: Landroid/view/inputmethod/InputMethodManager;.updateCursorAnchorInfo (Landroid/view/View;Landroid/view/inputmethod/CursorAnchorInfo;)V 10-07 12:42:08.363 D/cr_Ime (11867): [InputMethodManagerWrapper.java:27] Constructor 10-07 12:42:08.383 D/PMS ( 757): releaseHCC(42a7bc28): CPU_MIN_NUM PrismLaunchActivity_4 0x400 10-07 12:42:08.383 W/dalvikvm(11867): VFY: unable to resolve direct method 1414: Landroid/media/MediaCodecList;.&lt;init&gt; (I)V 10-07 12:42:08.383 D/PMS ( 757): releaseHCC(42a146c0): CPU_MIN_FREQ PrismLaunchActivity_4 0x100 10-07 12:42:08.413 W/dalvikvm(11867): VFY: unable to resolve virtual method 12744: Landroid/view/accessibility/CaptioningManager$CaptionStyle;.hasBackgroundColor ()Z 10-07 12:42:08.423 D/XWalkLib(11867): Init reserved object: class org.crosswalk.engine.XWalkCordovaResourceClient 10-07 12:42:08.433 D/XWalkLib(11867): Call reserved method: public void org.xwalk.core.internal.XWalkViewBridge.setResourceClientSuper(org.xwalk.core.internal.XWalkResourceClientBridge) 10-07 12:42:08.433 D/XWalkLib(11867): Init reserved object: class org.crosswalk.engine.XWalkCordovaUiClient 10-07 12:42:08.433 D/XWalkLib(11867): Call reserved method: public void org.xwalk.core.internal.XWalkViewBridge.setUIClientSuper(org.xwalk.core.internal.XWalkUIClientBridge) 10-07 12:42:08.433 D/XWalkLib(11867): Call reserved method: public void org.xwalk.core.internal.XWalkViewBridge.setXWalkViewInternalVisibilitySuper(int) 10-07 12:42:08.433 D/XWalkLib(11867): Call reserved method: public void org.xwalk.core.internal.XWalkViewBridge.setSurfaceViewVisibilitySuper(int) 10-07 12:42:08.433 D/XWalkLib(11867): ActivateTask finished, 1 10-07 12:42:08.443 I/XWalkWebViewEngine(11867): Iterate assets/xwalk-extensions folder 10-07 12:42:08.624 W/chromium(11867): [WARNING:xwalk_external_extension.cc(58)] Error loading extension '/data/app-lib/***-1/libxwalkdummy.so': couldn't get XW_Initialize function. 10-07 12:42:08.624 W/chromium(11867): [WARNING:xwalk_extension_server.cc(412)] Failed to initialize extension: /data/app-lib/***-1/libxwalkdummy.so 10-07 12:42:08.624 W/chromium(11867): [WARNING:xwalk_external_extension.cc(58)] Error loading extension '/data/app-lib/***-1/libxwalkcore.so': couldn't get XW_Initialize function. 10-07 12:42:08.624 W/chromium(11867): [WARNING:xwalk_extension_server.cc(412)] Failed to initialize extension: /data/app-lib/***-1/libxwalkcore.so 10-07 12:42:08.634 I/Choreographer(11867): Skipped 47 frames! The application may be doing too much work on its main thread. 10-07 12:42:08.644 W/dalvikvm(11867): Unable to resolve superclass of Lorg/chromium/net/NetworkChangeNotifierAutoDetect$MyNetworkCallback; (352) 10-07 12:42:08.644 W/dalvikvm(11867): Link of class 'Lorg/chromium/net/NetworkChangeNotifierAutoDetect$MyNetworkCallback;' failed 10-07 12:42:08.644 E/dalvikvm(11867): Could not find class 'org.chromium.net.NetworkChangeNotifierAutoDetect$MyNetworkCallback', referenced from method org.chromium.net.NetworkChangeNotifierAutoDetect.&lt;init&gt; 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to resolve new-instance 3514 (Lorg/chromium/net/NetworkChangeNotifierAutoDetect$MyNetworkCallback;) in Lorg/chromium/net/NetworkChangeNotifierAutoDetect; 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to resolve virtual method 1704: Landroid/net/Network;.toString ()Ljava/lang/String; 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to find class referenced in signature ([Landroid/net/Network;) 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.644 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/NetworkRequest;) 10-07 12:42:08.654 W/dalvikvm(11867): VFY: unable to find class referenced in signature ([Landroid/net/Network;) 10-07 12:42:08.654 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.654 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.654 W/dalvikvm(11867): Unable to resolve superclass of Lorg/chromium/net/NetworkChangeNotifierAutoDetect$MyNetworkCallback; (352) 10-07 12:42:08.654 W/dalvikvm(11867): Link of class 'Lorg/chromium/net/NetworkChangeNotifierAutoDetect$MyNetworkCallback;' failed 10-07 12:42:08.654 I/chromium(11867): [INFO:xwalk_extension_renderer_controller.cc(43)] EXTENSION PROCESS DISABLED. 10-07 12:42:08.654 W/dalvikvm(11867): VFY: unable to resolve virtual method 1697: Landroid/net/ConnectivityManager;.getAllNetworks ()[Landroid/net/Network; 10-07 12:42:08.654 W/dalvikvm(11867): VFY: unable to find class referenced in signature ([Landroid/net/Network;) 10-07 12:42:08.654 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.654 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.654 W/dalvikvm(11867): VFY: unable to resolve virtual method 1700: Landroid/net/ConnectivityManager;.getNetworkInfo (Landroid/net/Network;)Landroid/net/NetworkInfo; 10-07 12:42:08.654 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.654 W/dalvikvm(11867): VFY: unable to resolve virtual method 1700: Landroid/net/ConnectivityManager;.getNetworkInfo (Landroid/net/Network;)Landroid/net/NetworkInfo; 10-07 12:42:08.654 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/Network;) 10-07 12:42:08.664 W/dalvikvm(11867): VFY: unable to resolve virtual method 1698: Landroid/net/ConnectivityManager;.getNetworkCapabilities (Landroid/net/Network;)Landroid/net/NetworkCapabilities; 10-07 12:42:08.664 W/dalvikvm(11867): VFY: unable to find class referenced in signature (Landroid/net/NetworkRequest;) 10-07 12:42:08.664 W/dalvikvm(11867): VFY: unable to resolve virtual method 1702: Landroid/net/ConnectivityManager;.registerNetworkCallback (Landroid/net/NetworkRequest;Landroid/net/ConnectivityManager$NetworkCallback;)V 10-07 12:42:08.664 W/dalvikvm(11867): VFY: unable to resolve virtual method 1703: Landroid/net/ConnectivityManager;.unregisterNetworkCallback (Landroid/net/ConnectivityManager$NetworkCallback;)V 10-07 12:42:08.664 D/PMS ( 757): releaseWL(42858218): PARTIAL_WAKE_LOCK ActivityManager-Launch 0x1 10-07 12:42:08.694 E/libEGL (11867): validate_display:259 error 3008 (EGL_BAD_DISPLAY) 10-07 12:42:08.714 W/cr_BindingManager(11867): Cannot call determinedVisibility() - never saw a connection for the pid: 11867 10-07 12:42:08.864 W/CpuWake ( 757): &gt;&gt;nativeReleaseCpuPerfWakeLock() 10-07 12:42:08.864 W/CpuWake ( 757): &lt;&lt;nativeReleaseCpuPerfWakeLock() 10-07 12:42:08.864 W/CpuWake ( 757): &gt;&gt;release mCpuPerf_cpu_count wakelock 10-07 12:42:08.864 W/CpuWake ( 757): &lt;&lt;release mCpuPerf_cpu_count wakelock 10-07 12:42:08.864 W/CpuWake ( 757): &gt;&gt;release mCpuPerf_Freq wakelock 10-07 12:42:08.864 W/CpuWake ( 757): &lt;&lt;release mCpuPerf_Freq wakelock 10-07 12:42:08.864 D/PMS ( 757): releaseHCC(42a9afd0): CPU_MIN_NUM ActivityManager-MultiCore-Num 0x400 10-07 12:42:08.864 D/PMS ( 757): releaseHCC(42a4e7e0): CPU_MIN_FREQ ActivityManager-MultiCore-Freq 0x100 10-07 12:42:08.984 D/JsMessageQueue(11867): Set native-&gt;JS mode to OnlineEventsBridgeMode 10-07 12:42:09.424 V/StatusBar(11867): Executing action: _ready 10-07 12:42:09.424 W/CordovaPlugin(11867): Attempted to send a second callback for ID: StatusBar32585383 10-07 12:42:09.424 W/CordovaPlugin(11867): Result was: "Invalid action" 10-07 12:42:09.535 E/chromium(11867): [ERROR:layer_tree_host_impl.cc(2263)] Forcing zero-copy tile initialization as worker context is missing 10-07 12:42:10.315 I/chromium(11867): [INFO:SkFontMgr_android_parser.cpp(595)] [SkFontMgr Android Parser] '/system/etc/fonts.xml' could not be opened 10-07 12:42:10.315 I/chromium(11867): 10-07 12:42:10.315 I/chromium(11867): [INFO:SkFontMgr_android_parser.cpp(595)] [SkFontMgr Android Parser] '/vendor/etc/fallback_fonts.xml' could not be opened 10-07 12:42:10.315 I/chromium(11867): 10-07 12:42:10.676 D/PhoneStatusBar( 911): Status bar WINDOW_STATE_HIDING 10-07 12:42:10.766 I/chromium(11867): [INFO:CONSOLE(900)] "TypeError: Cannot read property 'CitiesCollection' of undefined", source: file:///android_asset/www/app/ressources/bower_components/requirejs/require.js (900) 10-07 12:42:11.076 D/PhoneStatusBar( 911): Status bar WINDOW_STATE_HIDDEN 10-07 12:42:12.688 D/PMS ( 757): acquireWL(42479e30): PARTIAL_WAKE_LOCK NlpWakeLock 0x1 24221 10020 10-07 12:42:12.698 D/PMS ( 757): acquireWL(421aa8b0): PARTIAL_WAKE_LOCK NlpWakeLock 0x1 24221 10020 10-07 12:42:12.698 D/WifiService( 757): acquireWifiLockLocked: WifiLock{NlpWifiLock type=2 binder=android.os.BinderProxy@42aa4de0} 10-07 12:42:12.708 D/PMS ( 757): acquireWL(42a29c70): PARTIAL_WAKE_LOCK AlarmManager 0x1 757 1000 10-07 12:42:12.718 V/AlarmManager( 757): sending alarm PendingIntent{42ba00f8: PendingIntentRecord{4286af78 com.google.android.gms broadcastIntent}}, i=com.google.android.gms.nlp.ALARM_WAKEUP_LOCATOR, t=2, cnt=1, w=2417663301, Int=0 10-07 12:42:12.718 D/PMS ( 757): releaseWL(42a29c70): PARTIAL_WAKE_LOCK AlarmManager 0x1 10-07 12:42:12.718 D/PMS ( 757): releaseWL(42479e30): PARTIAL_WAKE_LOCK NlpWakeLock 0x1 10-07 12:42:12.858 D/WifiService( 757): releaseWifiLockLocked: WifiLock{NlpWifiLock type=2 binder=android.os.BinderProxy@42aa4de0} 10-07 12:42:12.868 D/PMS ( 757): releaseWL(421aa8b0): PARTIAL_WAKE_LOCK NlpWakeLock 0x1 10-07 12:42:17.403 D/PMS ( 757): acquireWL(435b97f0): PARTIAL_WAKE_LOCK AlarmManager 0x1 757 1000 10-07 12:42:17.403 V/AlarmManager( 757): sending alarm PendingIntent{42a337e0: PendingIntentRecord{4273f320 com.android.vending startService}}, i=null, t=0, cnt=1, w=1475836937154, Int=0 10-07 12:42:17.403 D/PMS ( 757): releaseWL(435b97f0): PARTIAL_WAKE_LOCK AlarmManager 0x1 10-07 12:42:17.673 D/Finsky ( 2449): [1] 5.onFinished: Installation state replication succeeded. </code></pre> <p>Cordova plugins:</p> <pre><code> "cordova plugin add cordova-plugin-file@3.0.0", "cordova plugin add cordova-plugin-media@1.0.1", "cordova plugin add cordova-plugin-splashscreen@2.1.0", "cordova plugin add cordova-plugin-statusbar@1.0.1", "cordova plugin add cordova-plugin-vibration@1.2.0", "cordova plugin add cordova-plugin-geolocation@1.0.1", "cordova plugin add cordova-plugin-file-transfer@1.3.0", "cordova plugin add cordova-plugin-device@1.0.1", "cordova plugin add cordova-plugin-inappbrowser@0.6.0", "cordova plugin add cordova-plugin-app-preferences@0.7.7", "cordova plugin add https://github.com/macdonst/VideoPlayer.git", "cordova plugin add https://github.com/apache/cordova-plugin-network-information", "cordova plugin add https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin.git", "cordova plugin add cc.fovea.cordova.purchase@5.x --variable BILLING_KEY='&lt;%= BILLING_KEY %&gt;'", "cordova plugin add cordova-plugin-crosswalk-webview@1.8.x", </code></pre>
<p>Perhaps this will help others. In my case some initialization <strong>before the first view is rendered</strong> caused this error. Both single of the following points seems to bring on the problem unreproducible from time to time:</p> <ul> <li>unzipping some kB and copy some files to the app data directory</li> <li>parsing JSON into a backbone Collection via ajax</li> </ul>
Can't connect to container cluster: environment variable HOME or KUBECONFIG must be set when running gcloud get credentials <p>For some reason I can't connect to the cluster. Having followed the instructions per google container-engine after setting up the cluster, I get the following error: </p> <p>ERROR: (gcloud.container.clusters.get-credentials) environment variable HOME or KUBECONFIG must be set to store credentials for kubectl</p> <p>When running this command: gcloud container clusters get-credentials [my cluster name] --zone us-central1-b --project [my project name]</p> <p>Any ideas how I should be setting the variable HOME or KUBECONFIG. I couldn't find anything specific for container-engine.</p>
<p>gcloud attempts to write a kubeconfig file to <code>$HOME/.kube/config</code> (or <code>$KUBECONFIG</code> if it is set). The most straightforward approach is to set <code>HOME</code> to your home directory, but if you have a reason that you'd like to store your kubectl configuration elsewhere, you can do that with the <code>KUBECONFIG</code> variable.</p>
How to calculate the CRC of data to verify it with the CRC of a zip entry? <p>Before we get started: I am an absolute beginner with JAVA. I have always been a C++ coder. So please do tell me when I am doing stupid stuff here!</p> <p>I am querying a huge database and exporting that data directly into a zip-file. We are talking about 35GB of data here, so the results are streamed through a StringBuilder and when that StringBuilder has a specific size, its data is sent to the ZipOutputStream object for compression. I reset the StringBuilder and repeat until all data has been processed and zipped. This works fine. The zip files are always good, but the client wants me to put in extra checks.</p> <p>So I want to be able to calculate the checksum value myself from that in memory data so that at the end, I can reopen the zip-file to check if it is not corrupt and the checksum is what I expect it to be.</p> <p>So everytime I send data to the ZipOuputStream, I also update my internal checksum. I use the CRC32 class for this, which is also in the same zip library, so I would expect that zip entries use that same calculation.</p> <p>But alas... the calculated checksum and the zip entry's checksum are not the same while the zip file definitely is ok.</p> <p>Can anyone help me get this right?</p> <p>Here is some code. This is how I create a zip file, a CRC class and a StringBuilder.</p> <pre><code>File zipFile = new File(outputZipFileName); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry zipEntry = new ZipEntry(tableName + ".csv"); zipOut.putNextEntry(zipEntry); CRC32 zipEntryCrc = new CRC32(); StringBuilder sbZipData = new StringBuilder(); sbZipData.ensureCapacity(memoryBufferSize); </code></pre> <p>This is what I do every time when the StringBuilder reaches a limit or at the end of data:</p> <pre><code>byte[] sZipData = sbZipData.toString().getBytes(); zipEntryCrc.update(sZipData); zipOut.write(sZipData, 0, sZipData.length); zipOut.flush(); sbZipData.setLength(0); </code></pre> <p>Here's how I reopen my generated zip file and test the checksum:</p> <pre><code>ZipFile testZipFile = new ZipFile(outputZipFileName); ZipEntry testZipEntry = testZipFile.getEntry(tableName + ".csv"); System.out.format("Calculated CRC: %8X, Zip entry CRC: %8X\n", zipEntryCrc.getValue(), testZipEntry.getCrc()); testZipFile.close(); </code></pre> <p>As you can guess, the output is not the same:</p> <pre><code>Calculated CRC: 2E9F53AC, Zip entry CRC: 5270784D </code></pre> <p>Btw. I know I have to put some try-catches around to prevent the code from stopping when the zip entry is not found. This is just my first test.</p> <p>Anyone?</p>
<p>I reproduced your example and it does work, the checksum is identical, but, I needed to add at least the <code>zipOut.close()</code> call:</p> <pre><code> zipOut.write(sZipData, 0, sZipData.length); //zipOut.closeEntry(); // &lt;===== optional zipOut.flush(); zipOut.close(); // &lt;===== sbZipData.setLength(0); </code></pre> <p>Here the complete test class:</p> <pre><code>import java.io.*; import java.nio.charset.Charset; import java.util.zip.*; public class CRC32Test { public static void main(String[] args) throws IOException { // create test daata String input = "Hell is empty and all the devils are here. William Shakespeare"; for (int i = 0; i &lt; 15; i++) { input = input + "|" + input; } System.out.println("input length: " + input.length()); // get bytes from string byte bytes[] = input.getBytes(); // compute checksum Checksum checksum = new CRC32(); checksum.update(bytes, 0, bytes.length); // get current checksum value long checksumValue = checksum.getValue(); System.out.format("CRC32 checksum for input string: %8X\n", checksumValue); System.out.println("------------------"); String outputZipFileName = "t.zip"; int memoryBufferSize = 1024; String tableName = "string"; Charset charset = Charset.forName("UTF-8"); File zipFile = new File(outputZipFileName); if (zipFile.exists()) zipFile.delete(); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile), charset); ZipEntry zipEntry = new ZipEntry(tableName + ".csv"); zipOut.putNextEntry(zipEntry); CRC32 zipEntryCrc = new CRC32(); StringBuilder sbZipData = new StringBuilder(); sbZipData.ensureCapacity(memoryBufferSize); sbZipData.append(input); // &lt;===== byte[] sZipData = sbZipData.toString().getBytes("UTF-8"); zipEntryCrc.update(sZipData); zipOut.write(sZipData, 0, sZipData.length); //zipOut.closeEntry(); // &lt;===== optional zipOut.flush(); zipOut.close(); // &lt;===== sbZipData.setLength(0); ZipFile testZipFile = new ZipFile(outputZipFileName, charset); ZipEntry testZipEntry = testZipFile.getEntry(tableName + ".csv"); System.out.format("Calculated CRC: %8X, Zip entry CRC: %8X\n", zipEntryCrc.getValue(), testZipEntry.getCrc()); testZipFile.close(); } } </code></pre>
Push in array not reactive in HTML <p>When I remove a comment on my HTML var {{selecionados}} selected from, and I click on the list of names is all fine, but when HTML retreat or comment on again no longer works. </p> <pre><code>&lt;script async src="//jsfiddle.net/raphaelscunha/9cwztvzv/1/embed/"&gt;&lt;/script&gt; </code></pre>
<p>Vue.js will only update your view when a property within the <code>data</code> object is <em>changed</em>, not when a new property is added. (See <a href="http://vuejs.org/guide/reactivity.html#Change-Detection-Caveats" rel="nofollow">Change Detection Caveats</a> in the Vue.js guide)</p> <p>If you want it to react when <code>ativo</code> is set to <code>true</code>, make sure the property exists beforehand. Try something like this when you're initializing your <code>Vue</code> object:</p> <pre><code>atores: [ { name: 'Chuck Norris', ativo: false}, { name: 'Bruce Lee', ativo: false }, { name: 'Jackie Chan', ativo: false }, { name: 'Jet Li', ativo: false} ] </code></pre> <p><a href="http://jsfiddle.net/dtbgc8b7/1/" rel="nofollow">JSFiddle</a></p>
Does killing the parent actor kill the children too? Seeing some different behaviour <p>I was underassumption that, if you kill the parent actor, the children will be killed too, but when I tried something like this given below, I am getting a different behaviour. Could someone please explain?</p> <pre><code>1. Here the actor GrandFather creates Son and Son creates GrandSon. 2. Grandson sends a message to GandFather, so Grandfather gets the actoRef of the Grandson. 3. Then on receiving a specific message ("crash") from GrandFather, Son throws an exception. 4. Now GrandFather tries to send messages to both Son and GrandSon. Messages to Son goes to Deadletter Queue, whild messsages to GrandSon is received and printed. object GrandFather{ def props()=Props(new GrandFather) } class GrandFather extends Actor with ActorLogging { var child:ActorRef=Actor.noSender override def receive: Receive = { case x:String if x.equals("Test Grandpa") =&gt; println("I am grand father -&gt;" + x) child = context.actorOf(Son.props) child ! "Test Son" case y:String =&gt; val grandChild = sender() println("I am the grandfather, Got Message from grand child, gonna kill my son") child ! "crash" child ! "there" grandChild ! "Are you Alive?" child ! "there" grandChild ! "Are you Alive?" child ! "there" grandChild ! "Are you Alive?" child ! "there" grandChild ! "Are you Alive?" child ! "there" } } object Son{ def props:Props = Props(new Son) } class Son extends Actor with ActorLogging { var actr:ActorRef = Actor.noSender def receive:Receive={ case y:String if y.equals("crash") =&gt; throw new Exception("killed by self") case z:String if z.equals("there") =&gt; println("I am the son -&gt; " + "still here") case x:String =&gt; { val k = sender() println("I am the son -&gt; " + x) actr = context.actorOf(GrandSon.props()) actr ! ("Test GrandChild ", k) } } } object GrandSon{ def props() = Props(new GrandSon) } class GrandSon extends Actor with ActorLogging { def receive:Receive={ case (x:String, y:ActorRef) =&gt; { println("I am the grand child -&gt; " + x) y ! "go ahead and kill your son, i.e. my father" } case y:String if y.equals("Are you Alive?") =&gt; println("I am Grand Child, grandpa I am still alive") } } </code></pre> <p>The output of this code:</p> <pre><code> Testing started at 17:57 ... I am grand father -&gt;Test Grandpa I am the son -&gt; Test Son I am the grand child -&gt; Test GrandChild I am the grandfather, Got Message from grand child, gonna kill my son I am Grand Child, grandpa I am still alive I am Grand Child, grandpa I am still alive I am Grand Child, grandpa I am still alive I am Grand Child, grandpa I am still alive [WARN] [10/07/2016 17:57:10.818] [test-akka.actor.default-dispatcher-3] [akka://test/user/$a/$a] received dead letter from Actor[akka://test/user/$a#-275386619]: there [WARN] [10/07/2016 17:57:10.819] [test-akka.actor.default-dispatcher-3] [akka://test/user/$a/$a] received dead letter from Actor[akka://test/user/$a#-275386619]: there [WARN] [10/07/2016 17:57:10.820] [test-akka.actor.default-dispatcher-3] [akka://test/user/$a/$a] received dead letter from Actor[akka://test/user/$a#-275386619]: there [WARN] [10/07/2016 17:57:10.821] [test-akka.actor.default-dispatcher-3] [akka://test/user/$a/$a] received dead letter from Actor[akka://test/user/$a#-275386619]: there [WARN] [10/07/2016 17:57:10.821] [test-akka.actor.default-dispatcher-3] [akka://test/user/$a/$a] received dead letter from Actor[akka://test/user/$a#-275386619]: there </code></pre>
<p>per documentation default strategy</p> <pre><code>ActorInitializationException will stop the failing child actor ActorKilledException will stop the failing child actor Exception will restart the failing child actor Other types of Throwable will be escalated to parent actor </code></pre> <p>you are actually not killing the actor but restarting it. </p> <p>if you want to prove this, override more methods for son actor</p> <p>like in documentation</p> <pre><code>def preStart(): Unit = () def postStop(): Unit = () def preRestart(reason: Throwable, message: Option[Any]): Unit = { context.children foreach { child ⇒ context.unwatch(child) context.stop(child) } postStop() } def postRestart(reason: Throwable): Unit = { preStart() } </code></pre>
Declare, manipulate and access unaligned memory in C++ <p>I recently posted a question about <a href="http://stackoverflow.com/questions/39908946/unaligned-memory-access-is-it-defined-behavior-or-not">unaligned memory access</a>, but given the answer, I am a little lost. I often hear that "aligned memory access is far more efficient than unaligned access", but I am actually not sure what is unaligned memory. Consequently:</p> <ul> <li>What is unaligned memory?</li> <li>How you declare something unaligned in C++? (small example program)</li> <li>How do you access and manipulate something unaligned in C++? (small example program)</li> <li>Is there is a way to manipulate unaligned memory in with a defined behavior approach or all of that is platform dependent/undefined behavior in C++?</li> </ul>
<p>Whether something is unaligned or not depends on the data type and its size As the answer from Gregg explains.</p> <p>A well-written program usually does not have unaligned memory access, except when the compiler introduces it. (Yes, that happens during vectorization but let's skip that). </p> <p>But you can write program in C++ to force unaligned memory access. The code below does just that.</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int a[3] {1, 2, 3}; cout &lt;&lt; *((long long *)(&amp;a[0])) &lt;&lt; endl; cout &lt;&lt; *((long long *)(&amp;a[1])) &lt;&lt; endl; cout &lt;&lt; (long long) (&amp;a[0]) &lt;&lt; endl; cout &lt;&lt; (long long) (&amp;a[1]) &lt;&lt; endl; return 0; } </code></pre> <p>The output of the code is this</p> <pre><code>8589934593 12884901890 70367819479584 70367819479588 </code></pre> <p><strong>What this program does?</strong> I declare an integer array of size 3. This array will be 4 byte aligned because int is a 4 byte data type (at least on my platform). So the address of a[0] is divisible by 4. Now address of both of a[0] and a[1] is divisible by 4 but only address of one of them is divisible by 8.</p> <p>So if I cast the address of a[0] and a[1] to a pointer to long long (which is an 8 byte data type on my platform) and then deference these two pointers, one of them will be an unaligned memory access. This is not undefined behavior AFAIK, but it is going to be slower than aligned memory access. </p> <p>As you see this code contains C style casts which is not a good practice. But I think for enforcing some strange behavior that is fine.</p> <p>let me know if you have question about the output of the code. You should know about endianness and representation of integers to understand the first two lines. The third and fourth line are address of the first two elements of the integer array. That should be easier to understand.</p>
Nginx micro caching with JQuery callback <p>I have micro caching setup with my Nginx server to cache an API for 2 seconds. However, each time a request is made to the API, a different url is seen by Nginx because of the attached jQuery callback parameter.</p> <p><strong>Example:</strong></p> <p><code>api.example.com/get_heats.php?sheet=105&amp;callback=jQuery222018438785197213292_1475857341748&amp;_=1475857342048</code></p> <p>and </p> <p><code>api.example.com/get_heats.php?sheet=105&amp;callback=jQuery222018438785197213292_1475857341748&amp;_=1475857342049</code></p> <p>should return the same values for 2 seconds because they are both referencing sheet 105, but they don't because the callback and _ parameters are changing with each request. Is there a way for Nginx to ignore any of the other parameters?</p>
<p>Please try out the following code,</p> <pre><code>server { ... location ~ \.php$ { ... set $cache_key $request_uri; ... if ($args ~ "sheet") { set $cache_key $cache_key|$arg_sheet; } ... fastcgi_cache_key $cache_key; ... } ... } </code></pre> <p>References : <a href="https://www.techromance.com/2015/11/11/microcaching-nginx-web-server/" rel="nofollow">Learn to implement microcaching</a>, <a href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_cache_key" rel="nofollow">fastcgi_cache_key</a></p>
PHP :editing xml files via php form <p>This is my xml file and my php code. It modifies current information about student. however, what if I have several students. I can only edit the first one (John Doe) how can I edit my second student information then it also changes in my xml file. I have simplified the code here compare to my previous post as my previous code are not working. thanks </p> <pre><code>&lt;student&gt; &lt;firstname&gt;John&lt;/firstname&gt; &lt;lasttname&gt;Doe&lt;/lasttname&gt; &lt;student_id&gt;150334&lt;/student_id&gt; &lt;gender&gt;female&lt;/gender&gt; &lt;dob&gt;16-09-94&lt;/dob&gt; &lt;email&gt;Johndoe@gmail.com&lt;/email&gt; &lt;mobilenumber&gt;12345678&lt;/mobilenumber&gt; &lt;address&gt;xxx&lt;/address&gt; &lt;cohort&gt;cohort name&lt;/cohort&gt; &lt;programme&gt;Softwaree Engineering&lt;/programme&gt; &lt;mode&gt;FT&lt;/mode&gt; &lt;/student&gt; &lt;student&gt; &lt;firstname&gt;firnstmae&lt;/firstname&gt; &lt;lasttname&gt;hahah&lt;/lasttname&gt; &lt;student_id&gt;150500&lt;/student_id&gt; &lt;gender&gt;female&lt;/gender&gt; &lt;dob&gt;24-03-96&lt;/dob&gt; &lt;email&gt;lol@hotmail.com&lt;/email&gt; &lt;mobilenumber&gt;57056242&lt;/mobilenumber&gt; &lt;address&gt;addressname&lt;/address&gt; &lt;cohort&gt;cohort name&lt;/cohort&gt; &lt;programme&gt;web developement&lt;/programme&gt; &lt;mode&gt;FT&lt;/mode&gt; &lt;/student&gt; &lt;/students&gt; &lt;?php if(isset($_POST['submit'])) { $data=simplexml_load_file('studentdb.xml'); $data-&gt;item-&gt;firstname=$_POST['firstname']; $data-&gt;item-&gt;lasttname=$_POST['lastname']; $data-&gt;item-&gt;gender=$_POST['gender']; $data-&gt;item-&gt;dob=$_POST['dob']; $data-&gt;item-&gt;email=$_POST['email']; $data-&gt;item-&gt;mobilenumber=$_POST['mobilenumber']; $data-&gt;item-&gt;address=$_POST['address']; $data-&gt;item-&gt;cohort=$_POST['cohort']; $data-&gt;item-&gt;programme=$_POST['programme']; $data-&gt;item-&gt;mode=$_POST['mode']; $handle=fopen("studentdb.xml","wb"); fwrite($handle,$data-&gt;asXML()); fclose($handle); } $data=simplexml_load_file('studentdb.xml'); $fName=$data-&gt;item-&gt;firstname; $lName=$data-&gt;item-&gt;lasttname; $gender=$data-&gt;item-&gt;gender; $dob=$data-&gt;item-&gt;dob; $email=$data-&gt;item-&gt;email; $mobileNo=$data-&gt;item-&gt;mobilenumber; $address=$data-&gt;item-&gt;address; $cohort=$data-&gt;item-&gt;cohort; $programme=$data-&gt;item-&gt;programme; $mode=$data-&gt;item-&gt;mode; ?&gt; &lt;?php echo $fName . " "; echo $lName . " "; echo $gender . " "; echo $dob . " "; echo $email . " "; echo $mobileNo . " "; echo $address . " "; echo $cohort . " "; echo $programme . " "; echo $mode . " "; ?&gt; &lt;form method="post"&gt; Firstname&lt;input type="text" name="firstname" value="&lt;?php echo $fName;?&gt;" placeholder="firstname" pattern="[A-Z][a-z]+" title="Must start with capital letters!"required/&gt; &lt;/br&gt;&lt;/br&gt; Lastname&lt;input type="text" name="lastname" value="&lt;?php echo $lName;?&gt;"placeholder="lastname" pattern="[A-Z][a-z]+" title="Must start with capital letters!" required/&gt;&lt;/br&gt;&lt;/br&gt; gender &lt;input type="radio" name="gender" value="M" value="&lt;?php echo $gender;?&gt;"&gt; Male &lt;input type="radio" name="gender" value="F" value="&lt;?php echo $gender;?&gt;"&gt; Female&lt;br&gt;&lt;br&gt; dob&lt;input type="date" name="dob" placeholder="dob" value="&lt;?php echo $dob;?&gt;" /&gt; &lt;/br&gt;&lt;/br&gt; email&lt;input type="text" name="email" placeholder="email" value="&lt;?php echo $email;?&gt;"/&gt;&lt;/br&gt;&lt;/br&gt; mobile No:&lt;input type="text" name="mobilenumber" value="&lt;?php echo $mobileNo;?&gt;" placeholder="mobileno" pattern="5[0-9][0-9][0-9][0-9][0-9][0-9][0-9]" title="Must start with 5 followed by 7 digits" required/&gt;&lt;/br&gt;&lt;/br&gt; address&lt;input type="text" name="address" placeholder="address" value="&lt;?php echo $address;?&gt;" title="Must start with capital letters!"required/&gt;&lt;/br&gt;&lt;/br&gt; cohort&lt;input type="text" name="cohort" placeholder="cohort" value="&lt;?php echo $cohort;?&gt;" required /&gt;&lt;/br&gt;&lt;/br&gt; programme&lt;input type="text" name="programme" placeholder="programme" value="&lt;?php echo $programme;?&gt;" required //&gt;&lt;/br&gt;&lt;/br&gt; mode&lt;input type="radio" name="mode" value="FT" value="&lt;?php echo $mode;?&gt;"&gt; Full-Time &lt;input type="radio" name="mode" value="PT"&gt; Part-Time&lt;br&gt; &lt;br&gt; &lt;input name="submit" type="submit" /&gt; &lt;/form&gt; </code></pre>
<p>Try to use <code>$data-&gt;student[0]</code> for first student and <code>$data-&gt;student[1]</code> for second (<code>$data-&gt;student[n]</code> for nth student) instead of <code>$data-&gt;item</code>.</p>
How to add VoiceOver accessibility to an App's Icon Badge Number? <blockquote> <p><strong>Question:</strong></p> <p>How do I add a custom VoiceOver accessibility <code>Label</code> or <code>Hint</code> to an App Icon Badge Number?</p> </blockquote> <p><a href="http://i.stack.imgur.com/jHGRs.png"><img src="http://i.stack.imgur.com/jHGRs.png" alt="enter image description here"></a>           <a href="http://i.stack.imgur.com/m6uBw.png"><img src="http://i.stack.imgur.com/m6uBw.png" alt="enter image description here"></a>           <a href="http://i.stack.imgur.com/SQwpX.png"><img src="http://i.stack.imgur.com/SQwpX.png" alt="enter image description here"></a></p> <hr> <p><strong>For example</strong>, when the iOS Setting <code>Accessibility &gt; VoiceOver</code> is turned <code>On</code>, VoiceOver reads aloud items touched on screen. For the App Store and Mail icons, the following is read out aloud:</p> <blockquote> <p>App Store icon, VoiceOver says: <em>"App Store. <strong>2 updates available</strong>. Double tap to open."</em></p> <p>Mail icon, VoiceOver says: <em>"Mail. <strong>1 unread message</strong>. Double tap to open."</em></p> </blockquote> <p><strong><em>But</em></strong>, for the project I am working on, the VoiceOver read out is generic and not entirely helpful:</p> <blockquote> <p>My App icon, VoiceOver says: <em>"My App. <strong>123 new items</strong>. Double tap to open."</em></p> </blockquote> <p>The phrase <strong><em>"... new items"</em></strong> is too vague, not accurate, and I'm certain there must be a way to change this with a custom string to make it read better through setting an <code>accessibilityLabel</code>, <code>accessibilityHint</code> or something similar.</p> <p>But how exactly in Swift code?</p> <p>Many thanks.</p> <hr> <p><strong>Additional observation:</strong></p> <p>Using the Simulator Accessibility Inspector, it appears the VoiceOver values come from <code>Label</code> - "My App" and <code>Value</code> - "123 new items". So updated in the code I have tried setting the <code>accessibilityValue</code> to something custom - "123 custom description.". But still no luck, VoiceOver continues to read <em>"My App. 123 <strong>new items</strong>. Double tap to open."</em></p> <p><strong>Why isn't VoiceOver reading the custom badge value as expected?</strong></p> <p><a href="http://i.stack.imgur.com/9qX8g.png"><img src="http://i.stack.imgur.com/9qX8g.png" alt="enter image description here"></a></p> <hr> <p><strong>Code:</strong></p> <p>The below method adds a red circle App Icon Badge Number to My App's icon:</p> <pre><code>import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let badgeCount: Int = 123 let application = UIApplication.sharedApplication() if #available(iOS 8.0, *) { //// iOS 8, iOS 9, iOS 10 application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Badge], categories: nil)) } else { //// iOS 7 } application.applicationIconBadgeNumber = badgeCount application.accessibilityValue = "123 custom description." } } </code></pre>
<p>It appears this is an "Apple-only" feature as of now... <a href="http://lists.apple.com/archives/accessibility-dev/2015/Jan/msg00003.html" rel="nofollow">source</a></p> <p>Digging through API documentation, there doesn't seem to be any identifier that can set this for you, and I therefore think it's not publicly supported yet. It's likely been reported already, but reporting this as a request to <a href="http://%20https://bugreporter.apple.com/" rel="nofollow">Apple</a> can never hurt.</p> <p>Sorry this is probably not the answer you were hoping for! :/</p>
tox tests, use setup.py extra_require as tox deps source <p>I want to use setup.py as the authority on packages to install for testing, done with extra_requires like so:</p> <pre><code>setup( # ... extras_require={ 'test': ['pytest', ], }, ) </code></pre> <p>Tox only appears to be capable of <a href="https://testrun.org/tox/latest/example/basic.html#depending-on-requirements-txt" rel="nofollow">installing from a requirements.txt</a> file which just implies a step of snapshotting requirements before testing (which I'm ignorant how to do automatically) or by <a href="https://testrun.org/tox/latest/config.html#confval-deps=MULTI-LINE-LIST" rel="nofollow">duplicating the test dependencies</a> into the tox file, which is all I want to avoid. <a href="http://lists.idyll.org/pipermail/testing-in-python/2015-March/006285.html" rel="nofollow">One mailing list post</a> suggested that tox.ini should be the authority on test dependencies, but I don't wish to straightjacket tox into the project that completely.</p>
<p>I've come up with a nasty hack that seems to work</p> <pre><code># tox.ini ... [testenv] ... install_command = pip install {opts} {packages} {env:PWD}[test] </code></pre> <p>The defualt <code>install_command</code> is <code>pip install {opts} {packages}</code>, unfortunately <code>{packages}</code> is a required argument. Additionally tox doesn't expose the project directory as a magic variable; but it does expose the <code>env</code> of the shell that ran it.</p> <p>This works by assuming you ran <code>tox</code> from the same directory as your <code>setup.py</code> and <code>tox.ini</code>, and assuming your shell exposes <code>PWD</code> as your current path. Tox appears to use something like <code>shlex</code> to split your <code>install_command</code> into a shell-safe set of arguments, so we cant do things like <code>{packages}[test]</code>. Ultimately this hack will name your package twice, but I think that's okay since <code>{env:PWD}[test]</code> names your package plus the <code>extra_require</code> block you want.</p> <p>I don't know a better way, the <a href="https://github.com/pypa/sampleproject/" rel="nofollow">PYPA SampleProject</a> seems content with specifying your test dependencies in both setup.py and tox.ini.</p>
check if date argument is in yyyy-mm-dd format and correct date range <p>Is there a way to check if a date argument is in the correct date range eg </p> <blockquote> <p>2016-10-32 or 2016-09-31 should display as invalid</p> </blockquote> <p>.</p> <p>i can able to find correct argument yyyy-mm-dd using below code</p> <pre><code>if [[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] then echo "Date $1 is in valid format (YYYY-MM-DD)" else echo "Date $1 is in an invalid format (not YYYY-MM-DD)" fi </code></pre> <p>How to check date is in correct date range</p>
<p>delegate the validity check to <code>date</code> change the messages as you like</p> <pre><code>$ d='2016-10-32'; if date -d "$d" &amp;&gt;/dev/null; then echo "$d is OK"; else echo "$d is incorrect"; fi 2016-10-32 is incorrect $ d='2016-10-31'; if date -d "$d" &amp;&gt;/dev/null; then echo "$d is OK"; else echo "$d is incorrect"; fi 2016-10-31 is OK </code></pre>
How can I implement C's Structs in Java? <p>I have a little code that let me register an student (ID, name, age, etc), right now I could do it but just accepting one user, would overwrite if I register a new one, which is what I need now, be able to have more than 1 student.</p> <p>So I was thinking that if I were using C I would use structs, something like this</p> <pre><code>struct Students { int ID[6]; char Name[35]; char Age[2]; } student; </code></pre> <p>After reading a bit, Java doesn't have this facility.</p> <p>How to do this in Java ? Is it possible ?</p> <p>Thanks</p>
<p>Java has no <code>struct</code>. </p> <p>You can use <code>class</code> as structs with members having public access specifier and no methods</p>
Javascript formatting of 10 or 11 digit phone numbers and recognizing a 1800 phone number <p>I am trying to get javascript to format phone numbers based on a users input of 10 or 11 digits. The 11 digits are for phone numbers that start with a 1 at the beginning like a 1-800 number. I need the final output to be either 000-000-0000 or 1-000-000-0000. The sample javascript code that I was given to start out with, works with the 10 digit phone number but I need the javascript to also recognize if there is a 1800 number and append accordingly.</p> <p>The following is my initial working javascript and below that is code I found online that addresses the 10 and 11 digital formatting however I don’t know how to mesh the two together.</p> <p>Thank you in advance for any help given.</p> <p>~~~~~~~~~~~~~~~~~ </p> <pre><code>&lt;script type="text/javascript"&gt; var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ]; InitialFormatTelephone(); function InitialFormatTelephone() { for (var i = 0; i &lt; phoneNumberVars.length; i++) { FormatTelephone(phoneNumberVars[i]); } } function StorefrontEvaluateFieldsHook(field) { for (var i = 0; i &lt; phoneNumberVars.length; i++) { if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]]) { FormatTelephone(phoneNumberVars[i]); } } } function FormatTelephone(varName) { var num = document.getElementById("FIELD_" + FieldIDs[varName]).value; var charArray = num.split(""); var digitCounter = 0; var formattedNum; if (charArray.length &gt; 0) formattedNum = “-“; else formattedNum = ""; var i; for (i = 0;i &lt; charArray.length; i++) { if (isDigit(charArray[i])) { formattedNum = formattedNum + charArray[i]; digitCounter++; if (digitCounter == 3) { formattedNum = formattedNum + “-“; } if (digitCounter == 6) { formattedNum = formattedNum + "-"; } } } if (digitCounter != 0 &amp;&amp; digitCounter != 10) { alert ("Enter a valid phone number!"); } // now that we have a formatted version of the user's phone number, replace the field with this new value document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum; // force an update of the preview PFSF_AjaxUpdateForm(); } function isDigit(aChar) { myCharCode = aChar.charCodeAt(0); if((myCharCode &gt; 47) &amp;&amp; (myCharCode &lt; 58)) { return true; } return false; } &lt;/script&gt; </code></pre>
<pre><code>&lt;script type="text/javascript"&gt; var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ]; InitialFormatTelephone(); function InitialFormatTelephone() { for (var i = 0; i &lt; phoneNumberVars.length; i++) { FormatTelephone(phoneNumberVars[i]); } } function StorefrontEvaluateFieldsHook(field) { for (var i = 0; i &lt; phoneNumberVars.length; i++) { if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]]) { FormatTelephone(phoneNumberVars[i]); } } } function FormatTelephone(varName) { var num = document.getElementById("FIELD_" + FieldIDs[varName]).value; var cleanednum = num.replace( /[^0-9]/g, ""); var charArray = cleanednum.split(""); var digitCounter = 0; var formattedNum = ""; var digitPos1 = 0; var digitPos3 = 3; var digitPos6 = 6; if (charArray.length ===11) { digitPos1++; digitPos3++; digitPos6++; } if (charArray.length &gt; 0) formattedNum = ""; else formattedNum = ""; var i; for (i = 0;i &lt; charArray.length; i++) { if (isDigit(charArray[i])) { formattedNum = formattedNum + charArray[i]; digitCounter++; if (digitCounter === digitPos1) { formattedNum = formattedNum + "-"; } if (digitCounter == digitPos3) { formattedNum = formattedNum + "-"; } if (digitCounter == digitPos6) { formattedNum = formattedNum + "-"; } } } if ((charArray.length ==10 || charArray.length == 11 || charArray.length == 0) === false) { alert ("Enter a valid phone number!"); } // now that we have a formatted version of the user's phone number, replace the field with this new value document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum; // force an update of the preview PFSF_AjaxUpdateForm(); } function isDigit(aChar) { myCharCode = aChar.charCodeAt(0); if((myCharCode &gt; 47) &amp;&amp; (myCharCode &lt; 58)) { return true; } return false; } &lt;/script&gt; </code></pre>
Setting for Cookies never expire in SailsJs <p>I'm developing one application that i need a infinit session for some login. But my session was expire. I'm using Redis for control sessions and i'm authenticate Users with Json Web Token. Apparently, my Cookies settings is wrong.</p>
<p>Open config/session.js</p> <p>Uncomment the following lines:</p> <pre><code>cookie: { maxAge: 24 * 60 * 60 * 1000 }, </code></pre> <p>Replace maxAge value with some that will point in distant future, like 10 years from now:</p> <pre><code>maxAge: 10 * 365 * 24 * 60 * 60 * 1000 </code></pre>
reduceByKey doesn't work in spark streaming <p>I have the following code snippet in which the reduceByKey doesn't seem to work. </p> <pre><code>val myKafkaMessageStream = KafkaUtils.createDirectStream[String, String]( ssc, PreferConsistent, Subscribe[String, String](topicsSet, kafkaParams) ) myKafkaMessageStream .foreachRDD { rdd =&gt; val offsetRanges = rdd.asInstanceOf[HasOffsetRanges].offsetRanges val myIter = rdd.mapPartitionsWithIndex { (i, iter) =&gt; val offset = offsetRanges(i) iter.map(item =&gt; { (offset.fromOffset, offset.untilOffset, offset.topic, offset.partition, item) }) } val myRDD = myIter.filter( (&lt;filter_condition&gt;) ).map(row =&gt; { //Process row ((field1, field2, field3) , (field4, field5)) }) val result = myRDD.reduceByKey((a,b) =&gt; (a._1+b._1, a._2+b._2)) result.foreachPartition { partitionOfRecords =&gt; //I don't get the reduced result here val connection = createNewConnection() partitionOfRecords.foreach(record =&gt; connection.send(record)) connection.close() } } </code></pre> <p>Am I missing something?</p>
<p>In a streaming situation, it makes more sense to me to use <code>reduceByKeyAndWindow</code> which does what you're looking for, but over a specific time frame.</p> <pre><code>// Reduce last 30 seconds of data, every 10 seconds val windowedWordCounts = pairs.reduceByKeyAndWindow((a:Int,b:Int) =&gt; (a + b), Seconds(30), Seconds(10)) </code></pre> <p>"When called on a DStream of (K, V) pairs, returns a new DStream of (K, V) pairs where the values for each key are aggregated using the given reduce function func over batches in a sliding window. Note: By default, this uses Spark's default number of parallel tasks (2 for local mode, and in cluster mode the number is determined by the config property spark.default.parallelism) to do the grouping. You can pass an optional numTasks argument to set a different number of tasks."</p> <p><a href="http://spark.apache.org/docs/latest/streaming-programming-guide.html" rel="nofollow">http://spark.apache.org/docs/latest/streaming-programming-guide.html</a></p>
Trying to make movie of 3D PCA plot (rgl) using movie3d <p>I have made a rgl 3D PCA plot in R using the pca3d package, and I am trying to make a gif file containing a movie of the rotating plot using movie3d. There is a function in the pca3d package (makeMoviePCA), that passes its arguments to movie3d. Here is the command I am using:</p> <pre><code>pca3d(pc, components = 1:3, title=TRUE, col=col_conditions, radius=2) makeMoviePCA(dir="/Users/workdir", clean=TRUE, type = "gif", movie = "movie", convert=TRUE) </code></pre> <p>This plays the movie like I want to, but does not save it into a gif file, and displays the following error:</p> <pre><code>Writing 'movie100.png' ... Writing 'movie120.png' Error in system("convert --version", intern = TRUE) : error in running command sh: convert: command not found </code></pre> <p><strong>EDIT</strong>: I fixed this by telling R where "convert" is by using</p> <pre><code>Sys.setenv(PATH=paste("/opt/local/bin", Sys.getenv("PATH"), sep=":")) </code></pre> <p>Thanks!</p>
<p>I fixed this by telling R where "convert" is by using</p> <pre><code>Sys.setenv(PATH=paste("/opt/local/bin", Sys.getenv("PATH"), sep=":")) </code></pre>
How to (Dirty) Pair DateTimes Across Two Tables <p>I am looking at a SQL Server 2008 Database with two Tables, each with a PK (INT) column and a DateTime column.</p> <p>There is no explicit relationship between the Tables, except I know the application has a heuristic tendency to insert to the database in pairs, one row into each Table, with DateTimes that seem to never match exactly but are usually pretty close.</p> <p>I am trying to match back up the PKs in each table by finding the closest matching DateTime in the other table. Each PK can only be used once for this matching.</p> <p>What is the best way to do this?</p> <p>EDIT: Sorry, please find at bottom some example input and desired output.</p> <pre><code>+-------+-------------------------+ | t1.PK | t1.DateTime | +-------+-------------------------+ | 1 | 2016-08-11 00:11:03.000 | | 2 | 2016-08-11 00:11:08.000 | | 3 | 2016-08-11 11:03:00.000 | | 4 | 2016-08-11 11:08:00.000 | +-------+-------------------------+ +-------+-------------------------+ | t2.PK | t2.DateTime | +-------+-------------------------+ | 1 | 2016-08-11 11:02:00.000 | | 2 | 2016-08-11 00:11:02.000 | | 3 | 2016-08-11 22:00:00.000 | | 4 | 2016-08-11 11:07:00.000 | | 5 | 2016-08-11 00:11:07.000 | +-------+-------------------------+ +-------+-------+-------------------------+-------------------------+ | t1.PK | t2.PK | t1.DateTime | t2.DateTime | +-------+-------+-------------------------+-------------------------+ | 1 | 2 | 2016-08-11 00:11:03.000 | 2016-08-11 00:11:02.000 | | 2 | 5 | 2016-08-11 00:11:08.000 | 2016-08-11 00:11:07.000 | | 3 | 1 | 2016-08-11 11:03:00.000 | 2016-08-11 11:02:00.000 | | 4 | 4 | 2016-08-11 11:08:00.000 | 2016-08-11 11:07:00.000 | +-------+-------+-------------------------+-------------------------+ </code></pre>
<p>JOIN to the row with lowest DATEDIFF (in seconds) between <code>t1.DateTime</code> and <code>t2.DateTime</code>.</p>
Exporting Hash Table Using Property Dictionary to CSV <p>I can't seem to figure out how to simply export formatted information to a CSV unless I iterate through each item in the object and write to the CSV line by line, which takes forever. I can export values instantly to the CSV, it's just when using the properties dictionary I run into issues.</p> <p>The TestCSV file is formatted with a column that has IP addresses.</p> <p>Here's what I have:</p> <pre><code>$CSV = "C:\TEMP\OutputFile.csv" $RX = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.|dot|\[dot\]|\[\.\])){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" $TestCSV = "C:\TEMP\FileWithIPs.csv" $spreadsheetDataobject = import-csv $TestCSV $Finding = $spreadsheetDataObject | Select-String $RX $Props = @{ #create a properties dictionary LineNumber = $finding.LineNumber Matches = $finding.Matches.Value } $OBJ = New-Object -TypeName psobject -Property $Props $OBJ | Select-Object Matches,LineNumber | Export-Csv -Path $CSV -Append -NoTypeInformation </code></pre>
<p>This isn't going to work as written. You are using <code>Import-CSV</code> which creates an array of objects with properties. The <code>Select-String</code> command expects strings as input, not objects. If you want to use <code>Select-String</code> you would want to simply specify the file name, or use <code>Get-Content</code> on the file, and pass that to <code>Select-String</code>. If what you want is the line number, and the IP I think this would probably work just as well if not better for you:</p> <pre><code>$CSV = "C:\TEMP\OutputFile.csv" $RX = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.|dot|\[dot\]|\[\.\])){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" $TestCSV = "C:\TEMP\FileWithIPs.csv" $spreadsheetDataobject = import-csv $TestCSV $spreadsheetDataobject | Where{$_.IP -match $RX} | Select-Object @{l='Matches';e={$_.IP}},@{l='LineNumber';e={[array]::IndexOf($spreadsheetDataobject,$_)+1}} | Export-Csv -Path $CSV -Append -NoTypeInformation </code></pre> <p><strong>Edit:</strong> wOxxOm is quite right, this answer has considerably more overhead than parsing the text directly like he does. Though, for somebody who's new to PowerShell it's probably easier to understand. </p> <p>In regards to <code>$_.IP</code>, since you use <code>Import-CSV</code> you create an array of objects. Each object has properties associated with it based on the header of the CSV file. <code>IP</code> was listed in the header as one of your columns, so each object has a property of <code>IP</code>, and the value of that property is whatever was in the IP column for that record.</p> <p>Let me explain the <code>Select</code> line for you, and then you'll see that it's easy to add your source path as another column.</p> <p>What I'm doing is defining properties with a hashtable. For my examples I will refer to the first one shown above. Since it is a hashtable it starts with <code>@{</code> and ends with <code>}</code>. Inside there are two key/value pairs:</p> <pre><code>l='Matches' e={$_.IP} </code></pre> <p>Essentially 'l' is short for Label, and 'e' is short for Expression. The label determines the name of the property being defined (which equates to the column header when you export). The expression defines the value assigned to the property. In this case I am really just renaming the IP column to Matches, since the value that I assign for each row is whatever is in the IP field. If you open the CSV in Excel, copy the entire IP column, paste it in at the end, and change the header to Matches, that is basically all I'm doing. So to add the file path as a column we can add one more hashtable to the <code>Select</code> line with this:</p> <pre><code>@{ l='FilePath' e={$CSV} } </code></pre> <p>That adds a third property, where the name is FilePath, and the value is whatever is stored in <code>$CSV</code>. That updated <code>Select</code> line would look like this:</p> <pre><code> Select-Object @{l='Matches';e={$_.IP}},@{l='LineNumber';e={[array]::IndexOf($spreadsheetDataobject,$_)+1}},@{l='FilePath'e={$CSV}} | </code></pre>
Access Javascript array in Spring mvc controller <p>Right now I am sending some parameters through URL to the controller in spring mvc project. If the parameters are too long the url is more than 2083 characters which IE do not accept more than 2083 characters in a url.So I am thinking to access the front end JavaScript array in the backend controller. How is it possible or any other better alternative suggestion please?</p>
<p>It is not possible "to access the front end JavaScript array in the backend controller". The JavaScript array (and the logic around it) is in the browser, and your Java backend is on your server. The communication path are the URLs.</p> <p>You're probably currently sending your parameters with GET requests. You have to switch to POST requests, then you'll be able to send much much more than 2000 characters.</p> <p>See Spring docs section "<code>Mapping Requests With @RequestMapping</code>", depending on the Spring version you use, e.g.:</p> <ul> <li><a href="http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#mvc-ann-requestmapping" rel="nofollow">Spring 3.1.x</a></li> <li><a href="http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-requestmapping" rel="nofollow">Spring 4.3.x</a></li> </ul>
How to set properly a SPF record in WHM <p>we ran a test in <a href="https://www.mail-tester.com/" rel="nofollow">https://www.mail-tester.com/</a> by sending an email for mail spam test and this was the result:</p> <p><a href="http://i.stack.imgur.com/hwIm4.png" rel="nofollow"><img src="http://i.stack.imgur.com/hwIm4.png" alt="Test Result"></a></p> <p>then we tried to add that SPF record in our WHM page like this:</p> <ol> <li><a href="http://i.stack.imgur.com/LiEKv.png" rel="nofollow"><img src="http://i.stack.imgur.com/LiEKv.png" alt="enter image description here"></a></li> </ol> <p>2. <a href="http://i.stack.imgur.com/POosy.png" rel="nofollow"><img src="http://i.stack.imgur.com/POosy.png" alt="enter image description here"></a></p> <p>its been more than 12 hours since we applied that change but the problem still remains, how do we fix that?</p>
<p>There could be more email servers responsible for sending your email. Therefore, you must enter SPF record provided by your web host and not the one recommended by mail-tester.com</p> <p>with <strong>-all</strong> in SPF record, you're hard failing all other email servers and just allowing one.</p> <p>It's also possible that there is no email server on your given IP address because some web hosts use third party email servers to send you email. In this case, they will provide you SPF record for the party email servers.</p> <p>Putting right SPF record, as provided by your web host / email host would solve your issue.</p>
Using gulp-sass, how do I preserve the folder structure of my sass files except for the immediate parent directory? <p>I have a project with multiple folders that contain sass files:</p> <pre><code>|── src └── scripts └── app1 └── sass └── base.scss └── app2 └── sass └── base.scss </code></pre> <p>I also have a gulp task that compiles those <code>.scss</code> files using <code>gulp-sass</code> and <code>gulp-concat-css</code>:</p> <pre><code>gulp.task('build:sass', () =&gt; gulp.src([ 'scripts/**/*.scss' ]) .pipe(plugins.sass().on('error', plugins.sass.logError)) .pipe(plugins.concatCss('bundle.css')) .pipe(gulp.dest('dist')) ); </code></pre> <p>Right now, the above task just creates <code>bundle.css</code> into the <code>dist</code> folder:</p> <pre><code>|── dist └── bundle.css </code></pre> <p>What I'd like to have happen is this, where the initial folder structure is preserved, except for the <code>sass</code> folder is now <code>css</code>.</p> <pre><code>|── dist └── scripts └── app1 └── css └── bundle.css └── app2 └── css └── bundle.css </code></pre>
<p>You can use the <a href="https://www.npmjs.com/package/gulp-flatmap" rel="nofollow"><code>gulp-flatmap</code></a> plugin to solve this:</p> <pre><code>var path = require('path'); gulp.task('build:sass', () =&gt; gulp.src('scripts/app*/') .pipe(plugins.flatmap((stream, dir) =&gt; gulp.src(dir.path + '/**/*.scss') .pipe(plugins.sass().on('error', sass.logError)) .pipe(plugins.concatCss('css/bundle.css')) .pipe(gulp.dest('dist/' + path.basename(dir.path))) )) ); </code></pre> <p>This selects all of your <code>app</code> directories and then maps each of those directories to a new stream in which all <code>.scss</code> files in that particular directory are concatenated into a single <code>bundle.css</code> file.</p>
Is there any resource to learn how drupal 8 configurations work? <p>I'm confused to know how to drupal 8 configurations work,if there any resources please list them.</p>
<p>Managing your site's configuration <a href="https://www.drupal.org/docs/8/configuration-management/managing-your-sites-configuration" rel="nofollow">https://www.drupal.org/docs/8/configuration-management/managing-your-sites-configuration</a></p> <p>Defining and using your own configuration in Drupal 8 <a href="https://www.drupal.org/docs/8/creating-custom-modules/defining-and-using-your-own-configuration-in-drupal-8" rel="nofollow">https://www.drupal.org/docs/8/creating-custom-modules/defining-and-using-your-own-configuration-in-drupal-8</a></p> <p>Your Complete Introduction to Drupal 8 Configuration Management <a href="https://www.ostraining.com/blog/drupal/config/" rel="nofollow">https://www.ostraining.com/blog/drupal/config/</a></p>
Keeping Submit Button Disabled Until Form Fields Are Full <p>Would someone be able to take a look at my code and see what I'm missing here?</p> <p>I have a multi-page form with quite a lot of inputs, and I would like to keep "next page" buttons and the final "submit" buttons disabled until all the fields are full.</p> <p>I am trying to recreate the process on a smaller scale but in my tests, I cannot seem to re-enable the disabled submit input. I've checked the console and the JS is logging the variable elements so I'm not sure what I'm missing.</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>function checkForm() { var elements = document.forms[0].elements; var cansubmit= true; for(var i = 0; i &lt; elements.length; i++) { if(elements[i].value.length == 0 || elements[i].value.length == "" || elements[i].value.length == null) { cansubmit = false; } document.getElementById("myButton").disabled = !cansubmit; } };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form&gt; &lt;label for="firstName"&gt;First Name:&lt;/label&gt; &lt;input type="text" id="firstName" onkeyup="checkForm()" /&gt; &lt;br /&gt; &lt;label for="lastName"&gt;Last Name:&lt;/label&gt; &lt;input type="text" id="lastName" onkeyup="checkForm()" /&gt; &lt;button type="button" id="myButton" disabled="disabled"&gt;Test me&lt;/button&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
<p>Your <code>elements</code> array includes your <code>button</code>, which has no value. This will cause your loop to always evaluate to <code>cansubmit = false;</code>.</p> <p>Try this instead: <a href="https://jsfiddle.net/e00sorLu/2/" rel="nofollow">https://jsfiddle.net/e00sorLu/2/</a></p> <pre><code>function checkForm() { var elements = document.forms[0].elements; var cansubmit= true; for(var i = 0; i &lt; elements.length; i++) { if(elements[i].value.length == 0 &amp;&amp; elements[i].type != "button") { cansubmit = false; } } document.getElementById("myButton").disabled = !cansubmit; }; </code></pre>
Excel Macro to grab data from other spreadsheet <p>I need to write a macro in Excel that basically takes the count of data in another spreadsheet and puts it in the current spreadsheet. For ex. Spreadsheet B has 6 rows filled in column G. I want spreadsheet A to take the number 6 and add it to its own spreadsheet. Any help is appreciated. I have never worked on macros before. Thank you</p>
<p>Since this doesn't seem to be going anywhere in the comments. You can refer to a closed workbook with a sheet formula. In your case, something like:</p> <pre><code> =COUNTA('C:\[Book2.xlsx]Sheet1'!G:G) </code></pre> <p>To make this easy, open both workbooks. In workbook a type <code>=CountA(</code> and then select column G in workbook B so it will bring in the reference. Then close workbook B and you will have a formula like the one above. Done and done.</p>
Firebase3 listen for change event and get the old data value <p>On Firebase3 I am looking for a way to get to old value from an item in an firebasearray. Is there anyway to do it or can we ovveride the child_changed event? Solution should be for firebase 3 javascript sdk.</p> <pre class="lang-js prettyprint-override"><code>var commentsRef = firebase.database().ref('post-comments/' + postId); commentsRef.on('child_changed', function(data) { // data variable holds new data. I want the old one before the update happened! }); </code></pre>
<p>There is no way to get the old value with an event. If you need that, you'll have to track it yourself.</p> <pre><code>var commentsRef = firebase.database().ref('post-comments/' + postId); var oldValue; commentsRef.on('child_changed', function(snapshot) { // TODO: compare data.val() with oldValue ... oldValue = snapshot.val(); }); </code></pre>
Check for duplicates between jQuery elements <p>Does anybody know how to check for duplicate entries in a queries, where query elements are separated by comma.</p> <p>Eg.</p> <pre><code>$query1 = email1,email2,email3; $query2 = email1,email2,email2; $query3 = email4,email5,email6; $query4 = email7,email7,email8; </code></pre> <p>I need to check if there are any duplicates between each <code>$query</code> element? Eg. If in <code>$query1</code> I found <code>email1</code>, then in <code>$query2</code> the same variable would be indicated as a duplicate and so on in all the queries.</p> <p>Thank you!</p>
<p>Use</p> <ul> <li>for separating by comma <code>explode(',',$query)</code> to get an array of entries</li> <li>then test the arrays against each other with <code>in_array($keyFromAnotherArray,$array)</code></li> </ul> <p>that should lead to the solution</p>
change date format in displaying <p>I have this below code where i am trying to alert the date selected on click of an image. I am getting the alert but the issue is date format.</p> <p>Below is alert i am getting. I need the alert in mm/dd/yyy.</p> <p>And also why i am getting Thu Jan 01 1970 if i use todatestring() method.</p> <p>Below is the javascript code </p>
<p>Try this function to return mm/dd/yyyy</p> <pre><code>function getmmDdYy(thisDate) { return ('0' + (thisDate.getMonth() + 1)).slice(-2) + '/' + ("0" + (thisDate.getDate())).slice(-2) + '/' + thisDate.getFullYear(); } </code></pre> <p>So on your <code>fnUpdateDate()</code>, do this:</p> <pre><code>function fnUpdateDate(date1,date2){ alert(getmmDdYy(new Date(date1)) +" ss "+ getmmDdYy(new Date(date2))); } </code></pre> <p>Let me know if this works.</p>
PHP $_POST Array Empty <p>i'm new in coding and have a problem coding on Mac.</p> <p>When i do var_dump($_POST), answer is: array(0){}</p> <p>Here is the code:</p> <pre><code>&lt;?php session_start(); if ($_SERVER["REQUEST_METHOD"] == "POST") { $name=strip_tags($_POST["name"]); $age=$_POST["age"]*1; $_SESSION["name"] = $name; $_SESSION["age"] = $age; } else { $name = $_SESSION["name"]; $age = $_SESSION["age"]; } ?&gt; &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Session demonstration&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Session demonstration&lt;/h1&gt; &lt;a href="session-2.php"&gt;Demo session&lt;/a&gt;&lt;br&gt; &lt;a href="session_destroy.php"&gt;Close session&lt;/a&gt;&lt;br&gt;&lt;br&gt; &lt;form action="&lt;?=$_SERVER["PHP_SELF"]?&gt;" method="post"&gt; Your name is: &lt;input type="text" name="name" value="&lt;?php echo $name?&gt;"&gt;&lt;br&gt; You are: &lt;input type="text" name="age" value="&lt;?php echo $age?&gt;"&gt;&lt;br&gt; &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; &lt;?php if ($name and $age) { if ($name and $age) { echo "&lt;h1&gt;Hello, $name&lt;/h1&gt;"; echo "&lt;h3&gt;You are $age&lt;/h3&gt;"; } else { print "&lt;h3&gt;Bye!&lt;/h3&gt;"; } } ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Same time, when i press submit button it shows me: </p> <p>Notice: Undefined index: name in /Applications/MAMP/htdocs/PHP_Course 2/demo/mod2/sessions/session-1.php on line 5</p> <p>Notice: Undefined index: age in /Applications/MAMP/htdocs/PHP_Course 2/demo/mod2/sessions/session-1.php on line 6</p> <p>Maybe someone knows what can i do.</p> <p>Sincerelly</p>
<p>the problem with this is your session variables are not set at the beginning and you are trying to assign your $name and $age with those unassigned variables on your else block. Validate your assignments like this.</p> <pre><code>&lt;?php session_start(); $name = $age = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = strip_tags($_POST["name"]); $age = $_POST["age"] * 1; $_SESSION["name"] = $name; $_SESSION["age"] = $age; } elseif (isset($_SESSION['name']) || isset($_SESSION['age'])) { if (isset($_SESSION['name'])) { $name = $_SESSION['name']; } if (isset($_SESSION['age'])) { $age = $_SESSION['age']; } } ?&gt; &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Session demonstration&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Session demonstration&lt;/h1&gt; &lt;a href="session-2.php"&gt;Demo session&lt;/a&gt;&lt;br&gt; &lt;a href="session_destroy.php"&gt;Close session&lt;/a&gt;&lt;br&gt;&lt;br&gt; &lt;form action="&lt;?= $_SERVER["PHP_SELF"] ?&gt;" method="post"&gt; Your name is: &lt;input type="text" name="name" value="&lt;?php echo $name ?&gt;"&gt;&lt;br&gt; You are: &lt;input type="text" name="age" value="&lt;?php echo $age ?&gt;"&gt;&lt;br&gt; &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; &lt;?php if ($name and $age) { echo "&lt;h1&gt;Hello, $name&lt;/h1&gt;"; echo "&lt;h3&gt;You are $age&lt;/h3&gt;"; } else { print "&lt;h3&gt;Bye!&lt;/h3&gt;"; } ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
How to rotate image and axes together on Matlab? <p>Code 1 where flipping vertically and/or horizontally does not affect <code>axes()</code>; Code 2 where proposed solution does not yield the expected output</p> <pre><code>close all; clear all; clc; x = [5 8]; y = [3 6]; C = [0 2 4 6; 8 10 12 14; 16 18 20 22]; C2 = C(:,end:-1:1,:); %# horizontal flip C3 = C(end:-1:1,:,:); %# vertical flip C4 = C(end:-1:1,end:-1:1,:); %# horizontal+vertical flip % http://stackoverflow.com/a/4010203/54964 subplot(2,2,1), imagesc(x,y,C) subplot(2,2,2), imagesc(x,y,C2) subplot(2,2,3), imagesc(x,y,C3) subplot(2,2,4), imagesc(x,y,C4) %% Rotations of axes() unsuccessfully % http://stackoverflow.com/a/15071734/54964 figure subplot(2,2,1), imagesc(x,y,C) x = linspace(1, size(C, 2), numel(x)); % reverse only x set(gca, 'XTick', x, 'XTickLabel', x) subplot(2,2,2), imagesc(x,y,C2) x = linspace(1, size(C, 2), numel(x)); % reverse back x set(gca, 'XTick', x, 'XTickLabel', x) % reverse y y = linspace(1, size(C, 1), numel(y)); set(gca, 'YTick', y, 'YTickLabel', flipud(y(:))) subplot(2,2,3), imagesc(x,y,C3) x = linspace(1, size(C, 2), numel(x)); % now both x,y reversed set(gca, 'XTick', x, 'XTickLabel', x) subplot(2,2,4), imagesc(x,y,C4) </code></pre> <p>Fig. 1 Output where axis stay untouched but images are flipped correctly, Fig. 2 Output from attempt with moving <code>xticks</code>/<code>yticks</code></p> <p><a href="http://i.stack.imgur.com/d8PIv.png" rel="nofollow"><img src="http://i.stack.imgur.com/d8PIvm.png" alt="enter image description here"></a> <a href="http://i.stack.imgur.com/ie5zr.png" rel="nofollow"><img src="http://i.stack.imgur.com/ie5zrm.png" alt="enter image description here"></a></p> <p><strong>Expected output</strong>: </p> <ul> <li>Fig.1 (top-left) all correct in axes with figure</li> <li>Fig.2 (top-right) y-axis correct but x-axis from 8 to 5</li> <li>Fig.3 (lower-left) y-axis from 6 to 3 but x-axis correct</li> <li>Fig.4 (lower-right) y-axis correct but x-axis from 3 to 6</li> </ul> <h2>Attempt 2</h2> <p>Code </p> <pre><code>% 1 start of vector 2 end of vector 3 length of vector figure subplot(2,2,1), imagesc(x,y,C) x = linspace(size(C, 2), 1, numel(x)); % reverse only x set(gca, 'XTick', x, 'XTickLabel', x) subplot(2,2,2), imagesc(x,y,C2) x = linspace(1, size(C, 2), numel(x)); % reverse back x set(gca, 'XTick', x, 'XTickLabel', x) y = linspace(size(C, 1), 1, numel(y)); % reverse y set(gca, 'YTick', y, 'YTickLabel', flipud(y(:))) subplot(2,2,3), imagesc(x,y,C3) x = linspace(size(C, 2), 1, numel(x)); % now both x,y reversed set(gca, 'XTick', x, 'XTickLabel', x) y = linspace(1, size(C, 1), numel(y)); % reverse y set(gca, 'YTick', y, 'YTickLabel', flipud(y(:))) subplot(2,2,4), imagesc(x,y,C4) </code></pre> <p>Output</p> <pre><code>Error using matlab.graphics.axis.Axes/set While setting the 'XTick' property of 'Axes': Value must be a vector of type single or double whose values increase Error in test_imagesc_subplot_figure (line 26) set(gca, 'XTick', x, 'XTickLabel', x) </code></pre> <h2>Eskapp's proposal</h2> <p>I do unsuccessfully the following but no change on Fig. 2; the first row of figures stay in the same increasing order of <code>xaxis</code>; I also tried instead of <code>reverse</code> - <code>normal</code></p> <pre><code>figure subplot(2,2,1), imagesc(x,y,C) x = linspace(1, size(C, 2), numel(x)); % reverse only x set(gca,'xdir','reverse') subplot(2,2,2), imagesc(x,y,C2) </code></pre> <ul> <li><p>Output of Fig. 1 and Fig. 2 <code>axis</code> stay the same </p> <p><a href="http://i.stack.imgur.com/yhLON.png" rel="nofollow"><img src="http://i.stack.imgur.com/yhLONm.png" alt="enter image description here"></a></p></li> </ul> <h2>Studying EBH's <a href="http://stackoverflow.com/a/39937511/54964">answer</a></h2> <p>Output in the y-axis label when using <code>set(gca,'XTick',x,'XTickLabel',x, 'YTick',y,'YTickLabel',fliplr(y))</code> with variables <code>y=linspace(0,180,181); x=0:0.5:10</code></p> <p><a href="http://i.stack.imgur.com/zzmlQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/zzmlQs.png" alt="enter image description here"></a></p> <p>Matlab: 2016a<br> OS: Debian 8.5 64 bit<br> Hardware: Asus Zenbook UX303UA </p>
<p>If I correctly understand your question, then this code does what you look for:</p> <pre><code>x = 5:8; y = 3:6; C = reshape(0:2:22,4,3).'; C2 = fliplr(C); % horizontal flip C3 = flipud(C); % vertical flip C4 = rot90(C,2); % horizontal+vertical flip % the answer starts here: subplot(2,2,1), imagesc(x,y,C) set(gca,'XTick',x,'XTickLabel',x,... 'YTick',y,'YTickLabel',y) subplot(2,2,2), imagesc(x,y,C2) set(gca,'XTick',x,'XTickLabel',fliplr(x),... 'YTick',y,'YTickLabel',y) subplot(2,2,3), imagesc(x,y,C3) set(gca,'XTick',x,'XTickLabel',x,... 'YTick',y,'YTickLabel',fliplr(y)) subplot(2,2,4), imagesc(x,y,C4) set(gca,'XTick',x,'XTickLabel',fliplr(x),... 'YTick',y,'YTickLabel',fliplr(y)) </code></pre> <p>the result:</p> <p><a href="http://i.stack.imgur.com/IMmdY.png" rel="nofollow"><img src="http://i.stack.imgur.com/IMmdY.png" alt="rot_axes"></a></p> <p>I changed you <code>x</code> and <code>y</code> from 2-element vectors, but it works also if:</p> <pre><code>x = [5 8]; y = [3 6]; </code></pre> <p>BTW...</p> <p>Instead of manipulating <code>C</code> and create <code>C2</code>...<code>C4</code>, you can just write:</p> <pre><code>subplot 221, imagesc(x,y,C) subplot 222, imagesc(fliplr(x),y,C) subplot 223, imagesc(x,fliplr(y),C) subplot 224, imagesc(fliplr(x),fliplr(y),C) </code></pre> <p>and add the manipulation on the axis after each call to <code>subplot</code> like before.</p> <hr> <p><strong>Edit</strong>:</p> <p>Using your sizes and limits of the vectors:</p> <pre><code>x = linspace(0,10,6); y = linspace(0,180,19); % no need to plot each label N = 3613; C = diag(1:N)*ones(N)+rot90(diag(1:N)*ones(N)); % some arbitrary matrix </code></pre> <p>where all the rest of the code above remains the same, I get the following result:</p> <p><a href="http://i.stack.imgur.com/xd8GH.png" rel="nofollow"><img src="http://i.stack.imgur.com/xd8GH.png" alt="rot_ax2"></a></p>
Lazy loading Angular modules with Webpack <p>I'm trying to get lazy-loaded Angular modules working with Webpack, but I'm having some difficulties. Webpack appears to generate the split point correctly, because I see a <code>1.bundle.js</code> getting created that contains the code for the child app, but I don't see any request for <code>1.bundle.js</code> when I load the page, and the child app doesn't initialize. The <code>console.log</code> never seems to fire, and it doesn't even appear to get to the point where <code>$oclazyload</code> would initialize the module.</p> <p>There are a few points where I am confused.</p> <p>1) Will webpack make the request to the server, or do I have to load the second bundle manually? (I've tried both, and neither works)</p> <p>2) If I do need to load the bundles manually, in what order should they be loaded?</p> <p>3) The third argument to <code>require.ensure</code> supposedly lets you control the name of the bundle, but the bundle is named <code>1.bundle.js</code> no matter what string I pass.</p> <p>4) Why can't I step through the code inside the <code>require.ensure</code> block in the debugger? When I do so I end up looking at this in the Chrome source view:</p> <pre><code>undefined /** WEBPACK FOOTER ** ** **/ </code></pre> <p>(Code Below)</p> <p>Main entry point code:</p> <pre><code>'use strict'; import angular from 'angular'; import 'angular-ui-router'; import 'oclazyload'; angular.module('parentApp', [ 'ui.router', ]) .config(['$urlRouterProvider', '$locationProvider', ($urlRouterProvider, $locationProvider) =&gt; { $urlRouterProvider .otherwise('/'); $locationProvider.html5Mode(true); }]) .config(['$stateProvider', ($stateProvider) =&gt; { $stateProvider .state('child-app', { url: '/child-app', template: '&lt;child-app&gt;&lt;/child-app&gt;', resolve: { loadAppModule: ($q, $ocLazyLoad) =&gt; { return $q((resolve) =&gt; { require.ensure(['./child-app/app.js'], (require) =&gt; { let module = require('./child-app/app.js'); console.log(module); $oclazyload.load({name: 'childApp'}); resolve(module.controller); }); }) } }, controller: function() { } }) }]); </code></pre> <p>Child app:</p> <pre><code>'use strict'; import childAppTemplateURL from '../templates/child-app.html'; import childAppController from './controllers/childAppController'; export default angular.module('parentApp.childApp', []) .component('applicationListApp', { templateUrl: childAppTemplateURL, controller: childAppController }); </code></pre>
<p>The problem was unrelated to the <code>require.ensure</code> implementation. It was caused by some weirdness in the way <code>ocLazyLoad</code> is packaged (<a href="https://github.com/ocombe/ocLazyLoad/issues/179" rel="nofollow">https://github.com/ocombe/ocLazyLoad/issues/179</a>). The fix in my case was simple, I just added <code>'oc.lazyLoad'</code> to the module dependencies.</p> <pre><code>angular.module('parentApp', [ 'ui.router', 'oc.lazyLoad' ]) </code></pre> <p>To answer two of my own questions, Webpack does indeed make a request to the server for the bundle, and you do not have to manually load the bundle. One gotcha that really confused me: the <code>resolve</code> block will fail silently if it contains a promise that won't resolve. In my case <code>$ocLazyLoad.load()</code> was failing, but there was no indication of the failure. The only clue was that the state provider wasn't adding the <code>&lt;child-app&gt;&lt;/child-app&gt;</code> markup to the DOM, which meant that it was actually initializing the state.</p>
Why are my callbacks not firing with async queue? <p>I am using <a href="http://caolan.github.io/async/docs.html#.QueueObject" rel="nofollow">async queue</a> to process a huge amount of data. The queue works great until I try to perform an update in the database with <a href="https://docs.mongodb.com/v3.2/reference/method/db.collection.findOneAndUpdate/" rel="nofollow">MongoDB findOneAndUpdate</a> method.</p> <p>I first establish the queue, and start pushing objects to it from a Node Stream: </p> <pre><code>//Create queue to process all items let q = async.queue(processLink, 2); // Create Node Stream let createStream = function () { let stream = fs.createReadStream(LinkData, {encoding: 'utf8'}); let parser = JSONStream.parse('RECDATA.*'); return stream.pipe(parser); }; //Listen to 'data' event on stream and add object to queue createStream().on('data', function(link){ q.push(link) }); </code></pre> <p>Here is my task function, 'processLink'. It is here, that I am having trouble tracking down the problem. Whenever the findOneAndUpdate callback is fired, it enters one of the conditional blocks, and I am getting the message logged out to the console, but when I call the async callback processComplete(), the task does not finish as expected. </p> <p>As the title suggests, Why are my async callbacks not completing each task? </p> <pre><code>function processLink(link, processComplete){ if(_.includes(link.URL, 'www.usda.gov') &amp;&amp; _.includes(link.URL, '?recid=')){ let url_items = _.split(link.URL, '=',2); let facilityOrgID = url_items[1]; let update = {$push: {"links": link}}; if(_.isNumber(parseInt(facilityOrgID)) &amp;&amp; facilityOrgID.length &gt; 4 ){ Facility.findOneAndUpdate({facilityOrgID: parseInt(facilityOrgID)}, update, (err, result) =&gt; { if(err !== null){ console.log("Error:",err); return processComplete(err); /** NOT FIRING **/ } else if(err === null &amp;&amp; result !== null){ console.log("Link added to:", result.name); return processComplete(); /** NOT FIRING **/ }else if(err === null &amp;&amp; result === null){ console.log('Facility not in database'); processComplete(); /** NOT FIRING **/ }else{ console.log('Something has gone terrible wrong'); } }); }else{ console.log("Invalid facilityID"); return processComplete(); } }else{ console.log('Link Discarded:', link.URL); processComplete(); /** Fires normally **/ } } </code></pre>
<p>I solved my problem this morning. The callbacks were fine, but rather there was a conditional state of the data I was not aware of, thus it was leading to a state in which the code would never call the processComplete() callback. </p> <p>If anyone else is finding themselves in a similar bind, and you have tons of data, I would ensure that your data is being reported accurately and there are not some edge cases that were not being processed as expected. </p>
How to use different IDE with Netsuite <p>I'm admittedly new to Netsuite, so this may be obvious, although I've been unable to find anything specific one way or the other. In fact, I don't even attend any training until next week, but I'm trying to get part of my development environment setup with one of the editors/IDEs I prefer. I know that Netsuite offers an Eclipse plugin, but I'm not an Eclipse fan. I'd prefer to use either WebStorm or TextMate. (I'm on MacOS Sierra) </p> <p>I tried installing the WebStorm plugin, but it's throwing an exception and is not functional. I submitted a bug on GitHub, but what I'd really like to know is if it's possible for me to write my own script to upload/download files to the cabinet, so I could just roll my own feature in TextMate. Is this possible, and if so, how? (Just a link to the docs is perfectly fine)</p> <p>In other words, is it possible via their API, to submit changes to a script I've been working on in another editor/IDE? Or interact with our cabinet? (Not sure if I'm using the proper NS verbiage, but hopefully you get my intent) I'm thinking about writing a Python script, that accepts a local script path as a parameter, that will then get submitted to our cabinet. Thanks for the help in advance.</p>
<p>I don't like eclipse personally, so I just make my scripts in whatever and use Netsuite's script backend to upload the scripts as 'new' when I'm done. If I want to change them, simply use their backend again to 'edit' the script. You'll see a simple editor, where you can change things, or you just copy and paste what you have in there. It's a little more work than something integrated, but it does work..</p>
Python Load csv file to Oracle table <p>I'm a python beginner. I'm trying to insert records into a Oracle table from a csv file. csv file format : Artist_name, Artist_type, Country . I'm getting below error:</p> <pre><code>Error: File "artist_dim.py", line 42, in &lt;module&gt; cur.execute(sqlquery) cx_Oracle.DatabaseError: ORA-00917: missing comma import cx_Oracle as cx import csv import sys ##### Step 1 : Connect to Oracle Database######### conn_str=u'hr/hr@localhost:1521/PDBORCL' conn= cx.connect(conn_str) cur=conn.cursor() ####################################### #### Step 2: FETCH LATEST ROW ID FROM ARTIST_DIM### query="SELECT nvl(max(row_id)+1,1) from artist_dim" cur.execute(query) rownum=cur.fetchone() x=rownum[0] with open('D:\python\Artist.csv') as f: reader=csv.DictReader(f,delimiter=',') for row in reader: sqlquery="INSERT INTO ARTIST_DIM VALUES (%d,%s,%s,%s)" %(x,row['Artist_name'],row['Artist_type'],row['Country']) cur.execute(sqlquery) x=x+1 conn.commit() </code></pre> <p>When I try to read the file it is working correctly.</p> <pre><code> ##### Just to Read CSV File############################ with open('D:\python\Artist.csv') as f: reader = csv.DictReader(f, delimiter=',') for row in reader: a="row_id %d Artist : %s type : %s Country : %s " %(x,row['Artist_name'],row['Artist_type'],row['Country']) print(a) x=x+1 print(row['Artist_name'],",",row['Artist_type'],",",row['Country']) Also, when I try to insert using hard coded values it is working sqlquery1="INSERT INTO ARTIST_DIM VALUES (%d,'Bob','Bob','Bob')" %x cur.execute(sqlquery1) </code></pre>
<p>Put quotes around the values:</p> <pre><code>sqlquery="INSERT INTO ARTIST_DIM VALUES (%d,'%s','%s','%s')" %(x,row['Artist_name'],row['Artist_type'],row['Country']) </code></pre> <p>Without the quotes it translates to:</p> <pre><code>sqlquery="INSERT INTO ARTIST_DIM VALUES (1, Bob, Bob, Bob)" </code></pre>
C# - require a returned type to be assigned to an L-Value? <p>this may not be sensible, but i'm looking at a situation where i would like it to be a compile error if the return value of a method goes unused.</p> <p>specifically, Unity3D implements coroutines which look like this:</p> <pre><code>IEnumerator myCoroutine() {... yield break;} </code></pre> <p>if you call <code>myCoroutine()</code> and do nothing with the returned value (eg, you're calling it like a normal method, not from inside another yield clause or via the StartCoroutine() method), the result is that all the code inside myCoroutine() is not executed. <em>however</em>, there is no compile- or runtime- warning. i would like to get a compile-time error in this scenario.</p> <p>one approach i thought of is to subclass IEnumerator into say MyIEnumerator, which adds the property that it must be passed on in some way - either assigned to an L-Value or passed to a method, etc.</p> <p>but i haven't been able to discover if such a requirement exists.</p>
<p>There is no such feature in C# for this. You'd need to create some form of 3rd party code analysis tool to try to look for cases such as these.</p>
Admin panel and user panel in one solution ASP.NET <p>i am developing an online election web page using <code>ASP.NET</code>.I have completed the user panel.Now i am trying to develop the Admin panel for my web site.</p> <p><a href="http://i.stack.imgur.com/dfOUH.png" rel="nofollow">This is my project</a></p> <p>I have created the both admin panel and user panel as <code>Web Application</code> and included both them in one <code>Solution</code> explorer. Is this the standard of using an admin panel in a website ? If not can you suggest me how to do this.</p> <p>Thanx in advance !</p>
<p>Create a separate, protected folder for your admin forms. Then use membership to create users and roles: for example, you could have admin and editor roles limiting administration abilities, etc.</p> <p><a href="https://www.asp.net/identity" rel="nofollow">https://www.asp.net/identity</a> </p> <p>Looking at your solution, I would make the following suggestions: it is not "necessary" to have your admin logic in a separate project but that might be dictated by your support/maintenance priorities later on. I would not use the word "panel" as this suggests an ASP.NET control.</p>
net core - convert reader to json <p>I am working with <code>.net core 1.0.1</code>. I want to execute a stored procedure from a Sql Server Table. I can connect to the database correctly, now I have the following code:</p> <pre><code>var con = _context.Database.GetDbConnection(); var cmd = con.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "procedures.sp_Users"; cmd.Parameters.Add(new SqlParameter("@Command", SqlDbType.VarChar) { Value = "Login" } ); cmd.Parameters.Add(new SqlParameter("@user", SqlDbType.VarChar) { Value = "admin" } ); cmd.Parameters.Add(new SqlParameter("@pass", SqlDbType.VarChar) { Value = "admin" } ); var reader = cmd.ExecuteReader(); </code></pre> <p>So I want to convert this <code>reader</code> to a JSON string for returning it in a controller.</p> <p>How can I achieve it?</p> <p>I read I can not use <code>DataTable</code> and <code>DataSet</code> because they are not cross-platform.</p>
<p>Solved with the following:</p> <pre><code>var con = _context.Database.GetDbConnection(); var cmd = con.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "procedures.sp_Users"; cmd.Parameters.Add(new SqlParameter("@Command", SqlDbType.VarChar) { Value = "Login" } ); cmd.Parameters.Add(new SqlParameter("@user", SqlDbType.VarChar) { Value = "admin" } ); cmd.Parameters.Add(new SqlParameter("@pass", SqlDbType.VarChar) { Value = "admin" } ); var retObject = new List&lt;dynamic&gt;(); con.Open(); using (var dataReader = cmd.ExecuteReader()) { while (dataReader.Read()) { var dataRow = new ExpandoObject() as IDictionary&lt;string, object&gt;; for (var iFiled = 0; iFiled &lt; dataReader.FieldCount; iFiled++) dataRow.Add( dataReader.GetName(iFiled), dataReader.IsDBNull(iFiled) ? null : dataReader[iFiled] // use null instead of {} ); retObject.Add((ExpandoObject)dataRow); } } return retObject; </code></pre> <p>As suggested in the following <a href="http://stackoverflow.com/questions/34745822/how-can-i-call-a-sql-stored-procedure-using-entityframework-7-and-asp-net-5">link</a></p>
Windowactivate three windows with same name <p>In Pulover's Macro creator I'd like to use the command <em>windowactivate</em> to activate 3 windows sequentially. They share the same name. </p> <p>I tried to create a loop but it didn't work as expected.</p> <p>How can I solve this?</p>
<pre><code>; auto-execute section (top of the script): GroupAdd, GroupName, WinTitle ; return ; end of auto-execute section ; F1:: Loop 3 ; { GroupActivate, GroupName ; Sleep 1000 ; } ; return </code></pre> <p><a href="https://autohotkey.com/docs/commands/GroupAdd.htm" rel="nofollow">https://autohotkey.com/docs/commands/GroupAdd.htm</a></p> <p><a href="https://autohotkey.com/docs/commands/GroupActivate.htm" rel="nofollow">https://autohotkey.com/docs/commands/GroupActivate.htm</a></p> <p><strong>EDIT</strong>:</p> <p>If I understand you correctly, you want to record mouse or\and keyboard actions in each of the three windows using Pulover's Macro Creator.</p> <p>Then you can use this script to activate the next window while Macro Creator is running:</p> <pre><code>GroupAdd, GroupName, WinTitle return ; Press F1 to activate the next window in the group: F1:: GroupActivate, GroupName </code></pre> <p>Don't forget to </p> <p>add </p> <pre><code>GroupAdd, GroupName, WinTitle </code></pre> <p>in the autoexecute-section of the final script and</p> <pre><code>GroupActivate, GroupName </code></pre> <p>in places where the next window needs to become active</p> <p>and remove lines such as</p> <pre><code>Send, {F1} </code></pre> <p>etc. created from this script in Pulover's Macro Creator.</p>
Picasso with OKHttp not displaying image: log error <p>I'm trying to download and cache an image with picasso from a webserver. I found a solution right here: <a href="http://stackoverflow.com/a/30686992/6884064">http://stackoverflow.com/a/30686992/6884064</a></p> <pre><code> Picasso.Builder builder = new Picasso.Builder(this); builder.downloader(new OkHttpDownloader(this,Integer.MAX_VALUE)); Picasso built = builder.build(); built.setIndicatorsEnabled(true); built.setLoggingEnabled(true); Picasso.setSingletonInstance(built); Picasso.with(this) .load("http://i.imgur.com/Q85lste.jpg") .networkPolicy(NetworkPolicy.OFFLINE) .into(coverImg); </code></pre> <p>Build.gradle:</p> <pre><code>compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.squareup.okhttp:okhttp:2.4.0' compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0' </code></pre> <p>When I run it my placeholder image disappears but the new image doesn't load in.</p> <p>The run log gives me this:</p> <pre><code>D/Picasso: Main created [R0] Request{http://i.imgur.com/Q85lste.jpg} D/Picasso: Dispatcher enqueued [R0]+6ms D/Picasso: Hunter executing [R0]+7ms W/System.err: remove failed: ENOENT (No such file or directory) : /data/user/0/com.test.example1/cache/picasso-cache/journal.tmp D/Picasso: Dispatcher batched [R0]+45ms for error D/Picasso: Dispatcher delivered [R0]+246ms D/Picasso: Main errored [R0]+246ms </code></pre> <p>Anyone know what's going on here? Thanks!</p> <p><strong>EDIT:</strong></p> <p>It's working with this code: </p> <pre><code> OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder().header("Cache-Control", "max-age=" + (60 * 60 * 24 * 365)).build(); } }); okHttpClient.setCache(new Cache(getCacheDir(), Integer.MAX_VALUE)); OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient); Picasso picasso = new Picasso.Builder(this).downloader(okHttpDownloader).build(); picasso.load("http://i.imgur.com/test.jpg").into(coverImg); </code></pre>
<p>If you try in android Studio emulator, clean Cache and data of app and uninstall and then install it again. And also don't forget required permissions:</p> <pre><code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; </code></pre> <p>maybe worked. good luck.</p>
Convert char to byte <p>I am trying to convert char array to byte. But I am getting the below error:</p> <blockquote> <p>Cannot implicitly convert int to byte</p> </blockquote> <pre><code>public byte[] asciiToDecConversion(char[] asciiCharArray) { byte[] decimalArray = new byte[10]; const byte asciiFormat = 32; for (int j = 0; j &lt; 10; j++) { decimalArray[j] = (Convert.ToByte(asciiCharArray[j]) - asciiFormat); } return decimalArray; } </code></pre>
<p>You need to cast to byte:</p> <pre><code>decimalArray[j] = (byte) (Convert.ToByte(asciiCharArray[j]) - asciiFormat); </code></pre>
Is there a good "Laravel way" to escape html when returning json results? <p>I feel like this should be a common problem, but I haven't been able to find an answer for it. Blade templates make escaping html easy with <code>{{ $variable }}</code>, but for outputting json to an ajax request, not so much.</p> <p>Naturally, I work with an app that does a lot of ajax calls for user inputted data and returns the results as JSON to the client, which renders it in a jQuery DataTable. So consider this scenario:</p> <pre><code>$contacts = Contact::whereUserId(Auth::id()) -&gt;select('id', 'first_name', 'last_name', 'email', 'age') -&gt;get(); return response()-&gt;json($contacts); </code></pre> <p>I want to escape those name fields for html/script injection before rendering them in a DataTable, such as first and last names. The only way I can think to do it is to loop through each row in the collection, and for each, loop through each field, and if it's a string, use <code>e()</code> on it.</p> <p>Is there something in the Laravel framework to handle this process? Or a good package? I'd rather not do it every time <code>toJson()</code> runs, since there may be times I don't want to run that, or like if it's an API call and I need to return the raw json data.</p> <p>Any advice? I'm currently on Laravel 5.2.</p> <p>For the record, only a few of my fields are meant to contain html.</p> <p>UPDATE: As pointed out in the comments, I am using DataTables. Currently, I use the <code>render</code> option, which is just a closure, on each column I want to escape and use a javascript-based strip tags/html entities function. I kind of felt like I was doing it wrong, that there should be some function to do this automatically in the Laravel framework given how common it is plus the way blade templates are set up, but is this considered an ideal solution then?</p>
<p>jQuery DataTables doesn't escape HTML so that if field contains <code>&lt;b&gt;Text&lt;/b&gt;</code> it will be shown in bold in a table by default.</p> <p>You can encode HTML entities in your response using the code below:</p> <pre><code>return response()-&gt;json(array_map('e', $contacts-&gt;toArray())); </code></pre> <p>If you're using Yajra DataTables for Laravel, it has <code>escapeColumns()</code> method which you can use to escape HTML entities in some or all columns. For example:</p> <pre><code>return Datatables::of($contacts) -&gt;escapeColumns(['first_name', 'last_name') -&gt;make(true); </code></pre>
Deref a C pointer to a string within a struct within an array? <p>I have a thorny C syntax question. I'm building an array of linked lists, where each node in a list is represented by a struct. Each struct holds a string, which is important later:</p> <pre><code>// "linkedList.h" typedef struct llnode listnode; struct llnode { char* data; // string // ...and other data }; </code></pre> <p>My code builds a table of pointers to these "listnodes" and sets all those pointers to NULL, for reasons beyond the scope of this post:</p> <pre><code>void initTable(listnode** table){ // Initialize all pointers in the table to NULL for (int i = 0; i &lt; TABLESIZE; i++) table[i] = NULL; } int main(){ // Create table of linked lists listnode** table = (listnode**) malloc(TABLESIZE * sizeof(listnode*)); initTable(table); return 1; } </code></pre> <p>So far, so good. Later, my program stuffs data into the table, adding on to the right linked list if/when necessary. The code to do that works, but I'll offer up a HIGHLY simplified version here for the sake of keeping my post as brief as possible:</p> <pre><code>void insert(listnode** table, int index, char* newData){ if(*(table+index)==NULL){ // Create the new Node listnode *newNode = NULL; newNode = (listnode*)malloc(sizeof(listnode)); // allocate for the struct newNode-&gt;data = (char*)malloc(sizeof(char)*15); // allocate for the string within the struct strcpy(newNode-&gt;data, newData); // copy newData into newNode-&gt;data // Insert node into table (Super simple version) *(table+index) = newNode; } } int main(){ listnode** table = (listnode**) malloc(TABLESIZE * sizeof(listnode*)); initTable(table); insert(table, 0, "New String A"); insert(table, 5, "New String B"); insert(table, 7, "New String C"); return 1; } </code></pre> <p>All this works great. Now for my real question... Suppose I want to reach into the table and dereference one of those strings?</p> <pre><code>void printTable(listnode** table){ for(int i=0; i&lt;TABLESIZE; i++){ if(*(table+i)==NULL) printf("table[%d] == NULL\n", i); else printf("table[%d] == %s\n", i, **(table+i)-&gt;data); // &lt;&lt; PROBLEM IS HERE! } } int main(){ // create &amp; initialize the table, as above // insert data into the table, as above printTable(table); return 1; } </code></pre> <p>The compiler doesn't like my syntax:</p> <pre><code>$ gcc -Wall linkedList.c linkedListc: In function ‘printTable’: linkedList.c:31:48: error: request for member ‘data’ in something not a structure or union printf("table[%d] == %s\n", i, **(table+i)-&gt;data); ^ $ </code></pre> <p>So I know this is kinda a long-winding premise for a simple question, but can someone help me with the proper syntax here? I've tried a number of syntactical variations, with no luck.</p> <p>More puzzling, when I modify the code a little to compile it, then look at this in GDB, I can see that <code>**(table+i)</code> is my struct, yet <code>**(table+i)-&gt;data</code> is not accessible. Here's the GDB output when I debug the (modified) program; the node representing "New String A" is inserted first at index 0 in the table. :</p> <pre><code>31 printf("table[%d] == %d\n", i, **(table+i)); (gdb) p *(table+i) $1 = (listnode *) 0x6000397b0 (gdb) p **(table+i) $2 = {data = 0x6000397d0 "New String A"} (gdb) p **(table+i)-&gt;data Cannot access memory at address 0x4e (gdb) </code></pre> <p>I'm really confused about this. Once a C pointer goes through more than one layer of dereferencing, I start getting cross-eyed. Anyone know what the proper syntax here might be?</p> <p>Thanks a million, -Pete</p> <p>PS - Apologies for the superlong post. I swear I struggled to keep it a manageable size...</p>
<p>The C <code>a-&gt;b</code> operator evaluates to <code>(*a).b</code>. So your line actually evaluates to something like <code>***(table+i).data</code>, which is obviously incorrect.</p> <p>It also may help to group with parentheses so it's clear whether the line evaluates to <code>(***(table+i)).data</code> or <code>***((table+i).data)</code>. Based on the error message you get, it's probably the latter.</p> <p>And then you can use the array syntax to clean it up more.</p> <p>All put together, you can simplify the line to <code>table[i]-&gt;data</code>.</p> <p>So why did your debugging session indicate otherwise? Because **(table+i) is the actual <em>struct</em> itself. To use <code>-&gt;</code>, you need a pointer to the struct.</p> <p>Also, a little tip. You casted your malloc() calls. Generally, programmers avoid this for several reasons. There are several posts on this, but one of the best ones can be found <a href="http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc">here</a>.</p>
Vanilla node.js response encoding - weird behaviour (heroku) <p>I'm developing my understanding of servers by writing a webdev framework using vanilla node.js. For the first time a situation arose where a french character was included in a <code>json</code> response from the server, and this character showed up as an unrecognized symbol (a question-mark within a diamond on chrome).</p> <p>The problem was the encoding, which was being specified here:</p> <pre><code>/* At this stage we have access to "response", which is an object of the following format: response = { data: 'A string which contains the data to send', encoding: 'The encoding type of the data, e.g. "text/html", "text/json"' } */ var encoding = response.encoding; var length = response.data.length; var data = response.data; res.writeHead(200, { 'Content-Type': encoding, 'Content-Length': length }); res.end(data, 'binary'); // Everything is encoded as binary </code></pre> <p>The problem was that everything sent by the server is encoded as binary, which ruins the ability to display certain characters. The fix seemed simple; include a boolean <code>binary</code> value in <code>response</code>, and adjust the 2nd parameter of <code>res.end</code> accordingly:</p> <pre><code>/* At this stage we have access to "response", which is an object of the following format: response = { data: 'A string which contains the data to send', encoding: 'The encoding type of the data, e.g. "text/html", "text/json"', binary: 'a boolean value determining the transfer encoding' } */ . . . var binary = response.binary; . . . res.end(data, binary ? 'binary' : 'utf8'); // Encode responses appropriately </code></pre> <p>Here is where I have produced some very, very strange behavior. This modification causes french characters to appear correctly, but occasionally <strong>causes the last character of a response to be omitted on the client-side!!!</strong></p> <p>This bug only happens once I host my application on heroku. Locally, the last character is never missing.</p> <p>I noticed this bug because certain responses (not all of them!) now break the <code>JSON.parse</code> call on the client-side, although they are only missing the final <code>}</code> character.</p> <p>I have a horrible band-aid solution right now, which <em>works</em>:</p> <pre><code>var length = response.data.length + 1; var data = response.data + ' '; </code></pre> <p>I am simply appending a space to every single response sent by the server. This actually causes all <code>text/html</code>, <code>text/css</code>, <code>text/json</code>, and <code>application/javascript</code> responses to work because they can tolerate the unnecessary whitespace, but I hate this solution and it will break other <code>Content-Type</code>s!</p> <p>My question is: can anyone give me some insight into this problem?</p>
<p>If you're going to explicitly set a <code>Content-Length</code>, you should always use <code>Buffer.byteLength()</code> on the body to calculate the length, since that method returns the <em>actual</em> number of bytes in the string and not the number of <em>characters</em> like the string <code>.length</code> property will return.</p>
Speed up Google Web App Spreadsheet loading <p>I'm working on a GAS Web App that reads a spreadsheet (it is not associated with the spreadsheet, and can't be for unrelated reasons).</p> <p>I load in the sheet, or a range thereof, like this:</p> <pre><code>var ss = SpreadsheetApp.openById(ssId); dataSheet = ss.getSheetByName('Projects'); var data = dataSheet.getRange('A1:BL').getValues(); </code></pre> <p>I've done a lot of testing, and with my lightly-populated A1:BL5500 spreadsheet (with a fair number of cells filled with a few dozen characters of text), the load time takes around 6 seconds. I've tried named ranges and lots of things, but can't get it faster than that.</p> <p>What I really need is 1 column of the sheet, then I do a search to find the row I need, and then I need that row. But loading the 1 column takes nearly the same amount of time as loading the entire thing. Is there a better way to do this? The delay is problematic.</p> <p>Here's the timing breakdown:</p> <pre><code>SpreadsheetApp.openById(ssid) [0.174 seconds] Spreadsheet.getSheetByName([Projects]) [0 seconds] Sheet.getRange([A1:BL]) [0.387 seconds] Range.getValues() [6.483 seconds] </code></pre> <p>For comparison, here's loading just one column:</p> <pre><code>SpreadsheetApp.openById(ssid) [0.164 seconds] Spreadsheet.getSheetByName([Projects]) [0 seconds] Sheet.getRange([A1:A]) [0.336 seconds] Range.getValues() [5.887 seconds] </code></pre> <p>These are just single runs, the time differences aren't significant (they vary).</p>
<p>As I noted above, I found one answer that might be helpful to others. I created a second sheet ("ProjectIndex"), and set up two columns that merely pointed to the corresponding columns of interest in "Projects" (I'd originally said I was just searching one column, to keep it simpler: I'm actually searching two). I load that data, find the row of interest, and go back to "Projects" and load only the row I want. </p> <pre><code>var ss = SpreadsheetApp.openById(ssId); dataSheet = ss.getSheetByName('ProjectIndex'); var data = dataSheet.getRange('A1:B').getValues(); ... // search data and find row i var j = i+1; // account for zero-based array but 1-based row numbering var rc = 'A'+j+':BL'+j; // there are BL columns in Projects var record = ss.getSheetByName('Projects').getRange(rc).getValues(); </code></pre> <p>Time to load ProjectIndex:</p> <pre><code>SpreadsheetApp.openById(ssid) [0.153 seconds] Spreadsheet.getSheetByName([ProjectIndex]) [0 seconds] Sheet.getRange([A1:B]) [0.282 seconds] Range.getValues() [0.504 seconds] </code></pre> <p>Time to load one row of Projects:</p> <pre><code>Spreadsheet.getSheetByName([Projects]) [0 seconds] Sheet.getRange([A4785:BL4785]) [0.513 seconds] Range.getValues() [0.352 seconds] </code></pre> <p>I purposely illustrated with a row near the bottom of the file. It may be that I could load ProjectIndex asynchronously earlier, I don't know if that would further speed things up and I don't know how to do it anyway. Subsequent searches can in principle be fast, except for being uncertain about whether the data is up to date.</p>
What is the default text color for theme.appcompat.light? <p>The title says it all, looking for the default color value used in TextViews in theme.appcompat.light</p> <p>tried looking for it in Android studio by hitting ctrl on theme.appcompat.light but it brought me down a rabbit hole that I couldn't find the end of.</p>
<p>Looks like <code>theme.appcompat.light</code> goes all the way up to <code>Platform.AppCompat.Light</code></p> <p>By default I'm just going to assume you mean the primary color.</p> <p>Here's what it looks like:</p> <pre><code>&lt;style name="Platform.AppCompat.Light" parent="android:Theme.Light"&gt; &lt;item name="android:windowNoTitle"&gt;true&lt;/item&gt; ... &lt;!-- Text colors --&gt; &lt;item name="android:textColorPrimary"&gt;@color/abc_primary_text_material_light&lt;/item&gt; &lt;item name="android:textColorPrimaryInverse"&gt;@color/abc_primary_text_material_dark&lt;/item&gt; &lt;item name="android:textColorSecondary"&gt;@color/abc_secondary_text_material_light&lt;/item&gt; &lt;item name="android:textColorSecondaryInverse"&gt;@color/abc_secondary_text_material_dark&lt;/item&gt; &lt;item name="android:textColorTertiary"&gt;@color/abc_secondary_text_material_light&lt;/item&gt; &lt;item name="android:textColorTertiaryInverse"&gt;@color/abc_secondary_text_material_dark&lt;/item&gt; &lt;item name="android:textColorPrimaryDisableOnly"&gt;@color/abc_primary_text_disable_only_material_light&lt;/item&gt; &lt;item name="android:textColorPrimaryInverseDisableOnly"&gt;@color/abc_primary_text_disable_only_material_dark&lt;/item&gt; &lt;item name="android:textColorHint"&gt;@color/hint_foreground_material_light&lt;/item&gt; &lt;item name="android:textColorHintInverse"&gt;@color/hint_foreground_material_dark&lt;/item&gt; &lt;item name="android:textColorHighlight"&gt;@color/highlighted_text_material_light&lt;/item&gt; &lt;item name="android:textColorLink"&gt;?attr/colorAccent&lt;/item&gt; ... &lt;/style&gt; </code></pre> <p>Inside you'll see <code>abc_primary_text_material_light</code>:</p> <pre><code>&lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:state_enabled="false" android:color="@color/primary_text_disabled_material_light"/&gt; &lt;item android:color="@color/primary_text_default_material_light"/&gt; &lt;/selector&gt; </code></pre> <p>Which last but not least defines it's color as:</p> <pre><code>&lt;color name="primary_text_default_material_light"&gt;#de000000&lt;/color&gt; </code></pre>
C# async/await. call and forget, no waiting. And long running process <p>I am trying to take advantage of new (relatively) C# async/await Task based feature. I went through several examples and I got the general idea of advantages. Here are two topics I would be very grateful if someone shares with me/us some clues or piece of code on:</p> <ol> <li><p>I use to write some logging/tracking info during the "process" dozens of times (like write to a TXT file log or dump some statuses into db, etc.) I feel like it will be very efficient to do those calls asynchronously (call and forget, no waiting). But what I learned is that each async task HAS to have an await, to be truly asynchronous. So, what is the solution to calling the same method (with different parameter value, like message...) several times during the "main method/function" and do not wait for each call as "await"?</p></li> <li><p>I have a pretty complicated [processA()] (class.method) which is called within a loop in the "main" class in windows service to process a "next doc" (thousands of times) (long running process). I would like to put this [processA()] in a Task and use 4-8 tasks in parallel to call the [processA()].</p></li> </ol> <p>Any clues, useful links, or code sample will be truly appreciated. Thanks in advance.</p>
<blockquote> <p>I feel like it will be very efficient to do those calls asynchronously (call and forget, no waiting).</p> </blockquote> <p>The problem with fire and forget is that you have no idea whether the operation failed. This is not acceptable for most code.</p> <p>Many logging frameworks synchronously write to an in-memory store which is then periodically flushed to disk/db. This gives a good tradeoff between speed and log reliability.</p> <blockquote> <p>I would like to put this [processA()] in a Task and use 4-8 tasks in parallel to call the [processA()].</p> </blockquote> <p>Sounds like you're confusing asynchrony with parallel processing. If you want to use parallel processing, then use <code>Parallel.ForEach</code> or something like that; if you want to use asynchrony, then the first step is to make <code>processA</code> asynchronous, and then use <code>await Task.WhenAll</code> for all the tasks to complete.</p>
Reading array of string in C <p>I need to read an array of n strings from 2 letters in each (e.g. n = 3, need to read something near "ab bf cs"). I use this code and get segmentation fault:</p> <pre><code>int n; scanf("%d", &amp;n); char array[n][2]; char *tmp; for (int i = 0; i &lt; n; i++) { scanf("%s", &amp;tmp); strcpy(array[i], tmp); } </code></pre> <p>Please help me to fix it!</p>
<p><strong>Problem 1</strong></p> <p>To store a string of length 2, you need a <code>char</code> array of size 3. Use:</p> <pre><code>char array[n][3]; </code></pre> <p><strong>Problem 2</strong></p> <p>You are using <code>&amp;tmp</code> in the call to <code>scanf</code>. That is wrong on two accounts.</p> <ol> <li><p>The type is not appropriate. Type of <code>&amp;tmp</code> is <code>char**</code>. <code>scanf</code> needs a <code>char*</code> with the <code>%s</code> format specifier.</p></li> <li><p><code>&amp;tmp</code> cannot hold a string.</p></li> </ol> <p>You could use </p> <pre><code>scanf("%s", tmp); </code></pre> <p>That will be OK from type point of view but it won't ok from run time point of view since <code>tmp</code> does not point to anything valid.</p> <p>You can do away with <code>tmp</code> altogether and use:</p> <pre><code>scanf("%s", array[i]); </code></pre> <hr> <p>That entire block of code can be:</p> <pre><code>int n; scanf("%d", &amp;n); char array[n][3]; for (int i = 0; i &lt; n; i++) { // Make sure you don't read more than 2 chars. scanf("%2s", array[i]); } </code></pre>
update using a subquery causing error <p>What is wrong with below query, I'm trying to update a count in daily table using a weekly one , I've to update a count per item in daily table using the count for same item in weekly</p> <pre><code> select a.ik , a.date , d.count from Table1 a , Table2 b , ( select count from Table2 b where b.ik = a.ik and wk in ( select wk from calendar_table c,Table1 where c.calendar_date = Table1.date)) as d </code></pre> <p>table 1</p> <pre><code> ik, , date 133;0;"002996";"2014-06-26" 11;0;"003406";"2014-06-22" </code></pre> <p>table 2</p> <pre><code> ik, wk , count 368;201605;0 377;201438;0 </code></pre> <p>calendar_table</p> <pre><code> date, wk "2013-08-15";201329 "2019-09-05";201932 </code></pre>
<pre><code>select a.ik , a.date , b.count from Table1 a join Table2 b on b.ik=a.ik join Calendar_table c on c.calendar_date=a.date </code></pre>
react native embed video not working <p>It's a known issue for react native webview doesn't handle video playback well. </p> <p>I found that in this discussion <a href="https://github.com/facebook/react-native/issues/6405" rel="nofollow">https://github.com/facebook/react-native/issues/6405</a> and <a href="https://github.com/facebook/react-native/pull/6603" rel="nofollow">https://github.com/facebook/react-native/pull/6603</a> the WebChromeClient() has been implemented in WebView. But I still can't to make it work. All I get is black screen. I have try with html source as well as uri, neither of them works. </p> <p>I also found this <a href="https://github.com/lucasferreira/react-native-webview-android" rel="nofollow">https://github.com/lucasferreira/react-native-webview-android</a> which could possible can solve this problem. But the drawback of this module is that it doesn't support fullscreen playback. This is not really what I want. </p> <p>I have no Java background,I really don't know how to make it work. Is there other method to embed video in RN? The video source is not limited to youtube, but other streaming service like vimeo and dailymotion. </p>
<p>You should try using <a href="https://github.com/react-native-community/react-native-video" rel="nofollow"><code>react-native-video</code></a> or other libraries that you might find <a href="https://js.coach/react-native/react-native-media-player?search=video" rel="nofollow">here</a>.</p>
Accessing Groovy properties or methods <p>I have a simple question. If I have an <code>HttpResponseDecorator</code>(<code>groovyx.net.http.HttpResponseDecorator</code>) how come I can do <code>response.status</code> to get the response code? When I'm debugging I don't see this property available in the object. I looked up the API and I don't see the status property available. How is <code>response.status</code> working? Am I missing a language feature?</p>
<p>The Groovy property is a combination of a private field and getters/setters. Groovy will then generate the getters/setters appropriately. </p> <p>For example:</p> <pre><code>class Person { String name int age } </code></pre> <p>Properties are accessed by name and will call the getter or setter transparently. I would recommend read more in the <a href="http://groovy-lang.org/objectorientation.html#_fields_and_properties" rel="nofollow">Groovy documentation for field and properties</a>.</p>
Excel VBA: Advanced Filtering Blanks Not Working <p>I have a userform that uses a checkbox to filter out blanks for a certain column. The range to be filtered is Sheet 1 A1:C10, and the criteria range is Sheet 2 A1:C2.</p> <p>If checked: Don't filter Column C If unchecked: Filter out blanks on Column C</p> <p>I have looked around and found that the operator to filter blanks on an advanced filter is "=". Therefore, when I process the filter when I press a button on the userform, I set Sheet 2 C2 to "="</p> <pre><code>If Checkbox1.Value Then Sheets(2).Range("C2").Value = "" Else Sheets(2).Range("C2").Value = "=" End If Sheets(1).Range("A1:C10").AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:= _ Sheets(2).Range("A1:C2"), Unique:=False </code></pre> <p>When I process this, all entries disappear, even blanks. The same is true if I use:</p> <pre><code>Else Sheets(2).Range("C2").Value = "&lt;&gt;" </code></pre> <p>This should show non-blanks, but it hides all rows.</p> <p>Here's the kicker; to troubleshoot, I recorded a macro of me auto-filtering blanks, and it gave me this:</p> <pre><code>ActiveSheet.Range("$A$1:$C$2").AutoFilter Field:=3, Criteria1:="=" </code></pre> <p>So, it seems that filtering "=" is correct, but it just doesn't want to work with me.</p> <hr> <p><strong>Side note:</strong> just for kicks, I thought that the criteria cell needed to show ="", which means that the formula would read ="=""""", which means that the VBA would read:</p> <pre><code>Else Sheets(2).Range("C2").Value = "=""=""""""""""" </code></pre> <p>This also does not work.</p> <hr> <p><strong>Edit:</strong> @Scott, I have the following four lines. None of which seem to work. The linked page shows an example to remove blanks, not exclusively show them. Therefore I tried =0 in addition to >0.</p> <pre><code>Else Sheets(2).Range("C2").Value = "=LEN(Sheet1!C2)=0" Else Sheets(2).Range("C2").Value = "=""=LEN(Sheet1!C2)=0""" Else Sheets(2).Range("C2").Value = "=LEN(Sheet1!C2)&gt;0" Else Sheets(2).Range("C2").Value = "=""=LEN(Sheet1!C2)&gt;0""" </code></pre>
<p>Okay we missed a step.</p> <blockquote> <p><strong><em>C1 on sheet2 needs to be empty.</em></strong></p> </blockquote> <p>The formula will take care of the filter part.</p> <p>Then the code is:</p> <pre><code>If Checkbox1.Value Then Sheets(2).Range("C2").Value = "" Else Sheets(2).Range("C2").Formula = "=LEN(Sheet1!C2)=0" End If Sheets(1).Range("A1:C10").AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:= _ Sheets(2).Range("A1:C2"), Unique:=False </code></pre>
Azure - SqlBulkCopy throwing a timeout expired exception <p>I'm using an azure sql database (v12) on a vm. I have two different databases instances - one for staging and one for production. I'm trying to grab the data off of staging and insert it into production with the click of a button. This code works successfully 'sometimes' meaning randomly it will be successful. Otherwise I'm getting back an error of:</p> <blockquote> <p>BULK COPY Commit Exception Type: {0}System.Data.SqlClient.SqlException BULK COPY Message: {0}Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. This failure occurred while attempting to connect to the routing destination. The duration spent while attempting to connect to the original server was - [Pre-Login] initialization=1; handshake=17; [Login] initialization=0; authentication=0; [Post-Login] complete=0;</p> </blockquote> <p>Here is the code that I'm using to accomplish this task, maybe there's a flaw that I'm not seeing. By dump the StringBuilder out I can see that the SELECT query works and the DELETE query works but the error is thrown when I attempt to copy the data using SqlBulkCopy. Any help would be greatly appreciated. I've gone through a bunch of the MSDN docs already with no luck -> adding longer CommandTimeouts, adding a longer BulkCopyTimeout, and re-configuring ports on my firewall. Still no luck.</p> <p>Resources I've used: <a href="https://social.msdn.microsoft.com/Forums/en-US/1467d64f-69ae-4c1f-91a2-349fc5d514ae/sqlbulkcopy-fails-with-timeout-expired-error?forum=adodotnetdataproviders" rel="nofollow">https://social.msdn.microsoft.com/Forums/en-US/1467d64f-69ae-4c1f-91a2-349fc5d514ae/sqlbulkcopy-fails-with-timeout-expired-error?forum=adodotnetdataproviders</a></p> <p><a href="https://azure.microsoft.com/nb-no/documentation/articles/sql-database-develop-direct-route-ports-adonet-v12/" rel="nofollow">https://azure.microsoft.com/nb-no/documentation/articles/sql-database-develop-direct-route-ports-adonet-v12/</a></p> <p><a href="http://stackoverflow.com/questions/4535536/timeout-expired-with-sqlbulkcopy">Timeout expired with SqlBulkCopy</a></p> <pre><code>public static object SyncData() { StringBuilder sb = new StringBuilder(); sb.AppendLine("Internal Connection..."); string internalConnectionString = GetConnectionString("ConnectionString"); using (SqlConnection internalConnection = new SqlConnection(internalConnectionString)) { internalConnection.Open(); SqlCommand selectCommand = internalConnection.CreateCommand(); selectCommand.CommandTimeout = 180; try { selectCommand.CommandText = "SELECT * FROM dbo.test"; SqlDataReader reader = selectCommand.ExecuteReader(); sb.AppendLine("External Connection..."); string externalConnectionString = GetConnectionString("ExternalConnectionString"); using (SqlConnection externalConnection = new SqlConnection(externalConnectionString)) { externalConnection.Open(); SqlCommand CRUDCommand = externalConnection.CreateCommand(); CRUDCommand.CommandTimeout = 180; SqlTransaction transaction = externalConnection.BeginTransaction("test"); CRUDCommand.Connection = externalConnection; CRUDCommand.Transaction = transaction; try { CRUDCommand.CommandText = "DELETE FROM dbo.test"; sb.AppendLine("DELETE: Number of rows affected = " + CRUDCommand.ExecuteNonQuery()); using (SqlBulkCopy bulkCopy = new SqlBulkCopy(externalConnection, SqlBulkCopyOptions.KeepIdentity, transaction)) { try { bulkCopy.DestinationTableName = "dbo.test"; bulkCopy.BatchSize = 100; bulkCopy.BulkCopyTimeout = 180; bulkCopy.WriteToServer(reader); sb.AppendLine("Table data copied successfully"); transaction.Commit(); sb.AppendLine("Transaction committed."); } catch (Exception ex) { sb.AppendLine("BULK COPY Commit Exception Type: {0}" + ex.GetType()); sb.AppendLine(" BULK COPY Message: {0}" + ex.Message); try { transaction.Rollback(); } catch (Exception ex2) { sb.AppendLine("Rollback Exception Type: {0}" + ex2.GetType()); sb.AppendLine(" Message: {0}" + ex2.Message); } } finally { reader.Close(); } } } catch (Exception ex) { sb.AppendLine("Commit Exception Type: {0}" + ex.GetType()); sb.AppendLine(" Message: {0}" + ex.Message); try { transaction.Rollback(); } catch (Exception ex2) { sb.AppendLine("Rollback Exception Type: {0}" + ex2.GetType()); sb.AppendLine(" Message: {0}" + ex2.Message); } } } } catch (Exception ex) { sb.AppendLine("Commit Exception Type: {0}" + ex.GetType()); sb.AppendLine(" Message: {0}" + ex.Message); } } return sb.ToString(); } </code></pre>
<p>When creating your SqlBulkCopy instance, you're passing the connection string <code>externalConnectionString</code> and thus opening a new connection. That may be causing a deadlock issue with both connections trying to modify the same table.</p> <p>Have you tried passing your existing connection <code>externalConnection</code> to the SqlBulkCopy constructor instead of the connection string?</p>
Unable to write to txt file in php <p>I'm trying to simply overwrite a txt file with a number entered in a text box in PHP. Both the PHP and text file are in the html directory of my apache2 server. Every time it executes it just displays the die() string. I also tried using fwrite() with the same results. Any help would be much appreciated. </p> <pre><code>&lt;HTML&gt; &lt;TITLE&gt;Home Automation Interface&lt;/TITLE&gt; &lt;BODY&gt; &lt;H1&gt;Air Conditioning Power(Relay 1)&lt;/H1&gt; &lt;H2&gt;Turn AC On/Off&lt;/H2&gt; &lt;H3&gt; &lt;p&gt; &lt;form action="relayToggle.php" method="get"&gt; &lt;input type="submit" value="AC Power"&gt; &lt;/form&gt; &lt;/p&gt; &lt;form method= "post" action = "homeInter.php"&gt; &lt;p&gt; &lt;label for="acTemp"&gt;AC temperature (F):&lt;/label&gt;&lt;br/&gt; &lt;input type="text" id="temp" name="temp"&gt; &lt;/p&gt; &lt;button type="submit" name="submit" value="send"&gt;Change Temperature&lt;/button&gt; &lt;/form&gt; &lt;p&gt;&lt;strong&gt; &lt;?php $temp= $_POST['temp']; echo $temp; file_put_contents("/var/www/html/temp.txt", (string)$temp) or die("Unable to open file!"); ?&gt; } } ?&gt; &lt;/strong&gt; &lt;/p&gt; &lt;/H3&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre>
<p>Wrap your PHP code Ina valid checker to see if form was submitted</p> <p>Like this:</p> <pre><code>if ($_POST): //All functions go here endfor; </code></pre> <p>If the file is in the same directory as your PHP file just change the directory to the file name.file Extension in your <em>file_put_content()</em> </p>
Symfony Serializer doesn't deserialize into objects in different namespace: 'no supporting normalizer found' <p>I'm trying to deserialize json into an object using the packages symfony/serializer and symfony/property-access through composer. It works when the class I'm deserializing into is in the same file, but not when it's somewhere else (not even a different file in the same namespace). I have the following code:</p> <pre><code>&lt;?php // Somewhere/Foo.php namespace Somewhere; class Foo { private $foo; public function getFoo() { return $this-&gt;foo; } public function setFoo($foo) { $this-&gt;foo = $foo; } } </code></pre> <p>And:</p> <pre><code>&lt;?php // file tests/Test.php namespace tests; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Encoder\XmlEncoder; use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Serializer; use Somewhere\Foo; class Foo2 { private $foo; public function getFoo() { return $this-&gt;foo; } public function setFoo($foo) { $this-&gt;foo = $foo; } } class Test extends \PHPUnit_Framework_TestCase { public function testFoo() { $encoders = array(new XmlEncoder(), new JsonEncoder()); $normalizers = array(new ObjectNormalizer(), new GetSetMethodNormalizer()); $serializer = new Serializer($normalizers, $encoders); $payload = '{"foo": {"bar": "baz"}}'; $obj = $serializer-&gt;deserialize($payload, Foo::class, 'json'); $this-&gt;assertInstanceOf(Foo::class, $obj); } public function testFoo2() { $encoders = array(new XmlEncoder(), new JsonEncoder()); $normalizers = array(new ObjectNormalizer(), new GetSetMethodNormalizer()); $serializer = new Serializer($normalizers, $encoders); $payload = '{"foo": {"bar": "baz"}}'; $obj = $serializer-&gt;deserialize($payload, Foo2::class, 'json'); $this-&gt;assertInstanceOf(Foo2::class, $obj); } } </code></pre> <p>The test using the local class (<code>Foo2</code>) works fine, but the one using the class in a different namespace (<code>\Somewhere\Foo</code>) shows me this error: <code>Symfony\Component\Serializer\Exception\UnexpectedValueException: Could not denormalize object of type Somewhere\Foo, no supporting normalizer found</code>.</p> <p>I've tried using <code>\Somewhere\Foo::class</code>, <code>'Foo'</code> and <code>'\Somewhere\Foo'</code> instead of Foo::class too without any luck.</p> <p>Similar Questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/31831133/serializing-and-deserializing-in-symfony">Serializing and Deserializing in Symfony</a> marks one answer which uses strings as correct but not really, if you read the comments you'll see it didn't really solved the question.</li> <li><a href="http://stackoverflow.com/questions/39576832/could-not-denormalize-object-of-type-no-supporting-normalizer-found-symfony-2">Could not denormalize object of type, no supporting normalizer found. Symfony 2.8</a> In the comments the OP says using <code>ClassName::class</code> worked, but this doesn't work for me.</li> <li><a href="http://stackoverflow.com/questions/19953802/problems-try-encode-entity-to-json">Problems try encode entity to json</a> The answer was to stop using <code>symfony/serializer</code> and use <code>jms/serializer</code> instead. Is it really not possible with Symfony's serializer?</li> </ul> <p>Thanks for the help</p>
<p>The error occurs because <code>Foo</code> class doesn't exists in this context, you've probably forgotten to include this file <code>Somewhere/Foo.php</code> to autoload.</p> <p>In your sample this should work!</p> <pre><code>&lt;?php // file tests/Test.php namespace tests; include 'Somewhere/Foo.php'; //... </code></pre> <p>Some editors as PHPStorm are able to auto-import the <code>Foo</code> class if it's in the same directory without show any error.</p>
System.Data.SqlClient.SqlException Error while clicking button1 <p>A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll</p> <p>Additional information: Invalid object name 'Login'.</p> <p>Here's The Code :</p> <pre><code>public partial class Form1 : MetroFramework.Forms.MetroForm { public Form1() { InitializeComponent(); } SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Igurek\Documents\Database.mdf;Integrated Security=True;Connect Timeout=30"); private void metroButton1_Click(object sender, EventArgs e) { this.Close(); } private void metroButton2_Click(object sender, EventArgs e) { SqlDataAdapter sdf = new SqlDataAdapter("Select Count(*) From Login where Username='" + metroTextBox1.Text + "' and Password='" + metroTextBox2.Text + "'", con); DataTable dt = new DataTable(); sdf.Fill(dt); // &lt;--------- Here's the exception if (dt.Rows.Count == 1) { Form1 f1 = new Form1(); f1.Show(); } else { MessageBox.Show("Sprawdz Nazwe i Haslo"); } } } </code></pre> <p>Screenshot:</p> <p><img src="http://i.stack.imgur.com/WJQwE.png" alt="image description"></p>
<p>The message is pretty clear: you don't have an object (table, view) in your database named <code>Login</code>. Your query is attempting to select from that object.</p> <pre><code>Select Count(*) From Login where... </code></pre> <p>The bigger and more important issue here is that you're opening yourself up to a SQL injection attack because you're concatenating strings together to create the query. You should use parameters instead of doing that.</p> <pre><code>SqlDataAdapter sdf = new SqlDataAdapter( "Select Count(*) From Login where Username=@UserName and Password=@Password", con); command.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = metroTextBox1.Text; command.Parameters.Add("@Password", SqlDbType.NVarChar).Value = metroTextBox2.Text; </code></pre>
Center logo images within row on shopify page, with css / html? <p>I am making a grid of logos for a client's site. I am wondering how to make them centered within the grids in rows and columns. I have for css: </p> <pre><code>.center-block { display: block; margin-top: auto; margin-bottom: auto; margin-left: auto; margin-right: auto; } </code></pre> <p>let me know if any solutions exist.</p>
<p>If you want the logo centered horizontally you can do something like this and replace .center-me with your class for the element you want centered.</p> <p>if it's a block element do this. </p> <pre><code>.center-me { margin: 0 auto; } </code></pre> <p>if it's inline (text or links) do this</p> <pre><code>.center-me { text-align: center; } </code></pre>
Setup virtual path with .NET Core Kestrel and Node <p>Is it possible to setup a .NET Core project on localhost:5000 and another Node project which runs next to the previous one, but at localhost:5000/api?</p> <p>I have done this with .NET 4.6 and IISExpress, but a lot have changed with Kestrel server and I don't understand how to do it.</p> <p><strong>An image of how I did earlier</strong> <a href="http://i.stack.imgur.com/BleMJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/BleMJ.png" alt="enter image description here"></a> Adding the path then clicking Create Virtual Directory.</p> <p><a href="http://i.stack.imgur.com/frLC9.png" rel="nofollow"><img src="http://i.stack.imgur.com/frLC9.png" alt="enter image description here"></a></p>
<p>I don't think this is possible with kestrel alone. Check out the article explaining the architecture of developing with kestrel versus traditional IIS</p> <p><a href="https://weblog.west-wind.com/posts/2016/Jun/06/Publishing-and-Running-ASPNET-Core-Applications-with-IIS" rel="nofollow">https://weblog.west-wind.com/posts/2016/Jun/06/Publishing-and-Running-ASPNET-Core-Applications-with-IIS</a></p>
Pandas, convert aggregated dataframe to list of tuples <p>I am trying to obtain a <code>list</code> of <code>tuples</code> from a panda's <code>DataFrame</code>. I'm more used to other APIs like <code>apache-spark</code> where <code>DataFrame</code>s have a method called <code>collect</code>, however I searched a bit and found <a href="https://stackoverflow.com/questions/9758450/pandas-convert-dataframe-to-array-of-tuples">this approach</a>. But the result isn't what I expected, I assume it is because the <code>DataFrame</code> has aggregated data. Is there any simple way to do this?</p> <p>Let me show my problem:</p> <pre><code>print(df) #date user Cost #2016-10-01 xxxx 0.598111 # yyyy 0.598150 # zzzz 13.537223 #2016-10-02 xxxx 0.624247 # yyyy 0.624302 # zzzz 14.651441 print(df.values) #[[ 0.59811124] # [ 0.59814985] # [ 13.53722286] # [ 0.62424731] # [ 0.62430216] # [ 14.65144134]] #I was expecting something like this: [("2016-10-01", "xxxx", 0.598111), ("2016-10-01", "yyyy", 0.598150), ("2016-10-01", "zzzz", 13.537223) ("2016-10-02", "xxxx", 0.624247), ("2016-10-02", "yyyy", 0.624302), ("2016-10-02", "zzzz", 14.651441)] </code></pre> <hr> <h3>Edit</h3> <p>I tried what was suggested by @Dervin, but the result was unsatisfactory.</p> <pre><code>collected = [for tuple(x) in df.values] collected [(0.59811124000000004,), (0.59814985000000032,), (13.53722285999994,), (0.62424731000000044,), (0.62430216000000027,), (14.651441339999931,), (0.62414758000000026,), (0.62423407000000042,), (14.655454959999938,)] </code></pre>
<p>That's a hierarchical index you got there, so first you can do what is in this <a href="http://stackoverflow.com/questions/10373660/converting-a-pandas-groupby-object-to-dataframe">SO question</a>, and then something like <code>[tuple(x) for x in df1.to_records(index=False)]</code>. For example:</p> <pre><code> df1 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd']) In [12]: df1 Out[12]: a b c d 0 0.076626 -0.761338 0.150755 -0.428466 1 0.956445 0.769947 -1.433933 1.034086 2 -0.211886 -1.324807 -0.736709 -0.767971 ... In [13]: [tuple(x) for x in df1.to_records(index=False)] Out[13]: [(0.076625682946709128, -0.76133754774190276, 0.15075466312259322, -0.42846644471544015), (0.95644517961731257, 0.76994677126920497, -1.4339326896803839, 1.0340857719122247), (-0.21188555188408928, -1.3248066626301633, -0.73670886051415208, -0.76797061516159393), ... </code></pre>
Python generating a lookup table of lambda expressions <p>I'm building a game and in order to make it work, I need to generate a list of "pre-built" or "ready to call" expressions. I'm trying to do this with lambda expressions, but am running into an issue generating the lookup table. The code I have is similar to the following:</p> <pre><code>import inspect def test(*args): string = "Test Function: " for i in args: string += str(i) + " " print(string) funct_list = [] # The problem is in this for loop for i in range(20): funct_list.append(lambda: test(i, "Hello World")) for i in funct_list: print(inspect.getsource(i)) </code></pre> <p>The output I get is:</p> <pre><code>funct_list.append(lambda: test(i, "Hello World")) funct_list.append(lambda: test(i, "Hello World")) funct_list.append(lambda: test(i, "Hello World")) funct_list.append(lambda: test(i, "Hello World")) ... </code></pre> <p>and I need it to go:</p> <pre><code>funct_list.append(lambda: test(1, "Hello World")) funct_list.append(lambda: test(2, "Hello World")) funct_list.append(lambda: test(3, "Hello World")) funct_list.append(lambda: test(4, "Hello World")) ... </code></pre> <p>I tried both of the following and neither work</p> <pre><code>for i in range(20): funct_list.append(lambda: test(i, "Hello World")) for i in range(20): x = (i, "Hello World") funct_list.append(lambda: test(*x)) </code></pre> <p>My question is how do you generate lists of lambda expressions with some of the variables inside the lambda expression already set.</p>
<p>As others have mentioned, Python's closures are <em>late binding</em>, which means that variables from an outside scope referenced in a closure (in other words, the variables <em>closed over</em>) are looked up at the moment the closure is called and <em>not</em> at the time of definition.</p> <p>In your example, the closure in question is formed when your lambda references the variable <code>i</code> from the outside scope. However, when your lambda is called later on, the loop has already finished and left the variable <code>i</code> with the value 19.</p> <p>An easy but not particularly elegant fix is to use a default argument for the lambda:</p> <pre><code>for i in range(20): funct_list.append(lambda x=i: test(x, "Hello World")) </code></pre> <p>Unlike closure variables, default arguments are bound early and therefore achieve the desired effect of capturing the value of the variable <code>i</code> at the time of lambda definition.</p> <p>A better way is use <code>functools.partial</code> which allows you to partially apply some arguments of the function, "fixing" them to a certain value:</p> <pre><code>from functools import partial for i in range(20): funct_list.append(partial(lambda x: test(x, "Hello World"), i)) </code></pre>
Ungroup Sheets from an array in VBA <p>I've been trying to get an easy printout (in PDF using a single button) of one sheet with only active range and one chart located in another sheet. I've got everything working, except after I print, both sheets are grouped together and I can't edit my chart. </p> <p>I'm trying to make this foolproof and easy for coworkers during real time operations. Right now I can right-click and select 'Ungroup sheets' to fix it, but I hate to have to do that each time (or explain that it needs to be done).</p> <p>I tried to select a sheet, a different sheet, only one sheet etc. I can't figure out how to get VBA to ungroup the sheets at the end. Any ideas?</p> <pre><code>Sub CustomPrint() 'if statement to ask for file path If Dir(Environ("commonprogramfiles") &amp; "\Microsoft Shared\OFFICE" _ &amp; Format(Val(Application.Version), "00") &amp; "\EXP_PDF.DLL") &lt;&gt; "" Then If FixedFilePathName = "" Then 'Open the GetSaveAsFilename dialog to enter a file name for the PDF file. FileFormatstr = "PDF Files (*.pdf), *.pdf" fname = Application.GetSaveAsFilename("", filefilter:=FileFormatstr, _ Title:="Create PDF") 'If you cancel this dialog, exit the function. If fname = False Then Exit Sub Else fname = FixedFilePathName End If 'Dynamic reference to RT drilling data Dim LastRow As Long Dim LastColumn As Long Dim StartCell As Range Dim sht As Worksheet Set sht = Worksheets("rt drilling data") Set StartCell = Range("A1") 'Refresh UsedRange Worksheets("rt drilling data").UsedRange 'Find Last Row LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 'Select Range sht.Range("A1:K" &amp; LastRow).Select Sheets("Chart Update").Activate ActiveSheet.ChartObjects(1).Select ThisWorkbook.Sheets(Array("chart update", "RT drilling data")).Select ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=fname, IgnorePrintAreas:=False 'If the export is successful, return the file name. If Dir(fname) &lt;&gt; "" Then RDB_Create_PDF = fname End If If OverwriteIfFileExist = False Then If Dir(fname) &lt;&gt; "" Then Exit Sub End If On Error GoTo 0 Worksheets("ws model updates").Select End Sub </code></pre>
<p><code>If Dir(fname) &lt;&gt; "" Then Exit Sub</code> will bypass <code>Worksheets("ws model updates").Select</code></p> <pre><code>If OverwriteIfFileExist = False Then If Dir(fname) &lt;&gt; "" Then Worksheets("ws model updates").Select Exit Sub End If End If </code></pre>
How to check foreign table permissions on Postgres <p>does anybody know how to check user permissions for a foreign table on Postgres?</p> <p>I've tried <code>\dE</code> and <code>\det</code>, but no luck.</p> <p>I just want to know who can select, insert, update and delete from a foreign table.</p>
<p><code>\dp</code> is a <a href="https://www.postgresql.org/docs/current/static/app-psql.html" rel="nofollow"><strong>psql</strong></a> meta-command which lists tables with their associated access privileges. I believe <code>\z</code> is doing the same thing. It also lists privileges for accessing views and sequences.</p>
How to pull the non delimited date and time out of a string <p>I need to pull the date and time out of this string: <code>some_report_20161005_1530.xml</code> so I can reformat it to something more work-with-able. The date and time will change from file to file, but will always stay in this format: <code>some_report_{year}{month}{day}_{24hr time}.xml</code></p> <pre><code>$test = 'some_report_20161005_1530.xml'; preg_match('(\d{4})(\d{2})(\d{2})_(\d{4})', $test, $test_matches); print_r( $test_matches ); </code></pre> <p>What would be the best way to accomplish this?</p> <p>(Forgive my ignorance or misuse of these functions. I am by no means an expert) </p>
<p>If the <code>some_report</code> doesn't contain digits, the date and time parts are already in a good order to work in the DateTime constructor, so you can extract them with a simpler regex.</p> <pre><code>$date_time = new DateTime(preg_replace("/[^0-9]/", "", $your_string)); </code></pre>
RecyclerView In card View with Header <p>I want show a list of football games in my application with date time header.</p> <p>In my case I want to show games in date category in a card view and set a header that shown date but out side of card view.</p> <p>By adding card view as my RecyclerView parent, date title shown in CardView. and when I adding CardView as my ViewType's parent each item shown in a card.</p> <p>How can i create a list like below <a href="http://i.stack.imgur.com/iODk2.png" rel="nofollow"><img src="http://i.stack.imgur.com/iODk2.png" alt="picture"></a></p>
<p>You can use the library <a href="https://github.com/luizgrp/SectionedRecyclerViewAdapter" rel="nofollow">SectionedRecyclerViewAdapter</a> to group your data into sections.</p> <p>First create a Section class:</p> <pre><code>class MySection extends StatelessSection { String title; List&lt;String&gt; list; public MySection(String title, List&lt;String&gt; list) { // call constructor with layout resources for this Section header, footer and items super(R.layout.section_header, R.layout.section_item); this.title = title; this.list = list; } @Override public int getContentItemsTotal() { return list.size(); // number of items of this section } @Override public RecyclerView.ViewHolder getItemViewHolder(View view) { // return a custom instance of ViewHolder for the items of this section return new MyItemViewHolder(view); } @Override public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) { MyItemViewHolder itemHolder = (MyItemViewHolder) holder; // bind your view here itemHolder.tvItem.setText(list.get(position)); } @Override public RecyclerView.ViewHolder getHeaderViewHolder(View view) { return new SimpleHeaderViewHolder(view); } @Override public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) { MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder; // bind your header view here headerHolder.tvItem.setText(title); } } </code></pre> <p>Then you set up the RecyclerView with your Sections:</p> <pre><code>// Create an instance of SectionedRecyclerViewAdapter SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter(); // Add your Sections to the adapter sectionAdapter.addSection(new MySection("Indonesia Super League", firstDataList)); sectionAdapter.addSection(new MySection("Regionalliga West", secondDataList)); sectionAdapter.addSection(new MySection("Club Friendly Games", thirdDataList)); // Set up your RecyclerView with the SectionedRecyclerViewAdapter RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setAdapter(sectionAdapter); </code></pre>
Swift 3.0 error with C-style for loop <p>I converted my project to Swift 3.0 and I get this error at the <code>for</code> line. Please see the error image below. After I converted it gave me a C-style error.</p> <pre><code>func removeButton(_ aButton: UIButton) { var iteration = 0 var iteratingButton: UIButton? = nil for( ; iteration&lt;buttonsArray.count; iteration += 1) { iteratingButton = buttonsArray[iteration] if(iteratingButton == aButton) { break } else { iteratingButton = nil } } if(iteratingButton != nil) { buttonsArray.remove(at: iteration) iteratingButton!.removeTarget(self, action: #selector(SSRadioButtonsController.pressed(_:)), for: UIControlEvents.touchUpInside) if currentSelectedButton == iteratingButton { currentSelectedButton = nil } } } </code></pre> <p><img src="http://i.stack.imgur.com/bprAj.png" alt="Error image here"></p>
<p>It's a clear error, Swift 3 does NOT support the c-style <code>for</code> loop.</p> <p>Instead, you should:</p> <pre><code> for iteration in 0 ..&lt; buttonsArray.count { iteratingButton = buttonsArray[iteration] if(iteratingButton == aButton) { break } else { iteratingButton = nil } } </code></pre> <p>You should check <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html" rel="nofollow">Apple's Documentation</a>.</p>
Limiting integer width in python <p>I'm practicing python, I came across a situation where I wanted to limit the character width of a field but it wasn't working.(I hope I'm saying that right) I want to truncate the sum of 2 integers to 5 spaces. eg: the sum of 88888 + 22222 has 6 characters. Is it possible to limit it to 5?</p>
<p>You can easily truncate the value of these integers. Simply convert the result into a string and then use the Python index to select the first five characters:</p> <pre><code>&gt;&gt;&gt; str(88888 + 22222)[:5] '11111' </code></pre> <p>You can also convert this value back to an integer using <code>int()</code> if necessary.</p>
How and in what order do I combine printf formatting arguments for a single printed output consisting of Strings and doubles? <p>Good afternoon, </p> <p>Here are three lines of java code that I would like to combine into a single printf statement. The idea is to eventually have several columns of evenly spaced data expressed in computer scientific notation with 5 significant digits. I can't seem to combine the arguments in the right order. Also, when I try to format multiple columns by adding extra "%-#s" formats, I am being told that I have not included enough arguments, or funny stuff comes out. What am I doing wrong?</p> <pre><code>System.out.printf("%-3s", "a_"+k+" = "); System.out.printf("%6.3e\n", a_k[k]); System.out.printf("%6.3e\n", a1_k[k]); </code></pre> <p>I have tried the below in various orders and combinations to no avail, and can't understand the javadocs on how to implement this correctly:</p> <pre><code>System.out.printf("%-3s%5.4e%-10s%5.4e\n", "a_"+k+" = ", a_k[k], a1_k[k]); </code></pre> <p>Thanks!</p>
<blockquote> <p>when I try to format multiple columns by adding extra "%-#s" formats, I am being told that I have not included enough arguments</p> </blockquote> <p>It is expecting a string argument between <code>a_k[k]</code> and <code>a1_k[k]</code>. </p> <p>Here are the four formats I assume you were wanting. </p> <ol> <li><code>%-3s</code> -> <code>"a_" + k + "= "</code></li> <li><code>%5.4e</code> -> <code>a_k[k]</code></li> <li><code>%-10s</code> -> (whitespace)</li> <li><code>%5.4e</code> -> <code>a1_k[k]</code></li> </ol> <p>Therefore, just insert a <code>""</code> for position 3</p> <pre><code>System.out.printf("%-3s%5.4e%-10s%5.4e\n", "a_"+k+" = ", a_k[k], "", a1_k[k]); </code></pre> <p><a href="http://ideone.com/MduFlL" rel="nofollow">See example</a></p> <p>Or, to make this easier on the eyes</p> <pre><code>String akEq = "a_"+k+" = "; float col1 = a_k[k]; float col2 = a1_k[k]; System.out.printf("%-3s%5.4e%-10s%5.4e\n", akEq, col1, "", col2); </code></pre> <p>And, going further, put <code>"a_%d = "</code> into the format as well instead of using string concatenation</p> <pre><code>System.out.printf("a_%d = %5.4e%-10s%5.4e\n", k, col1, "", col2); </code></pre>