input
stringlengths
51
42.3k
output
stringlengths
18
55k
I need a regex that will return false if my value contains any letters <p>I need a <strong>regex</strong> that will return false if valueA contains any letters. I need letters rejected basically</p> <p><strong>Examples</strong>:</p> <p>1) test1 => reject 2) test => reject 3) 123 = > accept</p> <pre><code> this.validateLetters = (valueA): boolean =&gt; { const regex = /^[a-zA-Z]+$/; return regex.test(valueA); }; </code></pre> <p>I'm using javascript</p>
<p>The regex used is <code>/^[0-9]+$/</code></p> <p>You should replace <code>+</code> by <code>*</code> if an empty string is acceptable</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>console.log(/^[0-9]+$/.test("10.22")); console.log(/^[0-9]+$/.test(10.22)); console.log(/^[0-9]+$/.test('')); console.log(/^[0-9]+$/.test('test1')); console.log(/^[0-9]+$/.test('test')); console.log(/^[0-9]+$/.test('123')); console.log(/^[0-9]+$/.test('{}')); console.log(/^[0-9]+$/.test('//')); console.log(/^[0-9]+$/.test('()'));</code></pre> </div> </div> </p>
How is Rails.cache variable available across threads? <p>If i write a value into say <code>Rails.cache.write('foo', :bar)</code> inside a rails controller action, how is this available inside a rails console context run at the same time?</p>
<p>Since cache is simply a storage (of your choice), it does not matter, where you are accessing it from, controller, model, console - wherever the <code>Rails</code> is defined, <code>Rails.cache.fetch/read/write/etc</code> will work.</p>
Disable/Remove images and link from loading in HTML <p>How can I disable images and links from loading in HTML using a script.</p> <pre><code>&lt;div id="mailPreviewTarget" style="padding: 10px; overflow: auto;"&gt; Sample Text &lt;p&gt;&lt;/p&gt; &lt;img src="http://.../track/0/0.png"&gt; &lt;div&gt; &lt;a href="http://.../unsubscribe/0/0"&gt;Unsubscribe&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><a href="https://jsfiddle.net/ks8r3noa/2/" rel="nofollow">https://jsfiddle.net/ks8r3noa/2/</a></p>
<pre><code>&lt;script src="https://code.jquery.com/jquery-2.0.3.js"&gt; $(window).load(function(e){ e.preventDefault() $('img , a').remove(); }); &lt;/script&gt; </code></pre>
Python: decorator/wrapper for try/except statement <p>I have some blocks of code which need to be wrapped by function.</p> <pre><code>try: if config.DEVELOPMENT == True: # do_some_stuff except: logger.info("Config is not set for development") </code></pre> <p>Then I'll do again:</p> <pre><code>try: if config.DEVELOPMENT == True: # do_some_another_stuff except: logger.info("Config is not set for development") </code></pre> <p>So, how can I wrap this "do_some_stuff" and "do_some_another_stuff"?</p> <p>I'm trying to write function with contextmanager:</p> <pre><code>@contextmanager def try_dev_config(name): try: if name is not None: yield except Exception as e: print "not dev config" with try_dev_config("config.DEVELOPMENT"): # do_some_stuff </code></pre> <p>And I got an error:</p> <blockquote> <p>RuntimeError: generator didn't yield</p> </blockquote>
<p>You could pass in a function.</p> <pre><code>boolean = True def pass_this_in(): print("I just did some stuff") def the_try_except_bit(function): try: if boolean: function() except: print("Excepted") # Calling the above code the_try_except_bit(pass_this_in) </code></pre> <p>If you want to reduce the "pass_this_in" definition bit, then you can use <a href="http://www.secnetix.de/olli/Python/lambda_functions.hawk" rel="nofollow">lambda function definitions</a>:</p> <pre><code>pass_this_in = lambda : print("I just did some stuff") </code></pre>
I need to find out x-path for only number of videos present in page using selenium <p>I need to find out x-path for only number of videos present in page using selenium.</p> <pre><code>&lt;div&gt; &lt;h4&gt; From &lt;a href="/publishers/957-buzzfeed"&gt;BuzzFeed &lt;/a&gt; • 2188 Videos &lt;/h4&gt; &lt;/div&gt; </code></pre> <p>Thanks in Advance</p>
<p>First get the text containg number of videos as follows: String headerText = driver.findElement(By.cssSelector("div > h4")).getText();</p> <p>Then, replace all the non-digiy charecters from headerText like this:</p> <p>int totalVideos = Integer.valueOf(headerText.replaceAll("\\D+"));</p>
Where on the website should I put RDF/XML Schema.org code? <p>I'm trying to put Schema.org on a website. First I made JSON-LD but the website is not allowing any <code>script</code> in the <code>head</code> element. Then I converted it into RDF/XML format below. </p> <p>Now, where on the website should I put this for Google to read it. Should I put in the <code>head</code> element?</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:schema="http://schema.org/"&gt; &lt;schema:Organization rdf:nodeID="genid1"&gt; &lt;schema:name rdf:datatype="http://www.w3.org/2001/XMLSchema#string"&gt;National Public Radio&lt;/schema:name&gt; &lt;schema:sponsor&gt; &lt;schema:Organization&gt; &lt;schema:name rdf:datatype="http://www.w3.org/2001/XMLSchema#string"&gt;GloboCorp&lt;/schema:name&gt; &lt;schema:url rdf:resource="http://www.example.com/"/&gt; &lt;/schema:Organization&gt; &lt;/schema:sponsor&gt; &lt;schema:url rdf:resource="http://npr.org"/&gt; &lt;/schema:Organization&gt; &lt;/rdf:RDF&gt; </code></pre>
<p>If you want to include it in the HTML document, you would have to use a <code>script</code> element (just like with JSON-LD). This <code>script</code> element <a href="http://stackoverflow.com/a/28688394/1591669">doesn’t have to be</a> part of the <code>head</code>, you can place it in the <code>body</code>. An alternative is to provide the RDF/XML in its own file and link it from the <code>head</code>, or offer it via content negotiation.</p> <p>That said, <strong>Google Search doesn’t support RDF/XML</strong>. For their search result features, which make use of Schema.org, they only <a href="https://developers.google.com/search/docs/guides/intro-structured-data#structured-data-guidelines" rel="nofollow" title="Structured data guidelines">support</a> these syntaxes:</p> <ul> <li>JSON-LD (in <code>script</code>)</li> <li>Microdata</li> <li>RDFa</li> </ul>
FormUrlEncodedContent works but StringContent does not <p>I have a question about those 2 httpcontents.</p> <p>I've made an webapi (php), copy from this: <a href="http://www.9lessons.info/2012/05/create-restful-services-api-in-php.html" rel="nofollow">http://www.9lessons.info/2012/05/create-restful-services-api-in-php.html</a> I re-used the Rest.inc.php, and implement my own api file.</p> <p>I try to call this api from .Net (I'm a .Net developer) - a simple WinForm Application - the FormUrlEncodedContent works but the StringContent does not. This my code:</p> <pre><code>Dictionary&lt;string, string&gt; parameters = new Dictionary&lt;string, string&gt;(); parameters.Add("username", username); parameters.Add("title", title); parameters.Add("text", text); var jsonString = JsonConvert.SerializeObject(parameters); var content = new StringContent(jsonString, Encoding.UTF8, "text/json"); //var content = new FormUrlEncodedContent(parameters); PostData(url, content); </code></pre> <p>And the reason why I want to use StringContent: in the real data, sometime the parameters will contain a byte[] (photo), and the FormUrlEncodedContent can't handle it</p> <p>Please help me Thanks alot!</p>
<p>They are very different formats. If the api does not have a smart model binder like Asp.Net Web API then it will not work. You can always base64 encode your byte array which is the typical way to transmit bytes via HTTP.</p>
Javascript: Maximum String length Chrome <p>in some other post I found that there should be limitation like 512mb (~2^27) for the maximum string length in javascript. I have the following code in my application:</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>i = 1; selectionField.value = i; i++; for (i;i&lt;=tableEntries;i++){ selectionField.value = selectionField.value + "," + i; }</code></pre> </div> </div> </p> <p>whereby "tableEntries" is e.g. "40000". This code executes fine in Firefox (though it takes around 5-10 seconds and prompts with a warning for a long running script) but does not execute in chrome. Chrome just interupts in this loop and says it cannot display the page. Is there a particular setting in chrome that can lead to this unexpected result? I mean the final string should have a length of ~240k chars. This should be fine according to the limit mentioned at the beginning.</p> <p>Thanks for help in advance!</p>
<p>The problem is not with the length of the string, but that you're trying to update the value in the input field on screen 240k~ times.</p> <p>A better solution would be to copy the field value to a variable, perform the string concatenation in-memory and then update the finished string only once in the DOM (on screen).</p> <p>Adding to your code, it would be something like this:</p> <pre><code>i = 1; var str = i; i++; for (i;i&lt;=tableEntries;i++){ str = str + "," + i; } selectionField.value = str; </code></pre>
C# - handling session variables like regular variables <p><strong>My primary problem is, that I have a code, which is full of method calls to set/get session variables which makes the source hard to read. I am searching for a better/simpler/more elegant solution. I tried operator overload in classes, wrapper classes, implicit type conversion, but I run into problems with all of them.</strong></p> <p>I would like to handle session variables like regular variables. After reading a lot of articles, I came up with the following solution which I'd like to make even simpler:</p> <pre><code>public class SV_string { private string key = ""; //to hold the session variable key public SV_string(string key) { this.key = key; // I set the key through the constructor } public string val // I use this to avoid using setter/getter functions { get { return (string)System.Web.HttpContext.Current.Session[key]; } set { System.Web.HttpContext.Current.Session[key] = value; } } } </code></pre> <p>I use the same key as the variable name:</p> <pre><code>public static SV_string UserID = new SV_string("UserID"); UserID.val = "Admin"; //Now the value assignment is quite simple string user = UserID.val; //Getting the data is quite simple too UserID = "Admin"; //but it would be even simpler </code></pre> <p>So is there any way to get the desired behaviour?</p> <p>Thanks in advance!</p>
<p>You can create the following Session Wrapper and just add your methods/properties/members to it</p> <pre><code>public static class EasySession { public static string UserId { get { return Get&lt;string&gt;(); } set { Set(value); } } public static string OtherVariableA { get { return Get&lt;string&gt;(); } set { Set(value); } } public static &lt;datatype&gt; OtherVariableB { get { return Get&lt;datatype&gt;(); } set { Set(value); } } static void Set&lt;T&gt;(T value, [CallerMemberName] string key = "") { System.Web.HttpContext.Current.Session[key] = value; } static T Get&lt;T&gt;([CallerMemberName] string key = "") { return (T)System.Web.HttpContext.Current.Session[key]; } } </code></pre> <p>You will then use it as follow</p> <pre><code>EasySession.UserId = "Admin" </code></pre> <p>Better yet. If you are using C# 6.0 then you can add the following to your namespaces</p> <pre><code>using System; using static xxx.EasySession; </code></pre> <p>This will then allow you to just call</p> <pre><code>UserId = "Admin" </code></pre> <p>Here is how it works</p> <p>[CallerMemberName] will get the name of what is calling Get or Set In this case it will then bassically be "UserId eg Set("UserId","Admin")</p> <p>Then it will go and just do the following System.Web.HttpContext.Current.Session["UserId"] = "Admin";</p> <p>(Ref:<a href="https://msdn.microsoft.com/en-us/magazine/dn879355.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/magazine/dn879355.aspx</a>)</p>
Visual Studio 2015 - Typescript "Build:Cannot find module..." <p>I'm trying to add Typescript to an existing .NET MVC project. I however get weird error-messages when I try to build. The Intellisense works and I can see that the typeings works. I can also see the .js-files being generated on manual save, meaning that the compileOnSave works. It's only when I try to build the whole project the errors show up.</p> <p><a href="http://i.stack.imgur.com/Q0YwA.png" rel="nofollow"><img src="http://i.stack.imgur.com/Q0YwA.png" alt="enter image description here"></a></p> <p>I use the following settings in Visual Studio 2015:</p> <ul> <li><p>Have installed typescript 2.0.3</p></li> <li><p>Added the following devDependencies in my package.json-file</p></li> </ul> <p><a href="http://i.stack.imgur.com/WQpVb.png" rel="nofollow"><img src="http://i.stack.imgur.com/WQpVb.png" alt="enter image description here"></a></p> <ul> <li>My tsconfig-file looks like this</li> </ul> <p><a href="http://i.stack.imgur.com/7k11l.png" rel="nofollow"><img src="http://i.stack.imgur.com/7k11l.png" alt="enter image description here"></a></p> <ul> <li>This is how i import the dependencies specified in the package.json-file.</li> </ul> <p><a href="http://i.stack.imgur.com/KKYEj.png" rel="nofollow"><img src="http://i.stack.imgur.com/KKYEj.png" alt="enter image description here"></a></p>
<p>Are your npm dependencies installed? If not, then you should run <code>npm install</code> command on your project folder manually, or to avoid this in the future, you can automatically install npm packages to your project on build by editing your <code>.njsproj</code> file, after line</p> <pre><code>&lt;Import Project="$(VSToolsPath)\Node.js Tools\Microsoft.NodejsTools.targets" /&gt; </code></pre> <p>add the following section:</p> <pre><code>&lt;PropertyGroup&gt; &lt;PreBuildEvent&gt; npm install --msvs_version=2015 &lt;/PreBuildEvent&gt; &lt;/PropertyGroup&gt; </code></pre> <p>Or if you only want it on rebuild, then:</p> <pre><code>&lt;PropertyGroup&gt; &lt;BeforeRebuildEvent&gt; npm install --msvs_version=2015 &lt;/BeforeRebuildEvent&gt; &lt;/PropertyGroup&gt; </code></pre> <p>The <code>--msvs_version=2015</code>command line option is not mandatory, but if you use multiple versions of VS or your npm is not set up correctly, then it might be useful.</p>
C++ CScrollView, how to scroll an image? <p>I draw an image in CScrollView (inherited from CView). Image scale is recalculated if view form is zoom in or zoom out:</p> <pre><code>//*.h CPictureHolder pic; //*.cpp void CMyAppView::OnPaint() { CPaintDC dc(this); CBitmap bmp; BITMAP b; HBITMAP hbitmap; CRect rect; auto bmp_iter = theApp.FullBmpMap.find(m_iCurrentImage); if (bmp_iter == theApp.FullBmpMap.end()) return; hbitmap = bmp_iter-&gt;second; bmp.Attach((*bmp_iter).second); bmp.GetObject(sizeof(BITMAP), &amp;b); GetClientRect(&amp;rect); scaleRect = rect; OriginalWidth = b.bmWidth; OriginalHeight = b.bmHeight; if (rect.Height() &lt;= b.bmHeight) scaleRect.right = rect.left + ((b.bmWidth*rect.Height()) / b.bmHeight); else if (rect.Height() &gt; b.bmHeight) { scaleRect.right = b.bmWidth; scaleRect.bottom = b.bmHeight; } scaleRect.right = scaleRect.right + scale_koef_g; scaleRect.bottom = scaleRect.bottom + scale_koef_v; pic.CreateFromBitmap(hbitmap); pic.Render(&amp;dc, scaleRect, rect); (*bmp_iter).second.Detach(); (*bmp_iter).second.Attach(bmp); bmp.Detach(); int isclWidth = scaleRect.Width(); int isclHeight = scaleRect.Height(); int irHeight = rect.Height(); int irWidth = rect.Width(); if ((isclWidth&gt; irWidth)||(isclHeight &gt; irHeight)) { SetScrollSizes(MM_TEXT, CSize(isclWidth, isclHeight)); } } </code></pre> <p>Zoom option through mouseweel:</p> <pre><code>BOOL CCardioAppView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { CPaintDC dc(this); CRect rect, scaleRect; GetClientRect(rect); if (zDelta &gt; 0)//up scale_counter++; else //down scale_counter--; if (scale_counter &lt; 0) scale_counter = 0; scale_koef_g = OriginalWidth*0.2*scale_counter; scale_koef_v = OriginalHeight*0.2*scale_counter; Invalidate(TRUE); return CScrollView::OnMouseWheel(nFlags, zDelta, pt); } </code></pre> <p>Zoom and scrools are working, but when I'm scrolling I got this:</p> <p><a href="http://i.stack.imgur.com/OyN3V.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/OyN3V.jpg" alt="enter image description here"></a> </p> <p>What do I need to add in my code?</p>
<p>Try TO NOT execute </p> <pre><code>CScrollView::OnMouseWheel(nFlags, zDelta, pt); </code></pre> <p>and instead do</p> <pre><code>return FALSE; </code></pre>
How do I get more than 10 message attachments from Microsoft Graph API? <p>When I query Microsoft Graph API to return attachments of an email then only a maximum of 10 attachments are returned (<a href="https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/message_list_attachments" rel="nofollow">https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/message_list_attachments</a>).</p> <p>I'm facing the same issue with Microsoft Outlook v2.0 API.</p> <p>It seems that the OData query parameters like "filter", "skip" and "top" are not supported from <em>https://graph.microsoft.com/v1.0/me/messages/{message_id}/attachments</em>. The query doesn't return any <code>@odata.nextLink</code> property.</p> <p>I'm using javascript and jQuery to get the attachements of a message.</p> <p>Anyone facing the same issue?</p>
<p>I don't reproduce this with either Graph (using <a href="https://graph.microsoft.io/en-us/graph-explorer" rel="nofollow">Graph Explorer</a>) or Outlook APIs (using <a href="https://oauthplay.azurewebsites.net" rel="nofollow">OAuth Sandbox</a>). I've got a message with 24 attachments and they all come back. Can you try those portals and see if you only get 10?</p>
Two canvases at same absolute position, how to force mouse focus to the top one <p>I have two canvases exactly at same position, the first adCanvas is used to draw a video ad before a game is loaded to another div. When the video ad ends, I show the game and move focus to mainCanvas simply with a command adCanvas.style.display="none";</p> <p>Currently for some reason the mainCanvas has the mouse focus all the time, so clicking the video ads does not work at all. Clicking of game is ok.</p> <pre><code> &lt;canvas style="position:absolute; top:0px; left:0px; z-index:2" id="adCanvas" width="660" height="440"&gt;&lt;/canvas&gt; &lt;canvas style="position:absolute; top:0px; left:0px; z-index:1" id="mainCanvas" width="660" height="440"&gt;&lt;/canvas&gt; </code></pre> <p>I also tried to use pointer-events:none but failed. This game is inside iframe.</p> <p>The reason to use two canvases is that for some reason game does not load if there is one common canvas.</p>
<p>The <code>mainCanvas</code> is on top of <code>adCanvas</code> (i.e. a higher <code>z-index</code>) so it will accept any mouse clicks if it is visible.</p> <p>I'm guessing <code>mainCanvas</code> is transparent (otherwise you wouldn't be able to see <code>adCanvas</code> anyway, right?) at this point so why not hide it the same way you are hiding <code>adCanvas</code> and show it once the video has finished?</p>
Several questions to implement multi lingual functionality with Umbraco? <p>I'm struggling to implement the multilingual functionality in Umbraco CMS version 7.5, currently i see 2 possible solutions:</p> <p><strong>1- Use only one root path</strong></p> <p>I think the best package as a complement for this solution is "Vorto", all I have to do is create new data types which extends the vorto data types and I can start edit texts directly on document types.</p> <p><strong>2- Use multiple root path</strong></p> <p>The idea is to duplicate the main root path for each language.</p> <p>-> I followed a lot of tutorials on the web but they all relate on previous versions of Umbraco and the solutions i found seem not working with the current version... Once i duplicate the root path and i associate the language to the root folder, what's the next step ?</p> <p><strong><em>I have a few more questions:</em></strong></p> <ol> <li>Do you have a better solution than the 2 on top ?</li> <li>How Umbraco knows the client language ? Does it take the first language in the header "Accept-language" in the HTTP request ?</li> <li>How could i extend the default routing to add the language as the first part, for example: <a href="http://domainName.ext/language/" rel="nofollow">http://domainName.ext/language/</a>....</li> </ol> <p>Thank you by advance !</p>
<p>Both scenarios have their pros and cons and both are widely used in the Umbraco community / solutions. I prefer 2nd solution, as especially on larger sites it gives you ability to restrict access for different language editors for example and not each site has a requirement to be 1-1 content structured.</p> <p>There is an Umbraco TV episode covering this topic here: <a href="https://umbraco.tv/videos/umbraco-v7/implementor/multi-lingual/creating-a-multi-lingual-site/introduction/" rel="nofollow">https://umbraco.tv/videos/umbraco-v7/implementor/multi-lingual/creating-a-multi-lingual-site/introduction/</a>.</p> <p>In summary:</p> <ul> <li>you need to create copy of your root language node</li> <li>then setup the culture for it</li> <li>use dictionary items to translate static content for each language</li> <li>create simple language picker choosing related site or just redirecting to selected language root</li> </ul> <p>Regarding your questions:</p> <p><strong>Ad.1.</strong> I don't have :)</p> <p><strong>Ad.2.</strong> It's selecting culture set up on the node(s), so it may be forced. Other than that it use standard .NET culture detection, so yes - it's using "accept-language" headers.</p> <p><strong>Ad.3.</strong> There is a key "umbracoHideTopLevelNodeFromPath" which enables you to include top level roots in the url paths. Read more: <a href="https://our.umbraco.org/documentation/reference/config/webconfig/" rel="nofollow">https://our.umbraco.org/documentation/reference/config/webconfig/</a></p> <p>And still, if you prefer to go with option 1, there is an awesome article about it with example code as well: <a href="http://24days.in/umbraco/2015/multilingual-vorto-nested-content/" rel="nofollow">http://24days.in/umbraco/2015/multilingual-vorto-nested-content/</a>. I will be playing with it now too! :)</p>
map not quite lazy? <p>map doesn't seem quite as lazy as I would like, in this example map calls the function one time as I would expect:</p> <pre><code>(first (map #(do (println "x: " %) %) '(0 1))) </code></pre> <p>but in these two examples it calls the function two times:</p> <pre><code>(first (map #(do (println "x: " %) %) '[0 1])) (first (map #(do (println "x: " %) %) (doall (range 2)))) </code></pre> <p>What is the underlying principle for making the choice to be lazy or not?</p> <p>Is there a way to guarantee total laziness?</p> <p>Thanks for your time.</p>
<p>Map (and similar HOFs which work on collections) work on sequence abstraction over collections: it creates a sequence from passed collection <code>(seq coll)</code> and works on returned sequence afterwards. PersistentList (<code>'(0 1)</code> is instance of PersistentList) implements ISeq through ASeq extension so <code>seq</code> function returns list itself. In case of PersistentVector ([1 2]) <code>seq</code> function returns chunked sequence (performance reasons, it evaluates chunk (32 elts) of data in one step, but returns only requested element; next chunk is calculated when current chunk is exhausted).</p> <p>When testing this behaviour, try to test with collections with count > 32 (<code>(vec (range 40))</code> returns vector of items 0-39):</p> <pre><code>=&gt; (first (map #(do (println "x: " %) %) (vec (range 40)))) x: 0 x: 1 x: 2 x: 3 ... x: 30 x: 31 0 </code></pre> <p>As you can see, whole chunk (elements 0 - 31) is evaluated when accessing first element, remaining elements (32 - 39) will be evaluated when requesting first element from the next chunk.</p> <p>In case of list collection, chunked seq is not used and only first item is evaluated (<code>(apply list (range 40))</code> returns list of items 0 - 39):</p> <pre><code>=&gt; (first (map #(do (println "x: " %) %) (apply list (range 40)))) x: 0 0 </code></pre>
How to prevent scaling on touch screen != mobile <p>Am running a web app on touch screen computer where you can zoom in and out. I want to prevent this behaviour I added this meta tag:</p> <pre><code>&lt;meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=0, width=device-width" /&gt; </code></pre> <p>Which is work fine on mobile devices but not on computer touch screen.</p> <p>Added info: with the meta tag above I can also zoom in when use a mac.</p>
<p>Try <code>user-scalable = no</code> instead of <code>user-scalable = 0</code>.</p>
How can I filter objects using django views? <p>I am using this generic view and I would like to filter the campaign_type's for only certain types. I was trying to use queryset= CampaignType.objects.filter(type='social') but it doesn't work. Any Clue ? Notice that the filter is for a manytomany relation with CampaignType and my model is Campaign.</p> <pre><code> class CCtypeUpdate(generic.UpdateView): model = Campaign fields = ['campaign_type'] template_name = 'campaign/campaign.html' success_url = '../../' </code></pre>
<p>Try this</p> <pre><code>class CCtypeUpdate(generic.UpdateView): model = Campaign fields = ['campaign_type'] ...... #rest of your code def get_form(self, form_class=None): form = super(CCtypeUpdate, self).get_form(form_class) form.fields["campaign_type"].queryset = CampaignType.objects.filter(type='social') return form </code></pre>
Can't display multiple data in select option using ionic <p>I want to display the data I get from my database and I actually getting 2 data but only one data are displayed in my select option.</p> <p>My code from my controller is this.</p> <pre><code> var link = 'http://127.0.0.1/mobile/subject.php'; var userid = JSON.parse(localStorage.getItem('loginDetails')); console.log(userid); $http.post(link, {userid: userid}).success(function(data){ console.log(data); for(i = 0; i&lt;data.length; i++){ $scope.subject = data[i].SubjectName; //$("#datas").append("&lt;div&gt;"+$scope.subject+"&lt;/div&gt;") } }) .error(function(err) { console.log(err) }); </code></pre> <p>My html code look like this {{subject}} I only put the {{subject}} on my option and I think this part should be loop to display more than one data.</p> <p>This are the data that i retrieved from my database <a href="http://i.stack.imgur.com/uPBFC.png" rel="nofollow"><img src="http://i.stack.imgur.com/uPBFC.png" alt="first data"></a></p> <p><a href="http://i.stack.imgur.com/TzmQm.png" rel="nofollow"><img src="http://i.stack.imgur.com/TzmQm.png" alt="2nd data"></a></p> <p>But this is the only data that display in my select option the 2nd data.. [<img src="http://i.stack.imgur.com/hpAZs.png" alt="select option data[3]"></p> <p>any help will be appreciated thank you :D I'm new to this so i'm getting confused.</p>
<p>You need to loop through each subject on the front-end like an ng repeat on option or ng-option. The way you are trying to display it now it will only show the last item within the array. Try the code below taken from here, but customize it to fit your work. <a href="https://docs.angularjs.org/api/ng/directive/select" rel="nofollow">https://docs.angularjs.org/api/ng/directive/select</a></p> <pre><code>&lt;div ng-controller="ExampleController"&gt; &lt;form name="myForm"&gt; &lt;label for="mySelect"&gt;Make a choice:&lt;/label&gt; &lt;select name="mySelect" id="mySelect" ng-options="option.name for option in data.availableOptions track by option.id" ng-model="data.selectedOption"&gt;&lt;/select&gt; &lt;/form&gt; &lt;hr&gt; &lt;tt&gt;option = {{data.selectedOption}}&lt;/tt&gt;&lt;br/&gt; &lt;/div&gt; </code></pre> <p>Another example, but again, you need to change it in some areas but the structure should remain the same: </p> <pre><code>&lt;select ng-model="filterCondition.sub"&gt; &lt;option ng-selected="{{sub.value == filterCondition.sub}}" ng-repeat="sub in subject" value="{{sub.value}}"&gt; {{sub.displayName}} &lt;/option&gt; &lt;/select&gt; </code></pre>
`multiple definition of` lots of variables error - is my make file incorrect? <p>I am getting an error when I compile <code>multiple definition of</code> lots of variables. For example:</p> <pre><code>/tmp/ccwHwJ7t.o:(.data+0x0): multiple definition of `serial_number' /tmp/ccmT1XNI.o:(.data+0x0): first defined here </code></pre> <p>All the variables are located in <code>ftdi.h</code>, which is included by <code>main.c</code>. Is there something wrong with my make file that is causing this to be included twice? or am I looking in the wrong directio.</p> <pre><code>SSHELL = /bin/sh CC = gcc APP = npi_usb_ftdi INC = include INCDIRS +=-I${INC} CFLAGS= ${INCDIRS} -Wall -Wextra LIBS = libftd2xx.a -ldl -lpthread -lrt all: ${APP} ${APP}: src/main.c src/ftdi.c src/vt100.c src/monitor.c ${CC} ${CFLAGS} src/main.c src/ftdi.c src/vt100.c src/monitor.c -o ${APP} ${LIBS} ftdi.o: ${CC} -c -o src/ftdi.o src/ftdi.c vt100.o: ${CC} -c -o src/vt100.o src/vt100.c monitor.o: ${CC} -c -o src/monitor.o src/monitor.c clean: rm -f src/*.o ; rm -f src/*~ ; rm -f *~ ; rm -f ${APP} </code></pre>
<p>You probably include the .h file in other source files too. No problem, but only in one source file should the variables be declared and in the others just defined. I use:</p> <pre><code>// ftdi.h #ifndef EXTERN # define EXTERN extern #endif EXTERN int examplevar; // main.c #define EXTERN #include "ftdi.h" // ftdi.c #include "ftdi.h" </code></pre>
How to conditionally drag and drop a div <p>When moving a div from <strong>FIRST</strong> to <strong>Second</strong> </p> <p>I need to check if this div already exists inside <strong>Second</strong></p> <p>(based on the tag-id="2" video-id="4" attributes)</p> <p>i have tried it this way </p> <p>During the drag and drop inside the stop callback function </p> <p>I am trying to fetch the tag-id </p> <p>but i am geting the following error </p> <p>VM317:95Uncaught TypeError: $(...).attr(...).closest is not a function</p> <pre><code>var PortletDraggable = function () { return { //main function to initiate the module init: function () { if (!jQuery().sortable) { return; } $("#sortable_portlets").sortable({ connectWith: ".portlet", items: ".portlet", opacity: 0.8, handle : '.portlet-title', coneHelperSize: true, placeholder: 'portlet-sortable-placeholder', forcePlaceholderSize: true, tolerance: "pointer", helper: "clone", tolerance: "pointer", forcePlaceholderSize: !0, helper: "clone", cancel: ".portlet-sortable-empty, .portlet-fullscreen", // cancel dragging if portlet is in fullscreen mode revert: 250, // animation in milliseconds update: function(b, c) { if (c.item.prev().hasClass("portlet-sortable-empty")) { c.item.prev().before(c.item); } }, stop: function(event, ui) { console.log($(event.target).attr('id').closest('packlistupdate').attr('tag-id')); } }); } }; }(); jQuery(document).ready(function() { PortletDraggable.init(); }); </code></pre> <p><a href="https://jsfiddle.net/33keyjxx/22/" rel="nofollow">https://jsfiddle.net/33keyjxx/22/</a></p> <p>Could you please let em know how to conditionally drag and drop a div ?</p>
<p>You have to use 'ui' instead of the 'event' , Here is the <a href="https://jsfiddle.net/Lphf43wd/" rel="nofollow">Working Demo</a></p> <p>below changes need in your stop function:</p> <pre><code> stop: function(event, ui) { debugger; console.log($(ui.item).attr('tag-id')); console.log($(ui.item).attr('video-id')); } </code></pre> <p>I hope this solution is helpful to you.</p>
ionic push notification not working <p>I am Implementing push notification in <code>ionic</code></p> <p>I have successfully got device <code>token</code> and <code>FCM credentials</code>.</p> <p>But when I build the project, I got following error.</p> <pre><code>FAILURE: Build failed with an exception. * What went wrong: A problem occurred configuring root project 'android'. &gt; Cannot add task ':processDebugGoogleServices' as a task with that name already exists. * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Error: cmd: Command failed with exit code 1 Error output: </code></pre> <p>below is some of my build.gradle file code:-</p> <pre><code>buildscript { //System.properties['com.android.build.gradle.overrideVersionCheck'] = 'true' repositories { mavenCentral() jcenter() } // Switch the Android Gradle plugin version requirement depending on the // installed version of Gradle. This dependency is documented at // http://tools.android.com/tech-docs/new-build-system/version-compatibility // and https://issues.apache.org/jira/browse/CB-8143 dependencies { classpath 'com.android.tools.build:gradle:2.1.0' classpath 'com.google.gms:google-services:1.3.0-beta1' } } dependencies { compile fileTree(dir: 'libs', include: '*.jar') // SUB-PROJECT DEPENDENCIES START debugCompile project(path: "CordovaLib", configuration: "debug") releaseCompile project(path: "CordovaLib", configuration: "release") compile "com.android.support:support-v13:23+" compile "com.google.android.gms:play-services-gcm:9.0.2+" compile "me.leolin:ShortcutBadger:1.1.4@aar" // SUB-PROJECT DEPENDENCIES END } apply plugin: 'com.google.gms.google-services' </code></pre>
<p>Did you find a solution for this? I got the same error when following these steps: <a href="https://github.com/edismooth/ionic2-firebase" rel="nofollow">https://github.com/edismooth/ionic2-firebase</a></p> <p>I guess that relates to the changes in RC0, but I have no idea what is causing this.</p>
Spring boot - rest template and rest template builder <p>I have questiom about spring resttemplate and resttemplatebuilder. As I know the resttemplatebuilder is some kind of factory for RestTemplate.I have few questions about using it:</p> <ol> <li><p>Very often in examples at internet I see something like this in @Configuration class:</p> <pre><code>@Bean public RestTemplate getRestClient() { RestTemplate restClient = new RestTemplate(); ... return restClient; } </code></pre> <p>Shouldn't RestTemplate be instantiate per <code>@Service</code> class ? If so, how to customize it ?</p></li> <li><p>Spring reference says that RestTemplateBuilder should be customized via RestTemplateCustomizer. How to manager many URI's from many IP addresses with one builder ?</p></li> <li><p>How to add globaly basicAuthentication to all RestTemplates via RestTemplateBuilder - or what is good practice.</p></li> </ol> <p>Thanks for help.</p> <p>UPDATE:</p> <p>My application calls rest services from many servers on different IP's and urls - so logically for me is the situation when I have many RestTemplates.</p> <p>I'm trying to have a factory (RestTemplateBuilder) per server - let's say servers A, B, C. I know how to add a basic authentication. But what for example when I want a basic authentication for server A but not for server B ?</p> <p>I was thinking about to have one RestTemplateBuilder per server. I don't want to do this manually but use Spring mechanisms.</p> <p>Any help ?</p>
<ol> <li><p>No, you dont need to, typically you will have on rest template instance, and you would pass different url, and request parameters accordingly every time. </p> <p>String result = restTemplate.getForObject("<a href="http://example.com/hotels/" rel="nofollow">http://example.com/hotels/</a>{hotel}/bookings/{booking}", String.class, vars);</p> <pre><code>Foo foo = restTemplate.getForObject(fooResourceUrl + "/1", Foo.class); </code></pre></li> <li><p>A descriptive example from <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-restclient.html" rel="nofollow">spring doc</a>, you can add as many customizers to the builder</p> <p>public class ProxyCustomizer implements RestTemplateCustomizer {</p> <pre><code> @Override public void customize(RestTemplate restTemplate) { HttpHost proxy = new HttpHost("proxy.example.com"); HttpClient httpClient = HttpClientBuilder.create() .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { @Override public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { if (target.getHostName().equals("192.168.0.5")) { return null; } return super.determineProxy(target, request, context); } }).build(); restTemplate.setRequestFactory( new HttpComponentsClientHttpRequestFactory(httpClient)); } } </code></pre></li> </ol> <blockquote> <p>Any RestTemplateCustomizer beans will be automatically added to the auto-configured RestTemplateBuilder. Furthermore, a new RestTemplateBuilder with additional customizers can be created by calling additionalCustomizers(RestTemplateCustomizer…​)</p> </blockquote> <pre><code> @Bean public RestTemplateBuilder restTemplateBuilder() { return new RestTemplateBuilder() .rootUri(rootUri) .basicAuthorization(username, password); } </code></pre>
read css file from HTML throws error <p>I have the below code to read and append to a div tag.(I have a requirement to implement this.)</p> <pre><code>var totalCss= "\n"; var requiredSheets = ['test.css']; var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules; for (var s = 0; s &lt;= classes.length; s++) { var cssRules = document.styleSheets[s].cssRules || document.styleSheets[s].rules || []; for (var c = 0; c &lt; cssRules.length; c++) { totalCss+= (cssRules[c].cssText + '\n'); } } </code></pre> <p>Test.css is in the same folder of HTML.</p> <p>My test.css have the below properties.(this is just sample)</p> <pre><code>.test triangle { stroke: #000; stroke-opacity: .75; shape-rendering: crispEdges; } .test square { stroke-opacity: .75; } .test circle { stroke-opacity: 0; } .test .line { fill: none; } </code></pre> <p>When I run the snippet I'm getting </p> <blockquote> <p>No rules defined error</p> </blockquote> <p>. If the styles are embedded in the same html file, the properties are able to fetch by the code. But external files referenced in the html is not recognizing by the code.What may the cause?</p> <p><a href="http://jsfiddle.net/sx68T/83/" rel="nofollow">Sample</a></p> <blockquote> <p>In this alert returns null.</p> </blockquote> <p>Edit:</p> <p>To my surprise the same code is working fine in Mozilla but showing cssrules null in chrome.</p>
<p>There are multiple stylesheets with a document. So you have to loop all the stylesheets.</p> <p>Below is the working example</p> <h1>Update 1</h1> <p>Added ajax to get the external css linked with the page</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 style = "\n"; for (var s = 0; s &lt; document.styleSheets.length; s++) { var cssRules = document.styleSheets[s].cssRules || document.styleSheets[s].rules || []; // IE support for (var c = 0; c &lt; cssRules.length; c++) { style += (cssRules[c].cssText + '\n'); } } console.log(style); //Request for each external css $("link").each(function() { if (this.href) { $.get(this.href, function(css) { console.log(css); }); } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.box { position: absolute; background-color: red; height: 10px; width: 10px; } #car, .car { position: absolute; background-color: red; height: 11px; width: 10px; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.css" rel="stylesheet" /&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
INotifyPropertyChanged Delegate <p>I saw a implementation of INotifyPropertyChanged like</p> <pre><code>public event PropertyChangedEventHandler PropertyChanged = delegate { }; </code></pre> <p>I usually implement it like</p> <pre><code>protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } </code></pre> <p>What is the difference/advantages / disadvantages between the 2 and what is recommended to use use? </p>
<p>The difference is simply that by initializing <code>PropertyChanged</code> with a no-op delegate to start with, you don't need to worry about whether or not the delegate is <code>null</code> due to there being no subscribers.</p> <p>Before C# 6, the "check whether or not it's null" aspect was a bit of a pain - with the null conditional operator that you're using, it's probably simpler to just use that to handle there being no subscribers. The other approach still works though, and you can even use them together - it'll just be redundant.</p>
combobox with different worksheets, that changes worksheets in code <p>i've a question: I would like to have a Combobox where all the worksheets are displayed. If you select a worksheet, then the worksheets in the code needs to change to the worksheet that you selected. I've tried but can't program this. easy example:</p> <pre><code>dim WRKsheet as worksheet set worksheet = Combobox1.value sheets(WRKsheet).activate </code></pre> <p>Do any of you guys know how i can succeed in this? Grts</p>
<p>Use the following code in a <code>User_Form</code> Module </p> <pre><code>Private Sub ComboBox1_Change() ' select the worksheet selected in the ComboBox1 Worksheets(ComboBox1.Value).Activate End Sub Private Sub UserForm_Activate() Dim Sht As Worksheet ' show all sheets names in thisworkbook in ComboBox1 For Each Sht In ThisWorkbook.Sheets ComboBox1.AddItem Sht.Name Next Sht End Sub </code></pre> <p>Note: (you need to call the form from another module, with <code>UserForm1.Show</code>)</p>
creating a list from a discrete function in mathematica <p>I'm trying to make a list of lists {{a},{b}...}, but instead I'm building a list of non-list terms {{{a}},{{b}}...}</p> <p>First, I started with a discrete function: </p> <pre><code> f[n_]:=RandomReal[BinormalDistribution[{c[[n, 3]], c[[n, 1]]}, ........... </code></pre> <p>Second, I made a list of lists by: </p> <pre><code> d = Array[f, 100] </code></pre> <p>Outputs: <code>{{{1.64219, 0.0231185}}, {{0.690885, 0.00599381}},......</code></p> <p>Which can not be read by <code>SmoothDensityHistogram</code>:</p> <blockquote> <p>SmoothDensityHistogram::ldata: {{1.64219,0.0231185}} is not a valid dataset or list of datasets.</p> </blockquote>
<p>You can <code>Flatten</code> a single level in your list of lists. Essentialy you're squeezing out a singleton dimension in your 3d array, making it 2d:</p> <pre><code>In[22]:= mylist = {{{1.64219, 0.0231185}}, {{0.690885, 0.00599381}}} Out[22]= {{{1.64219, 0.0231185}}, {{0.690885, 0.00599381}}} In[23]:= Dimensions[mylist] Out[23]= {2, 1, 2} In[24]:= mymatrix = Flatten[mylist, 1] Out[24]= {{1.64219, 0.0231185}, {0.690885, 0.00599381}} In[25]:= Dimensions[mymatrix] Out[25]= {2, 2} </code></pre>
How to fetch all remote branches? <p>Somehow one of my repositories refuses to fetch new branches:</p> <pre><code>C:\temp&gt;git fetch --all Fetching origin C:\temp&gt;git branch -a * develop remotes/origin/develop C:\temp&gt;git ls-remote --heads origin d130c97c1ccbe9ab35cd6e268c760781e37e3628 refs/heads/2.1.0.x ... 92685125df152fe053a2818de0c4d2ce8655c6b8 refs/heads/2.2.5.x 1e2eec16c7d63c84d6b53d0a221d22109b4de2a8 refs/heads/develop f6447d5315fe777803b283bee7dac1dbdba92536 refs/heads/feature/0001089__icons_are_gone_-_move_inclusion_to_RC_files e2cf0112b7e7fc18eb3467c7c42657208147efb2 refs/heads/feature/0001102__Debug_time_fix_exception_EIdSocketError_10060 6b2c89c6a39b3ce26cf42c5e8e5e0dd12c88abac refs/heads/feature/0001103__Research_cause_of_Internal_error_Stack_not_balanced ... 9f724b76b7c3533996fa03189e18a2f61fa5cf4f refs/heads/master c233696172eb05522d1bb6705a3ea8cd730a762d refs/heads/origin/master 1db38f4fab2c41ee1931c9c6165aa6087556210a refs/heads/release c233696172eb05522d1bb6705a3ea8cd730a762d refs/heads/trunk </code></pre> <p>How can I force <code>git</code> to fetch all these remote branches?</p> <p>I'm at <code>git version 2.8.2.windows.1</code>.</p>
<p>Check you <code>git config --get remote.origin.fetch</code> <strong><a href="https://git-scm.com/book/en/v2/Git-Internals-The-Refspec" rel="nofollow">refspec</a></strong>.</p> <p>It would only fetch <em>all</em> branches if the refspec is </p> <pre><code>+refs/heads/*:refs/remotes/origin/* </code></pre> <p>If the refspec is:</p> <pre><code>+refs/heads/develop:refs/remotes/origin/develop </code></pre> <p>Then a <code>fetch</code> would only bring back the <code>develop</code> branch.<br> This is typical of a <a href="https://git-scm.com/docs/git-clone" rel="nofollow"><code>git clone --branch develop --single-branch</code></a>.</p>
Prevent onClick event by clicking on a child div <p>I'm trying to create a modal in React JS</p> <p>I have one outter div which is the whole body and I have I inner div. I want to apply the function to close the modal if it's clicked outside of the inner div.</p> <p>My code is as follows :</p> <pre><code>popupOutterDivStyle() { return { zIndex: 10000, position: "fixed", width: "100%", height: "100%", top: 0, left: 0, background: "rgba(102,102,102,0.8)" } } popupInnerDivStyle() { return { zIndex: 20000, position: "fixed", width: "70%", top: "50%", left: "50%", height: "400px", marginTop: "-200px", /*set to a negative number 1/2 of your height*/ marginLeft: "-35%", /*set to a negative number 1/2 of your width*/ background: "rgba(255,255,255,1)", display: 'block' } } closePopupIcon() { return { position: "absolute", right: -25, top: - 27, zIndex: 30000, cursor: "pointer" } } render() { const animationSettings = { transitionName: "example", transitionEnterTimeout: 500, transitionAppearTimeout: 500, transitionLeaveTimeout: 500, transitionAppear: true, transitionLeave: true }; return ( &lt;div onClick={this.props.closeModal}&gt; &lt;ReactCSSTransitionGroup {...animationSettings}&gt; &lt;div key={this.props.modalState} style={this.popupOutterDivStyle()} className={showModal}&gt; &lt;div style={this.popupInnerDivStyle()}&gt; &lt;a href="#" style={this.closePopupIcon()} onClick={this.props.closeModal}&gt;&lt;i className="closePopup ion-ios-close-empty" /&gt;&lt;/a&gt; {this.props.children} &lt;/div&gt; &lt;/div&gt; &lt;/ReactCSSTransitionGroup&gt; &lt;/div&gt; ); } </code></pre> <p>When I click on link with the icon or when I click outside of the inner div it's working fine. </p> <p>But the problem is that it's closed also if I clicked inside the inner div.</p> <p>I do not want to use jquery.</p> <p>Any advice?</p> <p><strong>UPDATE</strong></p> <pre><code>stopPropagation(event){ event.stopPropagation(); } &lt;div&gt; &lt;ReactCSSTransitionGroup {...animationSettings}&gt; &lt;div id="outter" key={this.props.modalState} style={this.popupOutterDivStyle()} className={showModal} onClick={this.props.closeModal}&gt; &lt;div id="inner" style={this.popupInnerDivStyle()} onClick={this.stopPropagation.bind(this)}&gt; &lt;a href="#" style={this.closePopupIcon()} onClick={this.props.closeModal}&gt;&lt;i className="closePopup ion-ios-close-empty" /&gt;&lt;/a&gt; {this.props.children} &lt;/div&gt; &lt;/div&gt; &lt;/ReactCSSTransitionGroup&gt; &lt;/div&gt; </code></pre> <p>And <code>this.props.children</code> in my case is a contact form :</p> <pre><code>export default class ContactForm extends React.Component { constructor(props) { super(props); this.state = { senderName: '', email: '', message: '', errors: {} }; this.sendingHandle = this.sendingHandle.bind(this); this.contactHandle = this.contactHandle.bind(this); } contactHandle(event) { let field = event.target.name; let value = event.target.value; console.log(field); } sendingHandle(event) { event.preventDefault(); } render() { const language = this.props.currentLanguage.homePage; return ( &lt;div className="contact-form"&gt; &lt;form&gt; &lt;div className="col-lg-12 col-md-12 col-sm-12 col-xs-12"&gt; &lt;TextInput type="text" name="senderName" label={language.contactNameLabel} labelClass="contactLabel" placeholder={language.contactNameLabel} className="templateInput" icon="user" iconSize="15x" iconClass="contactFaIcon" onChange={this.contactHandle} value={this.state.name} errors={this.state.errors.senderName} /&gt; &lt;/div&gt; &lt;div className="col-lg-12 col-md-12 col-sm-12 col-xs-12"&gt; &lt;TextInput type="text" name="email" label={language.contactEmailLabel} labelClass="contactLabel" placeholder={language.contactEmailLabel} className="templateInput" icon="envelope-o" iconSize="15x" iconClass="contactFaIcon" onChange={this.contactHandle} value={this.state.email} errors={this.state.errors.email} /&gt; &lt;/div&gt; &lt;div className="col-md-12 col-sm-12 col-xs-12"&gt; &lt;Textarea className="message" name="message" placeholder={language.contactMessageLabel} label={language.contactMessageLabel} labelClass="contactLabel" icon="comments-o" iconSize="15x" iconClass="contactFaIcon" onChange={this.contactHandle} errors={this.state.errors.message} /&gt; &lt;/div&gt; &lt;div className="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center"&gt; &lt;Button text="Verzenden" handleClick={this.sendingHandle.bind(this)}/&gt; &lt;/div&gt; &lt;/form&gt; &lt;div className="clearfix" /&gt; &lt;/div&gt; ); } } </code></pre>
<p>If you attach a function to the inner div which <code>stops propagation</code> it should work, right?</p> <pre><code> function stopPropagation(e) { e.stopPropagation( } </code></pre> <p>In your case <code>&lt;div style={this.popupInnerDivStyle()} onClick={stopPropagation}&gt;</code></p> <p>Does this help you: <a href="http://stackoverflow.com/questions/24415631/reactjs-syntheticevent-stoppropagation-only-works-with-react-events">ReactJS SyntheticEvent stopPropagation() only works with React events?</a></p>
error when defining a std::shared_ptr with new operator <p>I am trying to define a <code>std::shared_ptr</code> with <code>new</code> operator in the following way:</p> <pre><code>#include &lt;memory&gt; struct A { }; int main() { std::shared_ptr&lt;A&gt; ptr = new A(); return 0; } </code></pre> <p>but I obtained the following compile-time error:</p> <blockquote> <p>main.cpp: In function 'int main()':</p> <p>main.cpp:8:30: error: conversion from 'A*' to non-scalar type 'std::shared_ptr' requested std::shared_ptr ptr = new A(); </p> </blockquote> <p>Anyway, the following definitely works:</p> <pre><code> std::shared_ptr&lt;A&gt; ptr{new A()}; </code></pre> <p>Does anyone of you know why this happens?</p>
<p><strong><em>tl;dr:</em> it's a consequence of the relevant constructor being <code>explicit</code>.</strong></p> <p>When you initialise with <code>=</code>, you invoke copy-initialisation. C++ does not allow copy-initialisation of a <code>shared_ptr</code> from a raw pointer, because it would be too easy to end up with an accidental implicit conversion from some arbitrary raw pointer into a <code>shared_ptr</code> that doesn't actually manage it.</p> <p>This way, the only way you can "ensnare" a raw pointer into a <code>shared_ptr</code> is very deliberately and very explicitly (as you have correctly done in your second example). Now, only in this initialiser do you have to remember not to do so with a pointer you're already managing elsewhere.</p> <p>Is there anything actually dangerous about the specific line <code>std::shared_ptr&lt;A&gt; ptr = new A()</code>? No. But what you're seeing is a consequence of various C++ rules working together in concert.</p>
callback function for Google Geocode API returning NULL Value <p>I have the geoCode function that uses a callback function to do something after the asynchronous request has completed. However, it returns a NULL value. </p> <pre><code> function codeAddress(callback) { /***** build string address from form data var address = addressOne + "," + addressTwo + "," + region + "," + zip + "," + country; *****/ var geocodeAddress = geocoder.geocode( { 'address': address}, function (results, status) { callback( results ) } ); } codeAddress(function(returnData){ console.log("results= " + returnData); console.log(returnData); }); </code></pre> <p>this gives empty array</p>
<pre><code>var returnData = function () { return data; }; codeAddress (returnData ()); </code></pre> <p>Should be able to pass what you like.</p>
Migrating from AMPL to Pyomo <p>I am trying to use open source Pyomo lib instead of ampl, so i am trying migrating the ampl car problem that comes in the Ipopt source code tarball as example, but i am having got problems with the end condition (reach a place with zero speed at final iteration) and with the cost function (minimize final time).</p> <p>The code below states the dae system:</p> <pre><code># min tf # dx/dt = 0 # dv/dt = a - R*v^2 # x(0) = 0; x(tf) = 100 # v(0) = 0; v(tf) = 0 # -3 &lt;= a &lt;= 1 (a is the control variable) #!Python3.5 from pyomo.environ import * from pyomo.dae import * N = 20; T = 10; L = 100; m = ConcreteModel() # Parameters m.R = Param(initialize=0.001) # Variables def x_init(m, i): return i*L/N m.t = ContinuousSet(bounds=(0,1000)) m.x = Var(m.t, bounds=(0,None), initialize=x_init) m.v = Var(m.t, bounds=(0,None), initialize=L/T) m.a = Var(m.t, bounds=(-3.0,1.0), initialize=0) # Derivatives m.dxdt = DerivativeVar(m.x, wrt=m.t) m.dvdt = DerivativeVar(m.v, wrt=m.t) # Objetives m.obj = Objective(expr=m.t[N]) # DAE def _ode1(m, i): if i==0: return Constraint.Skip return m.dxdt[i] == m.v[i] m.ode1 = Constraint(m.t, rule=_ode1) def _ode2(m, i): if i==0: return Constraint.Skip return m.dvdt[i] == m.a[i] - m.R*m.v[i]**2 m.ode2 = Constraint(m.t, rule=_ode2) # Constraints def _init(m): yield m.x[0] == 0 yield m.v[0] == 0 yield ConstraintList.End m.init = ConstraintList(rule=_init) ''' def _end(m, i): if i==N: return m.x[i] == L amd m.v[i] == 0 return Constraint.Skip m.end = ConstraintList(rule=_end) ''' # Discretize discretizer = TransformationFactory('dae.finite_difference') discretizer.apply_to(m, nfe=N, wrt=m.t, scheme='BACKWARD') # Solve solver = SolverFactory('ipopt', executable='C:\\EXTERNOS\\COIN-OR\\win32-msvc12\\bin\\ipopt') results = solver.solve(m, tee=True) </code></pre>
<p>Currently, a ContinuousSet in Pyomo has to be bounded. This means that in order to solve a minimum time optimal control problem using this tool, the problem must be reformulated to remove the time scaling from the ContinuousSet. In addition, you have to introduce an extra variable to represent the final time. I've added an example to the <a href="https://github.com/Pyomo/pyomo/blob/master/examples/dae/car_example.py" rel="nofollow">Pyomo github repository</a> showing how this can be done for your problem. </p>
Flip a 2D character, using inverse kinematics, in Unity <p>I have a rigged 2D character with <a href="https://github.com/Banbury/UnitySpritesAndBones" rel="nofollow">Sprites And Bones</a> in Unity and I use inverse kinematics to animate it.</p> <p>But if I want to flip the X-axis, my character go berserk :</p> <p><a href="http://i.stack.imgur.com/nFxI0.gif" rel="nofollow"><img src="http://i.stack.imgur.com/nFxI0.gif" alt="IK flipping"></a></p> <p>I have a script attached to "Karateka", containing a simple <code>Flip()</code> function :</p> <pre><code>public void Flip(){ facingRight = !facingRight; Vector3 karatekaScale = transform.localScale; karatekaScale.x *= -1; transform.localScale = karatekaScale; } </code></pre> <ul> <li>"Karateka" is just a container for bones, sprites and IK targets</li> <li>"Skeleton" contains the Skeleton script from Sprite And Bones</li> <li>"Right leg bone", "Right lower leg bone", etc. have bone and IK scripts</li> <li>"Right leg", "Right lower leg", etc. are the sprites</li> <li>"IK" contains all the IK targets</li> </ul> <p>I have the same kind of effect with an other IK script, Simple CCD, from <a href="https://youtu.be/HM17mAmLd7k?t=644" rel="nofollow">Unite 2014 - 2D Best Practices In Unity</a>, so I may just do something stupid.</p> <p>What can I do to properly flip my character?</p> <p>EDIT (for Mark) :</p> <p>I got it to work using this :</p> <pre><code>public void Flip(){ facingRight = !facingRight; /* Vector3 karatekaScale = transform.localScale; karatekaScale.x *= -1; transform.localScale = karatekaScale; */ GameObject IK = GameObject.Find ("IK"); GameObject skeleton = GameObject.Find ("Skeleton"); Vector3 ikScale = IK.transform.localScale; ikScale.x *= -1; IK.transform.localScale = ikScale; if (facingRight) { skeleton.transform.localEulerAngles = new Vector3(skeleton.transform.localEulerAngles.x, 180.0f, skeleton.transform.localEulerAngles.z); } else { skeleton.transform.localEulerAngles = new Vector3(skeleton.transform.localEulerAngles.x, 0.0f, skeleton.transform.localEulerAngles.z); } } </code></pre>
<p>Okay, so as we discussed in comments, just to sum it up:<br> 1) You don't flip everything and/or don't reset bones correctly, that's why the animation "falls apart" on flipping<br> 2) One can do a <code>SpriteRenderer</code>.flip[X/Y] but this should be done on every element of the sprite<br> 3) Skeleton script has an "Edit mode" checkbox. When it's checked and one flips the character using <code>scale.x *= -1</code>, can see that everything <strong>except the bones</strong> are flipped</p> <p>And last but not least, the question got updated with the code snippet providing the "code level solution" to the issue.<br><br>Thanks for sharing all the details Cyrille as well as I'm glad I could help.</p>
No action occurred when clicking on Edite button <p>i'm trying to edit a row (my project is a simple phone book)from my index view which shows all of my records (Contact) but when i click on the edit button nothing happens </p> <p>this is my delete method </p> <pre><code>#region [- Delete -] #region [- Get -] [HttpGet] // [HttpDelete] public ActionResult Delete(int? _id, Models.EF_Model.Phone_book _model) { return View(); } #endregion #region [- Post -] [HttpPost] //[HttpDelete] public ActionResult Delete(Models.EF_Model.Phone_book _Model) { if (ModelState.IsValid) { Ref_ViewModel = new ViewModel.ViewModel(); Ref_ViewModel.Delete(_Model.Id); } else { ViewBag.Massage = "Choose a Contact"; } return View(_Model); } #endregion #endregion </code></pre> <p>this is my edit method in my Home controller</p> <pre><code> [HttpGet] public ActionResult Edit(int? _id) { if (_id==null) { return new HttpStatusCodeResult(HttpStatusCode.NoContent); } else { Ref_ViewModel = new ViewModel.ViewModel(); return View(Ref_ViewModel.Select(_id)); } } [HttpPost] public ActionResult Edit(ViewModel.DTO.Contact Ref_Contact) { if (ModelState.IsValid) { Ref_ViewModel = new ViewModel.ViewModel(); Ref_ViewModel.Edit(Ref_Contact, Ref_Contact.Id); } else { ViewBag.Message = "Choose a Contact"; } return View(); } </code></pre> <p>this is it's view(Contact class is a simple DTO class)</p> <pre><code>@model Phone_Book.ViewModel.DTO.Contact @{ ViewBag.Title = "Edit"; } &lt;h2&gt;Edit&lt;/h2&gt; @using (Html.BeginForm()) { @Html.AntiForgeryToken() &lt;div class="form-horizontal"&gt; &lt;h4&gt;Contact&lt;/h4&gt; &lt;hr /&gt; @Html.ValidationSummary(true, "", new { @class = "text-danger" }) &lt;div class="form-group"&gt; @Html.LabelFor(model =&gt; model.FName, htmlAttributes: new { @class = "control-label col-md-2" }) &lt;div class="col-md-10"&gt; @Html.EditorFor(model =&gt; model.FName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model =&gt; model.FName, "", new { @class = "text-danger" }) &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; @Html.LabelFor(model =&gt; model.LName, htmlAttributes: new { @class = "control-label col-md-2" }) &lt;div class="col-md-10"&gt; @Html.EditorFor(model =&gt; model.LName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model =&gt; model.LName, "", new { @class = "text-danger" }) &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; @Html.LabelFor(model =&gt; model.Num, htmlAttributes: new { @class = "control-label col-md-2" }) &lt;div class="col-md-10"&gt; @Html.EditorFor(model =&gt; model.Num, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model =&gt; model.Num, "", new { @class = "text-danger" }) &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; @Html.LabelFor(model =&gt; model.Email, htmlAttributes: new { @class = "control-label col-md-2" }) &lt;div class="col-md-10"&gt; @Html.EditorFor(model =&gt; model.Email, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model =&gt; model.Email, "", new { @class = "text-danger" }) &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; @Html.LabelFor(model =&gt; model.Address, htmlAttributes: new { @class = "control-label col-md-2" }) &lt;div class="col-md-10"&gt; @Html.EditorFor(model =&gt; model.Address, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model =&gt; model.Address, "", new { @class = "text-danger" }) &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;div class="col-md-offset-2 col-md-10"&gt; &lt;input type="submit" value="Save" class="btn btn-default" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; } &lt;div&gt; @Html.ActionLink("Back to List", "Index") &lt;/div&gt; </code></pre> <p>this is my index view </p> <pre><code>@model IEnumerable&lt;Phone_Book.Models.EF_Model.Phone_book&gt; @{ ViewBag.Title = "Index"; } &lt;h2&gt;Index&lt;/h2&gt; &lt;p&gt; @Html.ActionLink("Create New", "Create") &lt;/p&gt; &lt;table class="table"&gt; &lt;tr&gt; &lt;th&gt; @Html.DisplayNameFor(model =&gt; model.First_Name) &lt;/th&gt; &lt;th&gt; @Html.DisplayNameFor(model =&gt; model.Last_Name) &lt;/th&gt; &lt;th&gt; @Html.DisplayNameFor(model =&gt; model.Number) &lt;/th&gt; &lt;th&gt; @Html.DisplayNameFor(model =&gt; model.Email) &lt;/th&gt; &lt;th&gt; @Html.DisplayNameFor(model =&gt; model.Address) &lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;/tr&gt; @foreach (var item in Model) { &lt;tr&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.First_Name) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.Last_Name) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.Number) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.Email) &lt;/td&gt; &lt;td&gt; @Html.DisplayFor(modelItem =&gt; item.Address) &lt;/td&gt; &lt;td&gt; @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) &lt;/td&gt; &lt;/tr&gt; } &lt;/table&gt; </code></pre>
<p>In your Edit method in your HomeController, try this:</p> <pre><code>[HttpGet] public ActionResult Edit(int? _id) { if (_id==null) { return new HttpStatusCodeResult(HttpStatusCode.NoContent); } else { return View(); } } </code></pre>
Make a link that opens app if installed, open Google Play/Appstore if not installed, and open another link if desktop pc? <p>I want to make a link in an email, that opens my app, if the app is installed. If it isn't installed, I want it to open either google play or Appstore depending on the phone people use. If they are on a desktop pc / anything else than android and IOS, it should open another normal weblink.</p> <p>How is this possible?</p>
<p>Detect the user agent first, then according to that navigate the user to different locations. here is the simple javascript code which you can add up in your site, then give the site url in the email. Hope this help. </p> <pre><code>//Useragent detection from http://stackoverflow.com/questions/21741841/detecting-ios-android-operating-system function getMobileOperatingSystem() { var userAgent = navigator.userAgent || navigator.vendor || window.opera; // Windows Phone must come first because its UA also contains "Android" if (/windows phone/i.test(userAgent)) { //Code here for windows phone. } if (/android/i.test(userAgent)) { window.location = 'https://play.google.com/store/apps/details?id=YOUR_APPLICTION_ID'; } // iOS detection from: http://stackoverflow.com/a/9039885/177710 if (/iPad|iPhone|iPod/.test(userAgent) &amp;&amp; !window.MSStream) { //Code here for itunes. } //Code to navigation for your website. } </code></pre> <p>Opening apps in Android needs specific URI implementation in android, then you can redirect the users to that URI to open your application.</p>
How to get a webserver's content from a local html file <p>So right now I have a html file which I need locally stored, when I open this webpage I need it to download some content from a webserver.</p> <p>I've tried using Jquery's AJAX but that doesnt let me use cross domain, so I am stuck, here is what I have tried to get to work</p> <pre><code>&lt;script&gt; $(document).ready(function() { var url = 'example.com/function.php?ID=' + id; $( "#result" ).load( url); }); &lt;/script&gt; </code></pre> <p>Obviously Im aware the above code I made does not work as it has something to do with it being cross domain.</p>
<p>You can use JSONp method, this method is <strong>preferable</strong>. Here is how: <a href="http://stackoverflow.com/a/3506306/5434216">Link</a></p> <p>Or you can allow access on server side by using <code>Access-Control-Allow-Origin: *</code> in php headers. You write your own domain instead of using <code>*</code></p>
Pessimistic lock on orientDB graph API <p>I am creating a system in orientDB I have some cases where i need to make the system where multiple threads adding edges to certain vertex and updating a property on that vertex. My Question is that is there any method where i can block operations on this vertex until other threads finish a block of code this block for both read and write?</p> <p>My case i have vertex for hotel and number of available rooms as property, any reservation, my code will work the following order</p> <p>1- Make sure the remaining rooms size is more than 1</p> <p>2- Create an edge to the customer vertex </p> <p>3- Decrease the number of available rooms by one</p>
<p>OrientDB has an optimistic concurrency control system, but on very high concurrent updates on the few records it could be more efficient locking records to avoid retries. You could synchronize the access by yourself or by using the storage API. Note that this works only with non-remote databases.</p> <pre><code>((OStorageEmbedded)db.getStorage()).acquireWriteLock(final ORID iRid) ((OStorageEmbedded)db.getStorage()).acquireSharedLock(final ORID iRid) ((OStorageEmbedded)db.getStorage()).releaseWriteLock(final ORID iRid) ((OStorageEmbedded)db.getStorage()).releaseSharedLock(final ORID iRid) </code></pre> <p>Source and examples of usage can be found on the <a href="http://orientdb.com/docs/last/Performance-Tuning.html#high-concurrent-updates" rel="nofollow">official documentation</a>.</p>
Heroku run cp -r is trying to run on the wrong git remote <p>I tried to run this command on Heroku. </p> <pre><code>heroku run cp -r /app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/static/admin doctor_app/static/ </code></pre> <p>And I got this error.</p> <pre><code>▸ Error: Could not find git remote /app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/static/admin in /home/adil/Code/mezino/DocTest/doctor_app ▸ remotes: heroku </code></pre> <p>Any Idea, Why ?</p>
<p>Heroku uses different git remotes to separate environments, so I believe it is interpreting the -r flag in your command as the remote to run on. Sticking the command in quotes will force it to interpret that whole block as one argument.</p> <p><code>heroku run "cp -r /app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/static/admin doctor_app/static/" </code></p>
how to complex manage shell processes with asyncio? <p>I want to track reboot process of daemon with python's asyncio module. So I need to run shell command <code>tail -f -n 0 /var/log/daemon.log</code> and analyze it's output while, let's say, <code>service daemon restart</code> executing in background. Daemon continues to write to log after service restart command finished it's execution and reports it's internal checks. Track process read checks info and reports that reboot was successful or not based it's internal logic.</p> <pre><code>import asyncio from asyncio.subprocess import PIPE, STDOUT async def track(): output = [] process = await asyncio.create_subprocess_shell( 'tail -f -n0 ~/daemon.log', stdin=PIPE, stdout=PIPE, stderr=STDOUT ) while True: line = await process.stdout.readline() if line.decode() == 'reboot starts\n': output.append(line) break while True: line = await process.stdout.readline() if line.decode() == '1st check completed\n': output.append(line) break return output async def reboot(): lines = [ '...', '...', 'reboot starts', '...', '1st check completed', '...', ] p = await asyncio.create_subprocess_shell( ( 'echo "rebooting"; ' 'for line in {}; ' 'do echo $line &gt;&gt; ~/daemon.log; sleep 1; ' 'done; ' 'echo "rebooted";' ).format(' '.join('"{}"'.format(l) for l in lines)), stdin=PIPE, stdout=PIPE, stderr=STDOUT ) return (await p.communicate())[0].splitlines() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.gather( asyncio.ensure_future(track()), asyncio.ensure_future(reboot()) )) loop.close() </code></pre> <p>This code is only way I've found to run two coroutines in parallel. But how to run <code>track()</code> strictly before <code>reboot</code> to not miss any possible output in log? And how to retrieve return values of both coroutines?</p>
<blockquote> <p>But how to run track() strictly before reboot to not miss any possible output in log?</p> </blockquote> <p>You could <code>await</code> the first subprocess creation before running the second one. </p> <blockquote> <p>And how to retrieve return values of both coroutines?</p> </blockquote> <p><a href="https://docs.python.org/3.5/library/asyncio-task.html#asyncio.gather" rel="nofollow"><code>asyncio.gather</code></a> returns the aggregated results.</p> <p>Example:</p> <pre><code>async def main(): process_a = await asyncio.create_subprocess_shell([...]) process_b = await asyncio.create_subprocess_shell([...]) return await asyncio.gather(monitor_a(process_a), monitor_b(process_b)) loop = asyncio.get_event_loop() result_a, result_b = loop.run_until_complete(main()) </code></pre>
Worksheet_Changed Method for code generated Worksheet <p>I'm creating a Worksheet by Code and add some value. Now I want to check wheater the value in Column C has changed and want to change the value of column D too. I found the sub Worksheet_Change to do this. But this method is not working for my created worksheet, it's working for the sheet I came from. Can someone help me please?</p> <p>I'm setting the Worksheet to active using ws.activate, but it's not working like I want it to work.</p> <pre><code>Sub Test() Dim monat As Integer Dim jahr As Integer Dim tag As Integer Dim anzahlTage As Integer Dim ws As Worksheet Dim kalenderTag As Date On Error GoTo Fehler jahr = Worksheets("Kalender erstellen").Cells(2, 2).Value monat = Worksheets("Kalender erstellen").Cells(2, 1).Value anzahlTage = DateSerial(jahr, monat + 1, 1) _ - DateSerial(jahr, monat, 1) Set ws = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)) ws.Name = MonthName(monat) + " " + CStr(jahr) ws.Cells(1, 1) = "Datum" ws.Cells(1, 2) = "Wochentag" ws.Cells(1, 3) = "Beginn" ws.Cells(1, 4) = "Ende" ws.Cells(1, 5) = "Stunden" ws.Cells(1, 6) = "Über-/Unterstunden" ws.Cells(1, 8) = "Stunden gesamt" ws.Cells(1, 9) = "Urlaub gesamt" ws.range("A1", "I33").HorizontalAlignment = xlCenter ws.range("A1", "I1").Font.FontStyle = "Bold" ws.Columns("B").ColumnWidth = 20 ws.Columns("F").ColumnWidth = 20 ws.Columns("H").ColumnWidth = 25 ws.Columns("I").ColumnWidth = 25 ws.range("A2", "I2").MergeCells = True ws.Activate For tag = 1 To anzahlTage kalenderTag = DateSerial(jahr, monat, tag) ws.Cells(tag + 2, 1) = kalenderTag ws.Cells(tag + 2, 2) = Format$(kalenderTag, "dddd") Next tag 'Dim rng As range 'Set rng = ActiveSheet.range("A1", "F1") 'With rng.Borders '.LineStyle = xlContinous '.Color = vbBlack '.Weight = xlThin 'End With 'MsgBox (anzahlTage) Exit Sub Fehler: MsgBox "FehlerNr.: " &amp; Err.Number &amp; vbNewLine &amp; vbNewLine _ &amp; "Beschreibung: " &amp; Err.Description _ , vbCritical, "Fehler" End Sub Private Sub Worksheet_Change(ByVal Target As range) If Not Application.Intersect(Target, range("C3", "C33")) Is Nothing Then MsgBox ("TEST") End If End Sub </code></pre>
<p>For the code to work in a newly created worksheet, it must be inserted into the worksheet code for the new sheet.<br><br><br>It is easier to <code>.Copy</code> an existing worksheet that already has the macro installed than to <code>.Add</code> a fresh worksheet.</p> <p>You get the added benefit that the <code>.Copied</code> worksheet can have pre-formatted column, rows, headers, etc.</p>
Object not rotating around its axis <p>I have a gun consisting of two parts (1 is handle, 2 is nozzle). I want to rotate the nozzle when I shoot the target.</p> <p><a href="http://i.stack.imgur.com/AbQGS.gif" rel="nofollow"><img src="http://i.stack.imgur.com/AbQGS.gif" alt="I want to rotate the Nozzle like this"></a></p> <p>I am using following code of line inside my fire function </p> <pre><code>gunNozzle.transform.Rotate(0, 0, 10); </code></pre> <p>It is increasing the rotation value, but the result is different. Here is complete function: </p> <pre><code>void Update() { if (Input.GetKeyDown(KeyCode.P)) { isOut = true; } if (isOut) { playerAnim.CrossFade("gunplays", 0.03f); gunNozzle.transform.Rotate(0, 0, 10); audioSource.Play(); GameObject cloneArrow = (GameObject)Instantiate(theArrow, thePos, Quaternion.identity); cloneArrow.transform.position = thePos; cloneArrow.transform.rotation = this.transform.rotation; isOut = false; } } </code></pre> <p>It seems to be a simple thing, but I am stuck.</p> <p>Here is the result:</p> <p><a href="http://i.stack.imgur.com/4nlny.gif" rel="nofollow"><img src="http://i.stack.imgur.com/4nlny.gif" alt="Here is the result of the above code"></a></p>
<p>Your parameters to transform.Rotate don't looks correct to me. Should be something like </p> <pre><code>gunNozzle.transform.Rotate(Vector3.right * Time.deltaTime); </code></pre> <p>Nb: Vector direction might be wrong in my example.</p>
MYSQL LEFT JOIN result not giving <p>I have 2 tables</p> <p>banks table </p> <pre><code>create table `banks` ( `bank_id` int , `bank_name` varchar (150), `balance` double , `b_date` date , `delete_state` double ); insert into `banks` (`bank_id`, `bank_name`, `balance`, `b_date`, `delete_state`) values('1','Emirates NBD','632008','2016-10-10','0'); insert into `banks` (`bank_id`, `bank_name`, `balance`, `b_date`, `delete_state`) values('3','HABIB BANK LIMITED','1134484','2016-10-10','0'); </code></pre> <p>cheque table</p> <pre><code>create table `cheque` ( `ch_id` int , `bank_id` int , `amount` double , `status` int, `delete_state` double ); insert into `cheque` (`ch_id`, `bank_id`, `amount`, `status`, `delete_state`) values('4','1','15000','2','0'); insert into `cheque` (`ch_id`, `bank_id`, `amount`, `status`, `delete_state`) values('9','1','250000','1','0'); </code></pre> <p>My MYSQL Query is</p> <pre><code>SELECT bk.*, SUM(amount) AS tot_amount, (bk.balance - SUM(amount)) AS bank_balance FROM banks bk LEFT JOIN cheque ch ON bk.bank_id = ch.bank_id WHERE ch.status = 1 AND bk.delete_state=0 AND ch.delete_state = 0 </code></pre> <p>I need to join these 2 tables and get from bank table all the bank_name's even though cheque table doesn't have any entry..</p> <p>But current my query is giving when cheque table having entry only, So its returning only one bank result.. please check and let me know where I'm missing!!</p>
<p>You need to group by bank_id. When you group a question you get the result for each value for the variable you group on.</p> <pre><code>SELECT bk.*, SUM(amount) AS tot_amount, (bk.balance - SUM(amount)) AS bank_balance FROM banks bk LEFT JOIN cheque ch ON (bk.bank_id = ch.bank_id AND ch.status = 1 AND ch.delete_state = 0) WHERE bk.delete_state=0 GROUP BY bk.bank_id; </code></pre> <p><a href="http://sqlfiddle.com/#!9/57901e/11" rel="nofollow">SQL Fiddle</a></p>
Redux - Reset state of subtree <p>What is the proper way to reset the subtree of a redux store? I'm not interested in resetting the entire redux store, but just the reducer subtree portion of it. </p> <p>Here is an example snippet:</p> <pre><code>//initial state const initialState = { isFetching: false, error: '', page: 0 } //reducer for suggestions store export default function suggestions (state = initialState, action) { switch (action.type) { case FETCHING_SUGGESTIONS : { return { ...state, isFetching: true } } case FETCHING_SUGGESTIONS_SUCCESS : { return { ...state, [action.suggestion.suggestionId] : action.suggestion } } case FETCHING_SUGGESTIONS_ERROR : { return { ...state, isFetching: false, error: "Error in fetching suggestions" } } case CHANGE_PAGE : { return { ...state, page: action.page } } case ADD_SUGGESTION : { return { ...state, [action.suggestion.suggestionId]: action.suggestion } } case CLEAR_SUGGESTIONS : { return { initialState } } default : return state } } </code></pre> <p>I would think this would work, however whenever the CLEAR_SUGGESTIONS action is dispatched, I suddenly get undefined props in some of my components and the following error: warning.js:36 Warning: performUpdateIfNecessary: Unexpected batch number (current 161, pending 157)</p> <p>I'm not 100% confident I'm doing this correctly. Can someone confirm if the issue is with my reducer, or somewhere along my components lifecycle methods?</p> <p>Thanks!</p>
<p>The object you create will look like this:</p> <pre><code>{ initialState: { isFetching: false, error: '', page: 0 } } </code></pre> <p>What you want is this:</p> <pre><code>case CLEAR_SUGGESTIONS : { return { ...initialState } } </code></pre>
Styling a checkbox without the label tag <p>I made a checkbox style and it uses the label tag. See below </p> <p>Is it possible to still have the CSS of the entire checkbox without the label tag? So i just have the Input tag, but still the CSS. Here is the CSS of the checkbox. </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>.control { font-size: 18px; position: relative; display: block; margin-bottom: 15px; padding-left: 30px; cursor: pointer; } .control input { position: absolute; z-index: -1; opacity: 0; } .control__indicator { position: absolute; top: 2px; left: 0; width: 20px; height: 20px; background: #e6e6e6; } .control--radio .control__indicator { border-radius: 50%; } .control:hover input ~ .control__indicator, .control input:focus ~ .control__indicator { background: #ccc; } .control input:checked ~ .control__indicator { background: orange; } .control:hover input:not([disabled]):checked ~ .control__indicator, .control input:checked:focus ~ .control__indicator { background: #ecb53a; } .control input:disabled ~ .control__indicator { pointer-events: none; opacity: .6; background: #e6e6e6; } .control__indicator:after { position: absolute; display: none; content: ''; } .control input:checked ~ .control__indicator:after { display: block; } .control--checkbox .control__indicator:after { top: 4px; left: 8px; width: 3px; height: 8px; transform: rotate(45deg); border: solid black; border-width: 0 2px 2px 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;label class="control control--checkbox"&gt; &lt;input type="checkbox"/&gt; &lt;div class="control__indicator"&gt;&lt;/div&gt; &lt;/label&gt;</code></pre> </div> </div> </p> <p>I hope you guys can help me out.</p>
<p>You can apply custom style to the checkbox using css <code>:after</code> , <code>:checked</code>.</p> <p>Please see below code or jsfiddle</p> <p>HTML</p> <pre><code>&lt;input type="checkbox"/&gt; </code></pre> <p>CSS</p> <pre><code> input[type='checkbox']:after{ line-height: 1.5em; content: ''; display: inline-block; width: 18px; height: 18px; margin-top: -4px; margin-left: -4px; border: 1px solid rgb(192,192,192); border-radius: 0.25em; background: rgb(224,224,224); } input[type='checkbox']:checked:after { width: 15px; height: 15px; border: 3px solid #00ff00; } </code></pre> <p>FIDDLE</p> <pre><code>https://jsfiddle.net/guruling/evfr3kk3/ </code></pre> <p>Hope this will help you to apply your checkbox custom styling.</p>
How to install local jar with dependencies in maven <p>I have a local jar (a maven plugin I wrote myself) which I am installing with</p> <pre><code>mvn org.apache.maven.plugins:maven-install-plugin:2.5.2:install-file -Dfile=dependencies/my-maven-plugin-1.0.jar </code></pre> <p>The plugin has some dependencies (defined in the pom.xml within the jar);</p> <pre><code>&lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.maven&lt;/groupId&gt; &lt;artifactId&gt;maven-plugin-api&lt;/artifactId&gt; &lt;version&gt;2.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.maven.plugin-tools&lt;/groupId&gt; &lt;artifactId&gt;maven-plugin-annotations&lt;/artifactId&gt; &lt;version&gt;3.2&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.yaml&lt;/groupId&gt; &lt;artifactId&gt;snakeyaml&lt;/artifactId&gt; &lt;version&gt;1.13&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.hubspot.jinjava&lt;/groupId&gt; &lt;artifactId&gt;jinjava&lt;/artifactId&gt; &lt;version&gt;2.1.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-io&lt;/groupId&gt; &lt;artifactId&gt;commons-io&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>But using the maven-install-plugin, these are not installed. Can I somehow install the needed dependencies automatically when installing the jar?</p>
<p>No, you can't do that. And it is normal: the <a href="http://maven.apache.org/plugins/maven-install-plugin/install-file-mojo.html" rel="nofollow"><code>maven-install-plugin</code></a> will install the file you pass it, which in this case is <code>my-maven-plugin-1.0.jar</code>, and that's it. It will also look inside the JAR to find a POM to install as well, because without a POM installed, the installed artifact won't be usable as a dependency.</p> <p>But it doesn't do it, because it isn't needed. Next time you depend on this artifact, with the coordinates written in the POM, Maven will automatically download the dependencies from your configured remote repositories (Maven Central by default) and install them in the local repository. There won't be the need to manually launch the <code>install-file</code> goal; this is only useful when the artifact isn't available on Maven repositories.</p> <p>If the <code>maven-install-plugin</code> would also install the dependencies of the artifact to manually install, it would just do the same thing Maven itself would do when you finally depend on that artifact in one of your projects.</p>
Unfixable memory leak <p>I apologize for the long code snippet ahead, but I spent a good while looking on here and I feel like nothing I've seen so far can help me solve this. I've asked questions on course forums, had TAs help, and have gotten suggestions from friends and nothing has been able to lock down the root of my problem here.</p> <p>In this program, I am using a tree to create a spell-checker. There are many things that need to be fixed in my code, but the memory leak is the only one I really need help figuring out.</p> <p>The issue is that I am fairly sure I am allocating the correct amount of space for my nodes, and I think Valgrind confirms this, because I only have 2 not-freed blocks (out of 365,371 allocs).</p> <p>Anyway, I will post the entirety of the code (in case anyone needs the full context), but the relevant parts I presume are the load function and the clear function, where I allocate and free the memory, respectively.</p> <pre><code>/** c* Implements a dictionary's functionality. */ #include &lt;ctype.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "dictionary.h" // number of characters we are using (a-z and ') #define LETTERS 27 // max guaranteed number of nonnegative char values that exist #define CHARVALUES 128 // create node structure for trie typedef struct node { struct node *children[LETTERS]; bool is_word; } node; // create root node for trie node *root; // stores the size of our dictionary unsigned int dict_size = 0; /** * Returns true if word is in dictionary else false. */ bool check(const char *word) { // keeps track of where we are; starts with root for each new word node *current_node = root; while (*word != '\0') { // indices: 'a' -&gt; 0, ..., 'z' -&gt; 25, '\' -&gt; 26 int index = (tolower(*word) - 'a') % CHARVALUES; if (index &gt;= LETTERS - 1) { // by assumption, the char must be '\'' if not '\n' or a letter index = LETTERS - 1; } // if the node we need to go to is NULL, the word is not here if (current_node-&gt;children[index] == NULL) { return false; } // go to the next logical node, and look at the next letter of the word current_node = current_node-&gt;children[index]; word++; } return current_node-&gt;is_word; } /** * Loads dictionary into memory. Returns true if successful else false. */ bool load(const char *dictionary) { FILE *inptr = fopen(dictionary, "r"); if (inptr == NULL) { return false; } // allocate memory for the root node root = malloc(sizeof(node)); // store first letter (by assumption, it must be a lowercase letter) char letter = fgetc(inptr); // stores indices corresponding to letters int index = 0; /** * we can assume that there is at least one word; we will execute the loop * and assign letter a new value at the end. at the end of each loop, due * to the inside loop, letter will be a newline; we know the EOF in the * dictionary follows a newline, so the loop will terminate appropriately */ do { // keeps track of where we are; starts with root for each new word node *current_node = root; // this loop will only execute if our character is a letter or '\'' while (letter != '\n') { // indices: 'a' -&gt; 0, ..., 'z' -&gt; 25, '\' -&gt; 26 index = (letter - 'a') % CHARVALUES; if (index &gt;= LETTERS - 1) { // by assumption, the char must be '\'' if not '\n' or a letter index = LETTERS - 1; } // allocate memory for a node if we have not done so already if (current_node-&gt;children[index] == NULL) { current_node-&gt;children[index] = malloc(sizeof(node)); // if we cannot allocate the memory, unload and return false if (current_node-&gt;children[index] == NULL) { unload(); return false; } } // go to the appropriate node for the next letter in our word current_node = current_node-&gt;children[index]; // get the next letter letter = fgetc(inptr); } // after each linefeed, our current node represents a dictionary word current_node-&gt;is_word = true; dict_size++; // get the next letter letter = fgetc(inptr); } while (letter != EOF); fclose(inptr); // if we haven't returned false yet, then loading the trie must have worked return true; } /** * Returns number of words in dictionary if loaded else 0 if not yet loaded. */ unsigned int size(void) { return dict_size; } void clear(node *head) { for (int i = 0; i &lt; LETTERS; i++) { if (head-&gt;children[i] != NULL) { clear(head-&gt;children[i]); } } free(head); } /** * Unloads dictionary from memory. Returns true if successful else false. */ bool unload(void) { clear(root); return true; } </code></pre> <p>The relevant valgrind output is the following:</p> <pre><code>==18981== HEAP SUMMARY: ==18981== in use at exit: 448 bytes in 2 blocks ==18981== total heap usage: 365,371 allocs, 365,369 frees, 81,843,792 bytes allocated ==18981== ==18981== 448 (224 direct, 224 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2 ==18981== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==18981== by 0x4011B0: load (dictionary.c:111) ==18981== by 0x4008CD: main (speller.c:40) ==18981== ==18981== LEAK SUMMARY: ==18981== definitely lost: 224 bytes in 1 blocks ==18981== indirectly lost: 224 bytes in 1 blocks ==18981== possibly lost: 0 bytes in 0 blocks ==18981== still reachable: 0 bytes in 0 blocks ==18981== suppressed: 0 bytes in 0 blocks ==18981== 1 errors in context 3 of 11: ==18981== ==18981== ==18981== Invalid read of size 8 ==18981== at 0x40120C: load (dictionary.c:123) ==18981== by 0x4008CD: main (speller.c:41) ==18981== Address 0xb3fde70 is 16 bytes before a block of size 224 alloc'd ==18981== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==18981== by 0x4011CB: load (dictionary.c:111) ==18981== by 0x4008CD: main (speller.c:41) ==18981== ==18981== ==18981== 1 errors in context 4 of 11: ==18981== Invalid read of size 8 ==18981== at 0x4011E0: load (dictionary.c:114) ==18981== by 0x4008CD: main (speller.c:41) ==18981== Address 0xb3fde70 is 16 bytes before a block of size 224 alloc'd ==18981== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==18981== by 0x4011CB: load (dictionary.c:111) ==18981== by 0x4008CD: main (speller.c:41) ==18981== ==18981== ==18981== 1 errors in context 5 of 11: ==18981== Invalid write of size 8 ==18981== at 0x4011D4: load (dictionary.c:111) ==18981== by 0x4008CD: main (speller.c:41) ==18981== Address 0xb3fde70 is 16 bytes before a block of size 224 alloc'd ==18981== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==18981== by 0x4011CB: load (dictionary.c:111) ==18981== by 0x4008CD: main (speller.c:41) ==18981== ==18981== ==18981== 1 errors in context 6 of 11: ==18981== Invalid read of size 8 ==18981== at 0x4011B2: load (dictionary.c:109) ==18981== by 0x4008CD: main (speller.c:41) ==18981== Address 0xb3fde70 is 16 bytes before a block of size 224 alloc'd ==18981== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==18981== by 0x4011CB: load (dictionary.c:111) ==18981== by 0x4008CD: main (speller.c:41) </code></pre> <p>So, my interpretation of this output is that, in the following block of code:</p> <pre><code> if (current_node-&gt;children[index] == NULL) { current_node-&gt;children[index] = malloc(sizeof(node)); // if we cannot allocate the memory, unload and return false if (current_node-&gt;children[index] == NULL) { unload(); return false; } } </code></pre> <p>the <code>malloc</code> statement (which is indeed line dictionary.c:111) is executed twice such that the allocated memory is never freed. (Is this correct?) Now, that leads me to think that the real problem lies with my clear function, i.e. that it is written poorly and does not clear every node of my trie.</p> <p>However, I've stared at the code for hours and I literally cannot see anything wrong with it. (I'm sure a lot is; I'm just not too good at this.)</p> <p>Any help with this would be greatly appreciated.</p> <p>As a sidenote: I've had multiple people (not course staff) tell me that I should initialize all of my pointers in the children array to NULL, but the course staff outright told me this was optional, and I have already tested it both ways with the same results. I know it's probably a portability thing even if it technically "works" like that, but just know that that is <em>not</em> the solution I am looking for, as I know there is some other root cause (i.e. one that causes it to not work on any device at all whatsoever...)</p> <p>Again, if you can help in any way with what is wrong with my logic here, I would greatly appreciate it. I have been trying to figure this out for hours to no avail.</p>
<pre><code>root = malloc(sizeof(node)); </code></pre> <p>This gives a chunk of uninitialized memory.</p> <pre><code>if (current_node-&gt;children[index] == NULL) </code></pre> <p>Here you assume that the memory has been initialized, while it is actually garbage.</p> <p>You need to initialize the contents of <code>root</code> before using them, or alternatively use calloc to set them all to zero.</p>
MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response <p>I got this error on an Exchange 2007 mailbox. I see it is returning the <code>BAD</code> response from the error which is thrown by MailKit:</p> <pre><code>The IMAP server replied to the 'EXAMINE' command with a 'BAD' response. </code></pre> <p>But this doesn't tell me enough detail. So I am running protocol logging, from which I can tell what the problem is. It says:</p> <pre><code>K00000005 BAD Duplicate folders "Conversation Action Settings", "News Feed", "Quick Step Settings", "Suggested Contacts" were detected in the mailbox. Therefore the user's connection was disconnected. </code></pre> <p>I would like to get this error text and display it to the user, so they can fix their mailbox (which they can do by deleting the duplicate folders, assuming they know which ones they are). Is there a simple way to get the full response text?</p> <p>Full protocol log as follows:</p> <pre><code>S: * OK Microsoft Exchange Server 2007 IMAP4 service ready C: K00000000 CAPABILITY S: * CAPABILITY IMAP4 IMAP4rev1 AUTH=NTLM AUTH=GSSAPI AUTH=PLAIN IDLE NAMESPACE LITERAL+ S: K00000000 OK CAPABILITY completed. C: K00000001 AUTHENTICATE NTLM ... S: K00000001 OK AUTHENTICATE completed. C: K00000002 CAPABILITY S: * CAPABILITY IMAP4 IMAP4rev1 AUTH=NTLM AUTH=GSSAPI AUTH=PLAIN IDLE NAMESPACE LITERAL+ S: K00000002 OK CAPABILITY completed. C: K00000003 NAMESPACE S: * NAMESPACE (("" "/")) NIL NIL S: K00000003 OK NAMESPACE completed. C: K00000004 LIST "" "INBOX" S: * LIST (\Marked \HasNoChildren) "/" INBOX S: K00000004 OK LIST completed. C: K00000005 EXAMINE INBOX S: K00000005 BAD Duplicate folders "Conversation Action Settings", "News Feed", "Quick Step Settings", "Suggested Contacts" were detected in the mailbox. Therefore the user's connection was disconnected. S: * BYE Connection is closed. 15 </code></pre>
<p>You can try parsing the <code>ImapCommandException.Message</code> property to get the text following the ':' character that is used in the exception message.</p> <p>I've also just added a <code>ResponseText</code> property to <code>ImapCommandException</code> so you can get this text w/o needing to parse it if you want to use MailKit built source.</p>
Get artifact for GAV from Artifactory <p>For given groupId, artifactId, version, classifier and type, how can I download the corresponding artifact using REST?</p>
<p>use the gavc search to get the URL and from there you can download the artefact:</p> <p>GAVC Search</p> <blockquote> <p>Description: Search by Maven coordinates: GroupId, ArtifactId, Version &amp; Classifier. Search must contain at least one argument. Can limit search to specific repositories (local and remote-cache). Since: 2.2.0 Security: Requires a privileged user (can be anonymous) Usage: GET /api/search/gavc?[g=groupId][&amp;a=artifactId][&amp;v=version][&amp;c=classifier][&amp;repos=x[,y]]</p> <p>Headers (Optionally): X-Result-Detail: info (To add all extra information of the found artifact), X-Result-Detail: properties (to get the properties of the found artifact), X-Result-Detail: info, properties (for both). Produces: application/vnd.org.jfrog.artifactory.search.GavcSearchResult+json</p> <p>Sample Output:</p> </blockquote> <pre><code>GET /api/search/gavc?g=org.acme&amp;a=artifact&amp;v=1.0&amp;c=sources&amp;repos=libs-release-local { "results": [ { "uri": "http://localhost:8080/artifactory/api/storage/libs-release-local/org/acme/artifact/1.0/artifact-1.0-sources.jar" },{ "uri": "http://localhost:8080/artifactory/api/storage/libs-release-local/org/acme/artifactB/1.0/artifactB-1.0-sources.jar" } ] } </code></pre> <p>Taken from the <a href="https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API" rel="nofollow">API-Documenation</a>.</p>
Java List.addAll using collection's stream instead of using collection itself? <p>Recently I found a code snippet which uses stream in List.addAll, but I can't see the reason why it was used.</p> <p>So given a simple list. <code>List&lt;E&gt; subList</code> which is passed as argument to a method. There is a is an other which is a field and contains the same type of elements. <code>List&lt;E&gt; originalList.</code> </p> <p>Here is the the part when the original list is extended with the elements of the sublist.</p> <pre><code>originalList.addAll(subList.stream().collect(Collectors.toList())) </code></pre> <p>What I don't get: why did the author used stream here instead of doing the following:</p> <pre><code>originalList.addAll(subList) </code></pre> <p>Is there a benefit of using streams in this situation?</p>
<p>There is no difference at all, using <code>originalList.addAll(subList)</code> will do exactly the same because <code>addAll()</code> method creates an array copy of <code>subList</code> in memory and does not point to the same reference. Perhaps there was some intermediate operation in the <code>Stream</code> which was cleared and author forgot to clean-up the code.</p> <p>Use <code>originalList.addAll(subList)</code> as there is no need to create a stream and collect it to <code>List</code>, it's just unnecessary operations. </p>
Python SQLITE3 Inserting Backwards <p>I have a small piece of code which inserts some data into a database. However, the data is being inserting in a reverse order.<br> If i "commit" after the for loop has run through, it inserts backwards, if i "commit" as part of the for loop, it inserts in the correct order, however it is much slower.<br> How can i commit after the for loop but still retain the correct order? </p> <pre><code>import subprocess, sqlite3 output4 = subprocess.Popen(['laZagne.exe', 'all'], stdout=subprocess.PIPE).communicate()[0] lines4 = output4.splitlines() conn = sqlite3.connect('DBNAME') cur = conn.cursor() for j in lines4: print j cur.execute('insert into Passwords (PassString) VALUES (?)',(j,)) conn.commit() conn.close() </code></pre>
<p>You can't rely on <em>any</em> ordering in SQL database tables. Insertion takes place in an implementation-dependent manner, and where rows end up depends entirely on the storage implementation used and the data that is already there.</p> <p>As such, no reversing takes place; if you are selecting data from the table again and these rows come back in a reverse order, then that's a coincidence and not a choice the database made.</p> <p>If rows must come back in a specific order, use <code>ORDER BY</code> when selecting. You could order by <code>ROWID</code> for example, which <em>may</em> be increasing monotonically for new rows and thus give you an approximation for insertion order. See <a href="http://sqlite.org/lang_createtable.html#rowid" rel="nofollow"><em>ROWIDs and the INTEGER PRIMARY KEY</em></a>.</p>
One of threads rewrites console input in Python <p>I have a problem with console app with threading. In first thread i have a function, which write symbol "x" into output. In second thread i have function, which waiting for users input. (Symbol "x" is just random choice for this question).</p> <p>For ex.</p> <p>Thread 1:</p> <pre> while True: print "x" time.sleep(1) </pre> <p>Thread 2:</p> <pre> input = null while input != "EXIT": input = raw_input() print input </pre> <p>But when i write text for thread 2 to console, my input text (for ex. HELLO) is rewroted. </p> <pre> x x HELx LOx x x[enter pressed here] HELLO x x </pre> <p>Is any way how can i prevent rewriting my input text by symbol "x"?</p> <p>Thanks for answers.</p>
<p>In a console, standard output (produced by the running program(s)) and standard input (produced by your keypresses) are both sent to screen, so they may end up all mixed.</p> <p>Here your thread 1 writes 1 <code>x</code> by line every second, so if your take more than 1 second to type <code>HELLO</code> then that will produce the in-console output that you submitted.</p> <p>If you want to avoid that, a few non-exhaustive suggestions:</p> <ul> <li><p>temporarily interrupt thread1 output when a keypress is detected</p></li> <li><p>use a library such as ncurses to create separates zones for your program output and the user input</p></li> <li><p>just suppress thread1 input, or send it to a file instead.</p></li> </ul>
Cordova: can't use remote page as content for iOS CDVViewController <p>I'm trying to add Ionic 2 app as part of the native iOS application. As I found, CDVViewController should be used for integration.</p> <ul> <li>have Xcode 7.3.1</li> <li>installed <code>pod 'Cordova', '4.2.1'</code></li> <li>added <code>config.xml</code> which Ionic generated (not adding other files, because I need to display remote content)</li> <li>replaced <code>&lt;content src="index.html" /&gt;</code> with <code>&lt;content src="http://localhost:8100/" /&gt;</code> in config.xml as their documentation says to do for remote content.</li> <li>added <code>localhost</code> to App Transport Security exceptions (I tested it in another UIWebView and it's definitely working)</li> </ul> <p>After all that CDVViewController still doesn't display my remote URL. Tried in many different ways with no luck.. Tried to navigate with JS — not working. Tried another domains as <a href="https://github.com" rel="nofollow">https://github.com</a>. CDVViewController definitely see my <code>config.xml</code> and drops errors if it not there. If I replace back to <code>&lt;content src="index.html" /&gt;</code> (and add index.html to resources), it displays that index page, no problems.</p>
<p>Finally found: needed to add <code>&lt;allow-navigation href="..." /&gt;</code> tag. In my case it was <code>&lt;allow-navigation href="http://localhost" /&gt;</code>. </p> <p>Check <a href="https://github.com/apache/cordova-plugin-whitelist#navigation-whitelist" rel="nofollow">https://github.com/apache/cordova-plugin-whitelist#navigation-whitelist</a></p>
AVAudioPlayerNode doesn't play sound <p>I'm trying to generate sound with code below. Everthing is fine there is no error. But when I executed this code, there is no sound. How can I fix this problem ? </p> <p>By the way, I'm using this example : <a href="http://www.tmroyal.com/playing-sounds-in-swift-audioengine.html" rel="nofollow">http://www.tmroyal.com/playing-sounds-in-swift-audioengine.html</a></p> <pre><code>var ae:AVAudioEngine var player:AVAudioPlayerNode? var mixer:AVAudioMixerNode var buffer:AVAudioPCMBuffer ae = AVAudioEngine() player = AVAudioPlayerNode() mixer = ae.mainMixerNode; buffer = AVAudioPCMBuffer(pcmFormat: player!.outputFormat(forBus:0), frameCapacity: 100) buffer.frameLength = 100 // generate sine wave. var sr:Float = Float(mixer.outputFormat(forBus:0).sampleRate) var n_channels = mixer.outputFormat(forBus:0).channelCount var i:Int=0 while i &lt; Int(buffer.frameLength) { var val = sinf(441.0*Float(i)*2*Float(M_PI) / Float(sr)) buffer.floatChannelData?.pointee[i] = val * 0.5 i+=Int(n_channels) } // setup audio engine ae.attach(player!) ae.connect(player!, to: mixer, format: player!.outputFormat(forBus: 0)) ae.prepare() try! ae.start() // play player and buffer player!.scheduleBuffer(buffer, at: nil, options: .loops, completionHandler: nil) player!.play() </code></pre>
<p>Your <code>AVAudioEngine</code> looks like it's a local variable - that will go out of scope and be deallocated. Assign it to a class instance variable and maybe you'll hear some sound.</p>
Service Bus (On Premise) (1.1) and "High Availability" : Connection String <p>I have a question about Service Bus (On Premise) (1.1) and "High Availability".</p> <p>Below are 2 images from Microsoft. From this article </p> <p><a href="https://msdn.microsoft.com/en-us/library/jj193012%28v=azure.10%29?f=255&amp;MSPPError=-2147217396" rel="nofollow">https://msdn.microsoft.com/en-us/library/jj193012%28v=azure.10%29?f=255&amp;MSPPError=-2147217396</a></p> <p>My question is the "connection string" to Service Bus.</p> <p>I have locally setup 3 machines on my Farm. Machine1A(the very first thing I installed SB on) and then adding on 2 more machines for the farm. "Machine2" and "Machine3"</p> <p>However, my connection string (from my clients) is pointing to Machine1A.</p> <pre><code>Endpoint=sb://Machine1A.fullyqualified.domain.name.com/ServiceBusDefaultNamespace;StsEndpoint=https://Machine1A.fullyqualified.domain.name.com:9355/ServiceBusDefaultNamespace;RuntimePort=9354;ManagementPort=9355 </code></pre> <p>I don't understand, if Machine1A does down..........clients cannot connect to it.</p> <p>Is there a "farm" connection string? Can the only machines that crash...be Machine2 and Machine3 (Machines 2-N) ?</p> <p>What connection string (fully qualified machine name) do I use for High Availability?</p> <p><a href="http://i.stack.imgur.com/wtBeB.gif" rel="nofollow"><img src="http://i.stack.imgur.com/wtBeB.gif" alt="3 machines on Farm"></a></p> <p><a href="http://i.stack.imgur.com/1sQQI.gif" rel="nofollow"><img src="http://i.stack.imgur.com/1sQQI.gif" alt="If one machine on Farm goes down"></a></p> <p>Other articles I've read on this subject:</p> <p><a href="http://www.planetgeek.ch/2014/12/10/service-bus-for-windows-server-high-availability/" rel="nofollow">http://www.planetgeek.ch/2014/12/10/service-bus-for-windows-server-high-availability/</a></p> <p><a href="https://haishibai.blogspot.com/2012/08/walkthrough-setting-up-development.html" rel="nofollow">https://haishibai.blogspot.com/2012/08/walkthrough-setting-up-development.html</a></p> <p>"Scaling" (Below url)</p> <p><a href="https://msdn.microsoft.com/en-us/library/dn441424.aspx?f=255&amp;MSPPError=-2147217396" rel="nofollow">https://msdn.microsoft.com/en-us/library/dn441424.aspx?f=255&amp;MSPPError=-2147217396</a></p> <p><a href="https://blogs.technet.microsoft.com/meamcs/2013/12/08/recommended-practices-service-bus-for-windows-server/" rel="nofollow">https://blogs.technet.microsoft.com/meamcs/2013/12/08/recommended-practices-service-bus-for-windows-server/</a></p> <p><em>"Make sure it is highly available (HA): HA can be fully satisfied only when both service and database layers are HA. Service layer HA can be accomplished by having at least 3 servers in the ring. .................. Please note that Service bus v1.1 supports up-to 5 servers in the ring"</em></p>
<pre><code>To get ConnectionString Use the following cmdlet Get-SBAuthorizationRule -Namespace YourNamespaceName You have to Export and import the certificates to use the same connectionstring in your client machine. </code></pre> <p>For Your Reference: <a href="https://msdn.microsoft.com/en-us/library/jj192993.aspx" rel="nofollow">click here..</a></p>
How to find the product categories with subcategories and so on in wordpress? <p>Here i get 2-level categories of product but i want more than 2.Like prodA->proda1->proda11 </p> <pre><code>$taxonomy = 'product_cat'; $all_categories = get_categories(array( "taxonomy" =&gt;"product_cat","parent" =&gt; 0)); echo "&lt;pre&gt;"; print_r($all_categories); die(); foreach ($all_categories as $cat) { echo $category_id = $cat-&gt;term_id; echo "parent name ==". $cat-&gt;name; $sub = get_categories(array("taxonomy" =&gt; "product_cat", "parent" =&gt; $category_id)); echo "&lt;pre&gt;"; print_r($sub); } </code></pre>
<p>Please use this code becuase of if you not added <code>hide_empty =&gt; 0</code> then some unattached category product are not showing in your dropdown.</p> <pre><code>$args = array( 'type' =&gt; 'product', 'child_of' =&gt; 0, 'parent' =&gt; '', 'orderby' =&gt; 'term_group', 'hide_empty' =&gt; false, 'hierarchical' =&gt; 1, 'exclude' =&gt; '', 'include' =&gt; '', 'number' =&gt; '', 'taxonomy' =&gt; 'product_cat', 'pad_counts' =&gt; false ); $cats = get_categories( $args ); </code></pre> <p>other parameter as per your requirement not to mandatory.</p>
PHP populated dropdown, onchange populate different dropdown based on value <p>Hi so the here is my question,</p> <p>I have a Database containing Categories and Subcategories. I have two dropdown boxes (select). I want them both to be populated by using PHP/MYSQL.</p> <p>My Categories have been generated:</p> <pre><code>&lt;select name="prod_cat"&gt; &lt;?php include("php/dbconnect.php"); $sql = "SELECT * FROM categories"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) &gt; 0){ while ($row = mysqli_fetch_array($result)) { echo '&lt;option value="'. $row["cat_name"] .'"&gt;'. $row["cat_name"] .'&lt;/option&gt;'; } } else{echo "No categories were found!";} mysqli_close($conn); ?&gt; &lt;/select&gt; </code></pre> <p><a href="http://i.stack.imgur.com/ecTTx.png" rel="nofollow"><img src="http://i.stack.imgur.com/ecTTx.png" alt="browser preview of dropdown boxes"></a></p> <p>I want the subcategories to load when the category has changed. My SQL will look something like this:</p> <pre><code>SELECT subcat_name FROM subcategories WHERE cat_name = '$prod_cat' </code></pre> <p>I need to get the value from the categories dropdown and store it as a variable. In the past I have done something similar in javascript:</p> <pre><code>var subcat=document.forms["form"]['subcat'].value; </code></pre> <p>and then changed the value of another dropdown by calling an onChange(); function like:</p> <pre><code>document.getElementById('subcat').innerHTML='&lt;option value=""&gt;&lt;/option&gt;'; </code></pre> <p>I hope someone can point me in the right direction! Should I be looking into AJAX, JavaScript or can it all be done with PHP?</p> <p>Thank you.</p>
<p>add an id on category select box , like this -</p> <pre><code>&lt;select name="prod_cat" id="prod_cat"&gt; &lt;?php include("php/dbconnect.php"); $sql = "SELECT * FROM categories"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) &gt; 0){ while ($row = mysqli_fetch_array($result)) { echo '&lt;option value="'. $row["cat_name"] .'"&gt;'. $row["cat_name"] .'&lt;/option&gt;'; } } else{echo "No categories were found!";} mysqli_close($conn); ?&gt; &lt;/select&gt; </code></pre> <p>for subcategory -</p> <pre><code>&lt;select id='sub_cat' name='sub_cat'&gt;&lt;/select&gt; </code></pre> <p>write your script something like this - </p> <pre><code>&lt;script&gt; $("#prod_cat").change(function(){ //get category value var cat_val = $("#prod_cat").val(); // put your ajax url here to fetch subcategory var url = 'www.example/fetch_subcategory.php'; // call subcategory ajax here $.ajax({ type:"POST", url:url, data:{ cat_val : cat_val }, success:function(data) { $("#sub_cat").html(data); } }); }); &lt;/script&gt; </code></pre> <p>add code in ajax calling page -'www.example/fetch_subcategory.php'</p> <pre><code>&lt;?php $prod_cat = $_POST['cat_val']; $sql = "SELECT subcat_name FROM subcategories WHERE cat_name = '$prod_cat'"; $result = mysqli_query($conn, $sql); $msg =''; if (mysqli_num_rows($result) &gt; 0){ while ($row = mysqli_fetch_array($result)) { $msg =.'&lt;option value="'. $row["sub_cat_name"] .'"&gt;'. $row["sub_cat_name"] .'&lt;/option&gt;'; } } else{$msg .="No categories were found!";} echo $msg; mysqli_close($conn); ?&gt; </code></pre> <p>Do something like this, and hope it will work for you.</p>
i cannot round up and get it for my GTIN <pre><code>import random r1 = (random.randint(0,9)) r2 = (random.randint(0,9)) r3 = (random.randint(0,9)) r4 = (random.randint(0,9)) r5 = (random.randint(0,9)) r6 = (random.randint(0,9)) r7 = (random.randint(0,9)) print ("your item barcode number is", r1,r2,r3,r4,r5,r6,r7) r8 = (r1*3+r2*1+r3*3+r4*1+r5*3+r6*1+r7*3) roundup = round(r8, -1) print (r8) print(roundup) GTIN = (roundup-r8) if GTIN&lt;0: GTIN = (r8-roundup) print("the GTIN number is", GTIN) print(r1,r2,r3,r4,r5,r6,r7,GTIN) </code></pre> <p>i can't get it to round up to the higher ten somebody help so basically i want it to be like 44 rounds up to 50 unless the number is a mutiple of 10 somebody help me do it</p>
<pre><code>def round_up_by_ten(num): return num if not num%10 else ((num//10)+1)*10 </code></pre>
vpn service that use akamai servers <p>is it possible to host a vpn or a proxy on akamai servers and is there any available vpn services that host it servers on akamai I tried googling but it throw in another whole direction</p>
<p>@Rahim, As far as i am aware akamai doesn't host vpn servers, but there are other CDN providers which do provide this feature.</p> <p>If you are looking something within akamai then i suggest you contact the customer care, even though vpn server hosting might not be available but they will guide if you there are other approaches within akamai that you can use. </p>
Convert tabulated column to array <p>My input is copied from a HTML table and looks like this in text format:</p> <p>1 2 3</p> <p>4 5 6</p> <p>(imagine 'tabs' instead of the spaces)</p> <p>The String would become then:</p> <p>1\t\2\t3\r\n4\t5\t6</p> <p>How can I create an array so that:</p> <p>myArray(0,0) returns 1 myArray(0,1) returns 2 myArray(1,0) returns 4</p> <p>I have tried this:</p> <pre><code>String input = Clipboard.GetText(); String[] content = input.Split(("\t").ToCharArray()); </code></pre> <p>but this creates an array with the following elements: 1 2 3\r\n 4 5 6</p> <p>-- Thank you... -- </p>
<p>Since you know how to split it at the tabs, you can split it at the line break too.</p> <pre><code>stringIs = 1\t\2\t3\r\n4\t5\t6 firstSplit = stringIs.split("\r\n"); </code></pre> <p>Now you have an array with two elements.</p> <pre><code>firstSplit[0] = "1\t\2\t3"; firstSplit[1] = "4\t5\t6"; </code></pre> <p>So just split those the same way into a new array.</p>
Preprocessor definitions not working in C <p>I've been frantically trying to get this following code to work. The preprocessor definitions WIDR and LIDR aren't working and it's giving me the compile error: </p> <pre><code>projects/elcain.c: In function ‘main’: projects/elcain.c:17:6: error: ‘WIDR’ undeclared (first use in this function) if ( WIDR ) { ^ projects/elcain.c:17:6: note: each undeclared identifier is reported only once for each function it appears in projects/elcain.c:19:13: error: ‘LIDR’ undeclared (first use in this function) } else if ( LIDR ) { </code></pre> <p>I don't really have experience with preprocessor macros, or the preprocessor in general, so go easy on me. </p> <p>Here's the code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #ifdef _WIN32 #define WIDR 1 #elif defined _linux_ #define LIDR 1 #endif int main () { char* directory = (char*) malloc (1); if ( WIDR ) { strcpy(directory, "C:\\TEMP\\"); } else if ( LIDR ) { strcpy(directory, "~/.temp/"); } else { *directory = 0x00; } printf("%s\n", directory); return 0; } </code></pre>
<p>You probably simply want this:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; int main () { #ifdef _WIN32 char directory[] = "C:\\TEMP\\"; #elif defined _linux_ char directory[] = "~/.temp/"; #else #error Neither _WIN32 nor _linux_ are defined #endif printf("%s\n", directory); return 0; } </code></pre>
How to use ajax in Rails for destroy method? <p>I want to make an option "delete" for my items based on ajax.</p> <p>items_controller:</p> <pre><code>def destroy @item.destroy respond_to do |format| format.js { render :layout =&gt; false } end end </code></pre> <p>destroy.js.erb:</p> <pre><code>$('div#item_&lt;%= item.id %&gt;').bind('ajax:success', function() { $(this).fadeOut(); }); </code></pre> <p>_item.html.erb:</p> <pre><code>&lt;div class='item' id="item_&lt;%= item.id %&gt;"&gt; &lt;span class="item_image"&gt;&lt;%= image_tag item.image.url(:thumb) %&gt;&lt;/span&gt; &lt;span class="price"&gt;&lt;%= item.price %&gt;&lt;/span&gt; &lt;span class="item_name"&gt; &lt;br&gt; &lt;%= item.name %&gt; &lt;/span&gt; &lt;br&gt; &lt;span class="small-text text-center"&gt; &lt;% str = item.short_description %&gt; &lt;%= str[0..70] + "..." if str %&gt; &lt;/span&gt; &lt;br&gt; &lt;div class="small-2 large-4 columns rating_stars"&gt; &lt;% if true %&gt; &lt;%= rating_for item, "rating", half_show: true, cancel_place: :right %&gt; &lt;% end %&gt; &lt;/div&gt; &lt;div class='to_cart'&gt; &lt;%= link_to 'В корзину', to_cart_item_path(item), method: :put, class: 'a_to_cart' %&gt; &lt;/div&gt; &lt;span class='delete_my'&gt; &lt;%= link_to 'delete', item, method: :delete, remote: true %&gt; &lt;/span&gt; &lt;/div&gt; </code></pre> <p>Tell me please, what I do wrong? I'm very bad in ajax and js.</p>
<p>It looks like your <code>destroy.js.erb</code> file is wrong. You are attaching an event handler when you just need to simply remove the line. Change your file to:</p> <pre><code>$('div#item_&lt;%= @item.id %&gt;').fadeOut(); </code></pre> <p>Now, you could also make a check to see if the item truly has been deleted:</p> <pre><code>&lt;% if @item.destroyed? %&gt; $('div#item_&lt;%= @item.id %&gt;').fadeOut(); &lt;% else %&gt; #Do something &lt;% end %&gt; </code></pre>
In AutoCompleteTextView apply on item click listner returns always id as a 1 <p><strong>This is my json responce :-</strong></p> <pre><code>{ "ReplyCode": 1, "Message": "Franchisee and Plans List", "data2": [ { "StateId": 1, "StateName": "Andaman and Nicobar Island", "CountryId": 1 }, { "StateId": 2, "StateName": "Andhra Pradesh", "CountryId": 1 }, { "StateId": 3, "StateName": "Arunachal Pradesh", "CountryId": 1 }, { "StateId": 4, "StateName": "Assam", "CountryId": 1 }, </code></pre> <p><strong>This is my method by which i am fetching data from the json :-</strong></p> <pre><code> public void volleyStatedata() { if (mGeneralUtilities.isConnected()) { mProgressDialog.show(); StringRequest stateRequest = new StringRequest(Request.Method.POST, GlobalData.REGISTER_DATA_URL, new Response.Listener&lt;String&gt;() { @Override public void onResponse(String response) { mProgressDialog.dismiss(); try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("data2"); for (int i = 0; i &lt; jsonArray.length(); i++) { PojoState pojoState = new PojoState(); JSONObject jsonObject1 = jsonArray.getJSONObject(i); String stateId = jsonObject1.getString("StateId"); String stateName = jsonObject1.getString("StateName"); mStateList.add(stateName); mStateIdList.add(stateId); pojoState.setmStateId(stateId); pojoState.setmStatename(stateName); mpojoStateList.add(pojoState); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Log.e("error", "" + volleyError.getMessage()); } }) { @Override protected Map&lt;String, String&gt; getParams() throws AuthFailureError { Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;(); return params; } }; RequestQueue stateQueue = Volley.newRequestQueue(getContext()); stateQueue.add(stateRequest); } else { mGeneralUtilities.showAlertDialog("Hey User !", "Please connect to the internet", "Ok"); } } </code></pre> <p><strong>This is my Adapter where i am setting it to the autocompletetextview :-</strong></p> <pre><code> ArrayAdapter&lt;String&gt; mAdapter = new ArrayAdapter&lt;String&gt;(getContext(), android.R.layout.simple_list_item_1, mStateList); mActState.setAdapter(mAdapter); mActState.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; adapterView, View view, int i, long l) { mpojoStateList.get(i).getmStateId(); } }); </code></pre> <p>My problem is autocompletetextview always return id 1.i am applying onitemclick listner on it.but it is getting id 1 always.i want to id accordingly to the state as per shown my json.Can anyone tell me how can I achieve this ??</p>
<p>Your code uses <code>i</code> that returns in the <code>onItemClick</code> callback, which refers to the item you clicked from the visible items in the auto-complete list, not your original list. When you click on the first item in the auto-complete list, <code>i=0</code>, which means it always returns the "<em>Andaman and Nicobar Island</em>" item whose <code>StateId=1</code>.</p> <p>Off the top of my head, you can get the item String from the <code>mAdapter</code> and compare it to your <code>mpojoStateList</code> and find the corresponding item. (Check the sample code)</p> <pre><code> final ArrayAdapter&lt;String&gt; mAdapter = new ArrayAdapter&lt;String&gt;(getContext(), android.R.layout.simple_list_item_1, mStateList); mActState.setAdapter(mAdapter); mActState.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; adapterView, View view, int i, long l) { String itemName = mAdapter.getItem(i); for (PojoState pojo : mpojoStateList) { if (pojo.mStateName.equals(itemName)) { String id = pojo.getmStateId(); // This is the correct ID break; // No need to keep looping once you found it. } } } }); </code></pre> <p>It also is better if, inside your <code>PojoState</code> object, you override your <code>toString()</code> method and make it return the <code>mStateName</code>, and pass the <code>mpojoStateList</code> to the adapter without having to make 3 <code>ArrayLists</code>. That way, <code>mAdapter.getItem(i)</code> will return a <code>PojoState</code> object instead of a String, and you can use its ID without referring to the returned position (<code>i</code>).</p>
Single OnClickListener for multiple ViewHolders <p>My <code>ViewHolder</code> (inner) class:</p> <pre><code>static class HostViewHolder extends RecyclerView.ViewHolder { ImageButton button1; ImageButton button2; HostViewHolder(View listItemView) { super(listItemView); button1 = (ImageButton) listItemView.findViewById(R.id.button1); button2 = (ImageButton) listItemView.findViewById(R.id.button2); } } </code></pre> <p>In <code>onBindViewHolder()</code> i attach <code>OnClickListener</code>s to the <code>Button</code>s the following way:</p> <pre><code>@Override public void onBindViewHolder(final HostViewHolder holder, int position) { holder.button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = holder.getAdapterPosition(); // doing something using the value of pos } }); holder.button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = holder.getAdapterPosition(); // doing some other thing using the value of pos } }); } </code></pre> <p>It's working fine, but my problem with this approach is i'm creating a new <code>OnClickListener</code> instance for every <code>ViewHolder</code>, which feels kinda redundant.</p> <p>I would like to create a <strong>single</strong> <code>OnClickListener</code> instance to use, but i cannot access the <code>position</code> and <code>holder</code> params of <code>onBindViewHolder()</code> that way.</p> <p>Is this possible to achieve? If so, how?</p> <p>Thanks in advance.</p>
<p>You can attach onClickListener in the ViewHolder class itself.</p> <pre><code>static class HostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ ImageButton button1; ImageButton button2; HostViewHolder(View listItemView) { super(listItemView); button1 = (ImageButton) listItemView.findViewById(R.id.button1); button2 = (ImageButton) listItemView.findViewById(R.id.button2); button1.setOnClickListener(this); button2.setOnClickListener(this); } @Override public void onClick(View v) { int position = getAdapterPosition(); switch (v.getId()){ //handle clicks } } } </code></pre>
Semantic git message and cleaning <p>In one of my node code, I must do some cleaning. For example removing unused <code>console.log()</code> functions or comments placed here during dev/debugging phase by my coworker.</p> <p>I try to follow some semantic git message rules, for cleaning, as mentioned <a href="http://karma-runner.github.io/0.10/dev/git-commit-msg.html" rel="nofollow">here</a>. </p> <p>For example deleting useless console.log or debugging stuff like:</p> <pre><code>console.log('Starting app.js'); debugger; </code></pre> <p><strong>What kind of git message type should I use?</strong> Certainly not <code>feat:</code> as it's not a new feature. I'd go maybe with <code>refactor:</code>.</p>
<p>I'd go with <code>chore</code>, since this will not change the way the "production" code work.</p> <p>This is not a feature, not a bugfix, not a style change... so this is kind of a default choice, but it seems right.</p>
AngularJS: How to create and use an array for a value in the HTML <p>I have created a custom directive with fields: <code>ng-model</code>, <code>input-array</code></p> <pre><code>&lt;mydir ng-model="myBinding" input-array="input1,input2"&gt;&lt;/mydir&gt; </code></pre> <p>Input 1 and input 2 are both data bindings, how can I dynamically create an array of these two and pass then in the <code>input-array</code> argument?</p> <p>I do not want this logic to be in a controller or the directive.</p>
<p>Just wrap the variables in array braces</p> <pre><code>input-array="[input1,input2]" </code></pre> <p>Beyond that there isn't nearly enough detail in question</p>
Yield continue? <p>There's <code>yield return</code> to return the next element in the collection and then there's <code>yield break</code> to end the iteration. Is there a sort of <code>yield continue</code> to tell the loop controller to skip to the next element?</p> <p>Here's what I am trying to achieve, though it obviously doesn't build:</p> <pre><code>static IEnumerable&lt;int&gt; YieldTest() { yield return 1; yield return 2; yield continue; yield return 4; } </code></pre>
<p>There is no need to have a separate <code>yield continue</code> statement. Just use <code>continue</code> or any other conditional statement to skip the element as you need within your enumeration algorithm. </p> <p>The enumeration algorithm that uses <code>yield</code> is internally transformed into a state machine by the compiler, which can the be invoked several times. The point of <code>yield</code> is that it generates an output, effectively pausing / stopping the state machine at the place where it's used. The effect of a possible <code>yield continue</code> would be none at all in respect to the behavior of the state machine. Hence it is not needed.</p> <p>Example:</p> <pre><code>static IEnumerable&lt;int&gt; YieldTest() { for (int value = 1; value &lt;= 4; value++) { if (value == 3) continue; // alternatively use if (value != 3) { … } yield return value; } } </code></pre>
CSS Dropdown menu not working? <p>I've been following this video online on how to create dropdown menu using css. I followed it and there's no any signs of a dropdown menu on my website. It's so frustrating because i want to get over with it so i can focus now on backend dev. Hope you guys can figure this one out.</p> <p>Code for html:</p> <pre><code> &lt;!DOCTYPE&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;MUSIC STORE&lt;/title&gt; &lt;script src="js/jquery-1.11.2.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="jquery.bxslider.css"/&gt; &lt;link rel="stylesheet" href="styles.css"/&gt; &lt;link rel="shortcut icon" type="image/png" href="../Music Store/img/rockSign.png"/&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrapper"&gt; &lt;header id="main_header"&gt; &lt;div id="callout"&gt; &lt;h2&gt;&amp;#9742; 111222333&lt;/h2&gt; &lt;p&gt;Michigan State Kawasaki Iceland&lt;/p&gt; &lt;/div&gt; &lt;h1&gt;MUSIC STORE&lt;/h1&gt; &lt;/header&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;nav id="nav_menu"&gt; &lt;ul id="nav"&gt; &lt;li&gt;&lt;a href="#"&gt;HOME&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;INSTRUMENTS&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;ELECTRIC GUITARS&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;BASS GUITARS&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;DRUMS&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;AMPLIFIERS&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;ACCESSORIES&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;FEATURED ARTISTS&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;script src="js/jquery.bxslider.min.js"&gt;&lt;/script&gt;&lt;!--For Image Slider--&gt; &lt;div class="slide-wrap"&gt; &lt;div class="slider"&gt; &lt;ul class="slider1"&gt; &lt;li&gt;&lt;img src="../Music Store/img/ibanez.jpg"/&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="../Music Store/img/raven.jpg"/&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="../Music Store/img/metallica.jpg"/&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; $('.slider1').bxSlider({ mode: 'fade', captions: false, auto:true, pager:false, }); $('.slider2').bxSlider({ pager:false, captions: true, maxSlides: 3, minSlides: 1, slideWidth: 230, slideMargin: 10 }); $('.slider3').bxSlider({ mode: 'fade', captions: false, auto:true, pager:false, controls:false, }); &lt;/script&gt; &lt;section class="one-third"&gt; &lt;div class="border_section"&gt; &lt;h3&gt;NEW BASS AMPS THIS YEAR&lt;/h3&gt; &lt;img src="../Music Store/img/fender_amps_bassbreaker.jpg"/&gt; &lt;p&gt;We would like to proudly announce the new shipment of fender bass amps that you all have been waiting for. It will provide you that rich rock and roll tone like no other. Please check out our bass amp section for more details.&lt;/p&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class="one-third"&gt; &lt;div class="border_section"&gt; &lt;h3&gt;NEW FEATURE ARTIST&lt;/h3&gt; &lt;img src="../Music Store/img/feature_markHolcomb.jpg"/&gt; &lt;p&gt;Behold Mark Holcomb from Periphery is in the house! Check out his info and new signature guitar at our feature artists section. He will also be having a 20-minute guitar clinic on Oct 8 2016 right here at Music Store.&lt;/p&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class="one-third"&gt; &lt;div class="border_section"&gt; &lt;h3&gt;ATTENTION VOCALISTS!&lt;/h3&gt; &lt;img src="../Music Store/img/GoMic.jpg"/&gt; &lt;p&gt;Check out the new Samson Go Mic Connect. It has a top-notch noise cancellation feature that can definitely minimize the annoying sound that your dog makes while your recording. For more details, Go to Accessories section.&lt;/p&gt; &lt;/div&gt; &lt;/section&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;footer&gt; &lt;p&gt;&amp;copy;All Rights Reserved&lt;/p&gt; &lt;/footer&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Code for CSS:</p> <pre><code>@import url(http://fonts.googleapis.com/css?family=Black+Ops+One:400,700); /*--- Header --*/ @import url(http://fonts.googleapis.com/css?family=Open+Sans:400,700); /*--- Navigation --*/ * { margin: 0; border: 0; padding: 0; } body { background-image: url('../Music Store/img/background.png'); background-repeat: repeat-x; } .clearfix { clear:both; } #wrapper { margin: 0 auto; max-width: 1120px; overflow: auto; border: 1px solid black; } #main_header { width: 100%; font-family: 'Black Ops One', sans-serif; background-color: black; border: 1px solid black; color: white; } #main_header h1 { float: left; font-size: 380%; margin: -10% 0 0 2%; } #callout { margin: 50px 20px 0 0; } #callout h2{ text-align: right; color: white; } #callout p{ text-align: right; padding: 0%; color: grey; font-size: 20px; margin-bottom: 3px; } #nav_menu { width: 100%; height: 10%; background-color: white; } #nav_menu li { display: inline-block; margin: 20px 20px 20px 63px; font-family: 'Open Sans', sans-serif; font-size: 20px; font-weight: bold; } #nav_menu li a { text-decoration: none; color: black; } #nav_menu li a:hover { color: grey; } .sub-menu { position: absolute; background-color: black; list-style-type: none; width: 124px; padding-left: 0px; margin-left: -25px; padding-top: 5px; opacity: 0; } .sub-menu li { padding-left: 25px; padding-top: 5px; padding-bottom: 5px; } #nav_menu li:hover .submenu { opacity: 1; } .sub-menu li:hover { color: green; background-color: yellow; } /*--- Start Image Slider --*/ .slider{ max-width: 1120px; box-shadow: 1% 2% 5% 0 rgba(0, 0, 0, 0.07); } .slider1 img{ width: 100%; margin: 0 auto; } .slider .bx-wrapper .bx-controls-direction a{ outline: 0 none; position: absolute; text-indent: -9999px; top: 40%; height: 71px; width: 40px; z-index: -1; transition: all 0.7s; } .slider .bx-wrapper:hover .bx-controls-direction a{ z-index: 5; } .slider .bx-wrapper .bx-prev{ background: url("../Music Store/img/arrow_left.png") no-repeat 7px 9px; left: 0px; } .slider .bx-wrapper .bx-prev:hover{ background: url("../Music Store/img/arrow_left.png") no-repeat 8px 15px; } .slider .bx-wrapper .bx-next{ background: url("../Music Store/img/arrow_right.png") no-repeat 10px 12px; right: 0px; } .slider .bx-wrapper .bx-next:hover{ background: url("../Music Store/img/arrow_right.png") no-repeat 10px 17px; } /*--- End Image Slider --*/ .one-third img{ text-align: center; max-width: 100%; height: auto; opacity: 0.9; } .border_section p{ font-family: 'Lato', sans-serif; padding: 2%; color: white; text-align: justify; } .border_section h3 { font-family: 'Open Sans', sans-serif; text-align: center; color: white; text-transform: uppercase; letter-spacing: 1%; } .border_section { border: 1px solid black; background-color: black; } .one-third{ width: 27.35%; float: left; margin: 2% 0 3% 4.5%; text-align: center; background-color: white; } footer{ font-family: 'Open Sans', sans-serif; font-weight: bold; text-align: center; width: 100%; height: 6%; background-color: black; overflow: auto; } footer p { margin-top: 1%; color: white; } </code></pre>
<p>Add this to your CSS : It will help you to have the result you want. Of course there are still adaptations to do regarding your preferences.</p> <pre><code>/* Without this line, the submenu elements are black on black background */ #nav_menu .sub-menu li a { color: #fff; } /* With this line you will remove the opacity:0; of the submenu when you hover the parent li */ #nav_menu li:hover .sub-menu { opacity: 1; } /* Don't set a width so you have a better output */ #nav_menu li .sub-menu { width: auto; } /* This lines make the submenu li dislay verticaly and not inline */ #nav_menu li .sub-menu li { display: block; } </code></pre> <p><strong>Edit:</strong></p> <p>Instead of changing the <code>opacity</code> property to show/hide the submenu, you should use the <code>display</code> property. Currently, the submenu is just transparent, but always opened. If your menu were bigger in height, you could open it by hovering the mouse on the slide at the location where it is when opened. By using the <code>display</code> property, you're actually hiding it, and it will be opened only if you hover the menu element (as it should be).</p> <p>To do this, you have to replace the <code>opacity: 0;</code> in your <code>.sub-menu</code> class by : <code>display: none;</code></p> <p>Then change the code <code>opacity: 1;</code> in the <code>#nav_menu li:hover .sub-menu</code> by : <code>display: block;</code> (in the code I gave you before).</p> <p>It will be cleaner than handling it with the <code>opacity</code>.</p>
EF 6 Tries to insert an object twice <p>I'm new using Entity Framework, and we are triyng to addapt our application with an architecture using EF6 model first. I have a class like that (I have simplified the code to explain better):</p> <pre><code>class Country { int CountryId (identity column) { get; set; } string Name { get; set; } ICollection&lt;Child&gt; Regions { get; set; } } class Region { int RegionId (identity column) { get; set; } string Name { get; set; } int CountryId { get ; set; } //foreign key to Country(CountryId) } </code></pre> <p>In a Business Layer in the application we initialize the object Region like that: </p> <pre><code>public Region Create() { Provincia Region = new Region (); provincia.Country = CountryDAL.GetByCode("ES"); provincia.CountryId = Region.Country.CountryId ; return Region ; } </code></pre> <p>CountryDAL is the layer that load a Country from the DB. When i try to saveChanges i have an Unique contraint exception from the DB beacause EF tries to insert the Country twice. i can't understand why</p> <pre><code>this.context.Entry(entity).State = Data.Entity.EntityState.Added; entity.AcceptChanges(user); int Result = this.context.SaveChanges(); </code></pre> <p>I only want to Save the entity Region with his property CountryId filled, i dont want to save The Country as a new object. However, In other View i should be able to create a Country and save their countries as childs (but this is another problem that i have solved).</p> <p>Thanks a lot</p>
<p>First of all, I think that your code doesn't compile. You have errors in Create() method. There is type Region and you use it as name of variable.</p> <p>Secondly, you asssign both navigation property (Country) and foreign key value (CountryId) in create method. You can just assign a CountryId property. So, in my opinion, this should work:</p> <pre><code>public Region Create() { var country = CountryDAL.GetByCode("ES"); Region provincia = new Region(); provincia.CountryId = country.CountryId; return Region; } </code></pre> <p>I also recommend you to not loading all Country entity. Instead of it, create a query that returns only id of country based on "ES" string.</p>
Is there any way to remove encryption from an existing Realm database? <p>We are using the Objective-C version of Realm, version 2.0.2. The database is currently encrypted and is in the field.</p> <p>Intermittent crashes on the startup of Realm have been occurring, with an error message of "Unable to open a Realm at path ... Realm file decryption failed". We are at the latest version available of Realm, and have not been able to find a solution. </p> <p>We don't really need the database to be encrypted on the device, so we would like to consider removing the encryption. Is this an option, and if so, how would we migrate the existing encrypted databases?</p>
<p>You can use <code>writeCopyToURL:encryptionKey:error:</code> with a <code>nil</code> encryption key to write an unencrypted copy, and then move that over the original file:</p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { RLMRealmConfiguration *confg = [[RLMRealmConfiguration alloc] init]; config.encryptionKey = ...; NSURL *tempUrl = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingPathComponent:"temp.realm"]]; // Open the Realm within an autoreleasepool so that it's closed before we try // to overwrite the original file @autoreleasepool { RLMRealm *realm = [RLMRealm realmWithConfiguration:config error:nil]; [realm writeCopyToURL:tempUrl encryptionKey:nil error:nil]; } [[NSFileManager defaultManager] moveItemAtURL:tempUrl toURL:config.fileUrl error:nil]; // ... other didFinishLaunchingWithOptions things ... return YES; } </code></pre>
Change div position with translate3d according to the mouse movement <p>I would like to achieve the effect of subtil div position changes with css transform translate3d according to the mouse movement. Something like the geometric figures of this website home section: <a href="http://riccardozanutta.com/" rel="nofollow">http://riccardozanutta.com/</a></p> <p>I tried this: </p> <pre><code>$(window).mousemove(function(event) { $(".home-img").css({"left" : event.pageX, "top" : event.pageY}); }); </code></pre> <p>with a single image positioned absolute and it worked (the image changed position according to the mousemove), however when I try to animate 3 divs with class .basic-skill</p> <pre><code>$(window).mousemove(function(event) { $(".basic-skill").css({"left" : event.pageX, "top" : event.pageY}); }); </code></pre> <p>they go out of the view port (when they are positioned relative) or they overlap one another (when they are positioned absolute).</p> <p>Moreover, I don't know how to limit the movement to max 5 px instead of making it move all over the view port.</p> <p>Thanks a lot for your guidance! </p>
<p>Solving your question for the max 5px displacement, you can multiply the X and Y coordinates with a factor like 0.1 to reduce the amount of movement. Like so:</p> <pre><code>$(".basic-skill").css({"left" : event.pageX * 0.1, "top" : event.pageY * 0.1}); </code></pre> <p><strong>EDIT:</strong> Instead of using <code>top</code> and <code>left</code>, you can use <code>margin-top</code> and <code>margin-left</code> with a static <code>top</code> and <code>left</code> value in CSS. <a href="https://jsfiddle.net/qcoy5xpg/1/" rel="nofollow">JSFiddle</a></p> <p>CSS</p> <pre><code>position: absolute; top: 50px; left: 50px; </code></pre> <p>JS</p> <pre><code>$("#two").css({"margin-left" : -(event.pageX * 0.1), "margin-top" : -(event.pageY * 0.1)}); </code></pre> <p><strong>EDIT 2:</strong> Enhanced Fiddle: <a href="https://jsfiddle.net/qcoy5xpg/2/" rel="nofollow">https://jsfiddle.net/qcoy5xpg/2/</a></p> <p>But this is just a quick n easy one. In the demo page you provided, he has used CSS animations on SVG elements. That is why it seems elegant, if I may (easings)</p>
Open unique secondary window with Tkinter <p>I'm having a trouble when i open a secondary window. Now I'm just creating a toplevel window with a button and I need to open the same secondary window If i click the button (not generate a new instance).</p> <p>Which is the better way to generate single secondary window and not generating a new window instance?</p> <p>I leave the code that I'm actually working on:</p> <pre><code>import tkinter class LogWindow(): def __init__(self, parent): self.parent = parent self.frame = tkinter.Frame(self.parent) class MainWindow(tkinter.Frame): def __init__(self, parent): tkinter.Frame.__init__(self, parent) self.parent = parent frame = tkinter.Frame(self, borderwidth=1) frame.pack(fill=tkinter.BOTH, expand=True, padx=5, pady=5) self.LogButton = tkinter.Button(frame, text="Log Viewer", command= self.openLogWindow) self.LogButton.grid(sticky=tkinter.E+tkinter.W) self.pack(fill=tkinter.BOTH,expand=True) def openLogWindow(self): self.logWindow = tkinter.Toplevel(self.parent) self.app = LogWindow(self.logWindow) def main(): global app, stopRead root = tkinter.Tk() root.geometry("300x300") app = MainWindow(root) root.mainloop() if __name__ == '__main__': main() </code></pre> <p>Maybe i need to have a single instance of a Toplevel class and call show and close to show or hide the secondary window.</p>
<p>Finally after some tests I've found how to solve that, thanks to the @furas response and some investigation about the Tkinter events with the protocol function.</p> <p>I've got that working with:</p> <pre><code>import tkinter logWindowExists = False class LogWindow(): def __init__(self, parent): global logWindowExists, root logWindowExists = True self.parent = parent self.frame = tkinter.Frame(self.parent) def on_closing(self): global logWindowExists logWindowExists = False self.parent.destroy() class MainWindow(tkinter.Frame): def __init__(self, parent): tkinter.Frame.__init__(self, parent) self.parent = parent frame = tkinter.Frame(self, borderwidth=1) frame.pack(fill=tkinter.BOTH, expand=True, padx=5, pady=5) self.LogButton = tkinter.Button(frame, text="Log Viewer", command= self.openLogWindow) self.LogButton.grid(sticky=tkinter.E+tkinter.W) self.pack(fill=tkinter.BOTH,expand=True) def openLogWindow(self): if not logWindowExists: self.logWindow = tkinter.Toplevel(self.parent) self.app = LogWindow(self.logWindow) self.logWindow.protocol("WM_DELETE_WINDOW", self.app.on_closing) else: self.logWindow.deiconify() def main(): global app, stopRead, root root = tkinter.Tk() root.geometry("300x300") app = MainWindow(root) root.mainloop() if __name__ == '__main__': main() </code></pre> <p>Using a boolean to know if the window exists or not i can handle when the window it's opened or not and just show the existing window or creating a new one.</p>
Why is my Presenter not subscribed to my View event in my WinForms project? <p>I am trying to implement the MVP pattern into my WinForms project. However, the method 'Activate' in my Presenter that is subscribed to my 'ActivatedForm' event from my View, does not seem to fire when i load the form. I have tested it simply by printing someting in the 'Activate' method. Why is this not working properly?</p> <p>I have posted my code below. </p> <p>I think it has something to do with the fact that I am creating the Presenter with the concrete View even though the _view attribute is of the interface type 'IHomeScreenView'. I know that the 'HomeScreenView_Activated' event occurs, because I have put a print in there too and that worked. The 'ActivatedForm' event just always returns null there which means that nothing is subscribed to the event.</p> <p><strong>IHomeScreenView.cs</strong></p> <pre><code>public interface IHomeScreenView { List&lt;string&gt; ExistingAssessments { get; set; } event EventHandler&lt;EventArgs&gt; ActivatedForm; event EventHandler&lt;EventArgs&gt; CreatingNewAssessment; event EventHandler&lt;EventArgs&gt; AddingNewStandard; event EventHandler&lt;EventArgs&gt; OpeningAssessment; } </code></pre> <p><strong>HomeScreenView.cs</strong></p> <pre><code>public partial class HomeScreenView : Form, IHomeScreenView { private HomeScreenPresenter homeScreenPresenter; public List&lt;string&gt; ExistingAssessments { get { return recentAssessments.Items.Cast&lt;string&gt;().ToList(); } set { recentAssessments.DataSource = value; } } public event EventHandler&lt;EventArgs&gt; ActivatedForm; public event EventHandler&lt;EventArgs&gt; CreatingNewAssessment; public event EventHandler&lt;EventArgs&gt; AddingNewStandard; public event EventHandler&lt;EventArgs&gt; OpeningAssessment; // Initialize homescreen. public HomeScreenView() { InitializeComponent(); } // Fires the activating form event. private void HomeScreenView_Activated(object sender, EventArgs e) { ActivatedForm?.Invoke(this, EventArgs.Empty); } </code></pre> <p><strong>HomeScreenPresenter.cs</strong></p> <pre><code>public class HomeScreenPresenter { private IHomeScreenView _view; private AssessmentsModel _assessmentsModel; public HomeScreenPresenter(IHomeScreenView view) { _assessmentsModel = new AssessmentsModel(); _view = view; _view.ActivatedForm += Activate; _view.CreatingNewAssessment += CreateNewAssessment; _view.AddingNewStandard += AddNewStandard; _view.OpeningAssessment += OpenAssessment; } public void Activate(object sender, EventArgs e) { Debug.Print("hi"); HashSet&lt;string&gt; items = new HashSet&lt;string&gt;(_assessmentsModel.GetDataList("Assessments", "assessment_name")); List&lt;string&gt; assessments = items.ToList(); _view.ExistingAssessments = assessments; } </code></pre> <p>I hope someone can help, thank you.</p>
<p>The <code>Form.Activated</code> event is only fired when the form is visible. See <a href="https://msdn.microsoft.com/en-us/library/system.windows.forms.form.activated(v=vs.110).aspx" rel="nofollow">the documentation</a>.</p> <blockquote> <p>When the application is active and has multiple forms, the active form is the form with the input focus. <strong>A form that is not visible cannot be the active form</strong>. The simplest way to activate a visible form is to click it or use an appropriate keyboard combination.</p> </blockquote> <p>If your form is already visible when the presenter is being created, then the activated event has already fired. You could call <code>Form.Activate()</code> once the presenter is created and the eventhandler is hooked up.</p>
Inverse match for HTML tags <p>Using <strong>NodeJS</strong>, I have the following regex: <code>/&lt;[^&gt;]*&gt;/g</code> which matches HTML tags: (<a href="https://www.regex101.com/r/KIC8hb/1" rel="nofollow">Live Demo</a>) <a href="http://i.stack.imgur.com/OYO06.png" rel="nofollow"><img src="http://i.stack.imgur.com/OYO06.png" alt="enter image description here"></a></p> <p>I would like to inverse the match so it will capture the text, I've tried <a href="http://stackoverflow.com/questions/6851921/negative-lookahead-regular-expression">negative lookahead</a> approach, with no luck.</p> <p><strong>EDIT</strong> I'm avoiding split method, because I need the indexes of the match</p> <p>Is it possible with JS?</p>
<blockquote> <p>Is it possible with JS?</p> </blockquote> <p>No. HTML can be arbitrarily nested, which means you need recursion in order to consume it using regex - something which JavaScript regex doesn't have.</p> <p>Assuming you can ditch JS and use a language that supports PCRE, this <strike>monstrous bunch of unintelligible characters written by Cthulhu</strike> regex does the trick (<a href="https://regex101.com/r/52Zm7Z/1" rel="nofollow">mandatory regex101 link</a>) (note that it doesn't deal with CDATA):</p> <pre><code>&lt;!--[\s\S]*?--&gt;|&lt;([a-z]+)(?:\s\S+?=(["']|)[\s\S]*?\2)*&gt;((?:[\s\S]*?(?R)?)*)&lt;\/\1&gt; </code></pre> <p>Here's how it works:</p> <ul> <li><code>&lt;!--[\s\S]*?--&gt;|</code> is for preventing comments from causing false positives</li> <li><code>&lt;([a-z]+)(?:\s\S+?=(["']|)[\s\S]*?\2)*&gt;</code> is the opening tag, where <ul> <li><code>([a-z]+)</code> is the tag name (note the capturing group - we'll need it in the closing tag)</li> <li><code>(?:\s\S+?=(["']|)[\s\S]*?\2)*</code> is the attributes, where <ul> <li><code>\s</code> is the whitespace character that separates attributes from tag name and each other</li> <li><code>\S+?=</code> is the attribute name followed by an equals sign (note the lazy quantifier - we need it because <code>\S</code> includes <code>=</code>)</li> <li><code>(["']|)[\s\S]*?\2</code> is the value, that can be enclosed in double quotes, single quotes, or nothing</li> </ul></li> </ul></li> <li><code>((?:[\s\S]*?(?R)?)*)</code> is the text between tags (note the capturing group - <strong>it's exactly what you need and will appear as group 3</strong>), where <code>(?R)?</code> makes the regex able to deal with nested constructs</li> <li><code>&lt;\/\1&gt;</code> is the closing tag, where <code>\1</code> is the tag name (remember the capturing group in the opening tag)</li> </ul>
Spring REST service log request and response messages <p>How to log incoming request and response HTTP messages along with headers for my Spring REST services? I am using Spring 4 and Tomcat 7. </p> <p>What is the best practice to log the above? </p> <p>I checked logBack TeeFilter but the documentation advises to disable it in production machine. I am looking to setup something that I can use in production as well. Would like to log the request and response to a specific log file.</p> <p>I have looked through stack overflow and there are different suggestion so not sure which is the best approach to take as of Spring 4.0</p>
<p>I have been using the answer provided in <a href="http://stackoverflow.com/questions/3017188/java-tomcat-standalone-how-to-log-access-all-the-http-get-requests?rq=1">Java/Tomcat standalone, how to log/access all the HTTP GET requests</a> for my Spring 4 project and it works like a charm. Idea behind this is to remove logging from code for http. </p> <p>Uncomment below in server.xml: </p> <pre><code>&lt;Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/&gt; </code></pre>
Currently working on my project and need some help ...want to save my command line info or text in Text File through c# <pre><code> System.Diagnostics.Process process1; process1= new System.Diagnostics.Process(); process1.EnableRaisingEvents = false; string strCmdLine; strCmdLine = "/k " +textBox3.Text; System.Diagnostics.Process.Start("CMD.exe",strCmdLine); </code></pre> <p>This will run a command on cmd .. Want to save that CMD command text on text file.. Using this for save but not working..</p> <pre><code> ProcessStartInfo PSI = new ProcessStartInfo(); PSI.FileName = "c:\\WINDOWS\\System32\\cmd.exe"; PSI.RedirectStandardInput = true; PSI.RedirectStandardOutput = true; PSI.RedirectStandardError = true; PSI.UseShellExecute = false; Process p = Process.Start(PSI); string output = p.StandardOutput.ReadToEnd(); StreamWriter st = new StreamWriter(@"C:\test.txt"); st.Write(output); st.Close(); </code></pre>
<p>Try this</p> <pre><code>using System.Diagnostics; Process.Start("cmd", "/k " + textBox3.Text + @" &gt; C:\test.txt"); </code></pre> <p>Also, read <a href="http://www.codeproject.com/Articles/335909/Embedding-a-Console-in-a-C-Application" rel="nofollow">Embedding a Console in a C# Application - CodeProject</a></p>
React Native: synchronously run functions <p>I'm new to OOP. My knowledge of promises/asynchronously/synchronously running functions is simply basic. I'd really appreciate your time and attention!</p> <p>This is the example from React-Native docs:</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>async function getMoviesFromApi() { try { let response = await fetch('https://facebook.github.io/react-native/movies.json'); let responseJson = await response.json(); return responseJson.movies; } catch(error) { console.error(error); } }</code></pre> </div> </div> </p> <p>As i understand from code above, getMoviesFromApi is declared as async function. which means it will execute functions one after other. Right? please correct me if not!</p> <p>it will first wait for fetch to finish then call response.json, right?</p> <p>I have few functions, which get data from a server via fetch, then insert them to sqlite database. so they don't return anything.</p> <p>in example above, fetch returns something. but my functions, not. so, can i use this structure to make javascript run my functions consequently? what is the best practice / right solution to achieve this?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let query = []; export default class Main extends Component(){ constructor(props){ super(props); } componentWillMount(){ this.getBookable(); this.getBooked(); this.runQuery(); this.redirectUser(); //// i need this functions to run consequently. not all in same time, one after eachother } getBookable(){ let fetchedData = fetch(); /// Fetchs data from remote server query.push('INSERT INTO bookable (data) VALUES (' + fetchedData + ')'); } getBooked(){ let fetchedData = fetch(); /// Fetchs data from remote server query.push('INSERT INTO booked (data) VALUES (' + fetchedData + ')'); } runQuery(){ for(let i=0; i &lt; query.length; i++){ db.transaction((tx) =&gt; { tx.executeSql(query[i],[], (tx, results) =&gt; { console.log('Query', query[f], 'Executed. results:', results); }, (err)=&gt;{ console.log('Something went wrong while executing query',query[i],'error is', err); }); }); } } redirectUser(){ Actions.tabbar({type: 'reset'}); //// Using redux. redirect user to another page } }</code></pre> </div> </div> First, i get bookable courses, then booked courses, insert them to database, then redirect user to another page via redux How should i update my code?</p> <hr> <p>UPDATE :</p> <p>updated code according to @Bergi : is this the right way?</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>import React, {Component, PropTypes} from 'react'; import { ActivityIndicator, StyleSheet, Text, View, NetInfo, AlertIOS, } from 'react-native'; var SQLite = require('react-native-sqlite-storage'); var Loading = require("./Loading"); var DeviceInfo = require('react-native-device-info'); import { Actions } from 'react-native-router-flux'; var LOADING = {}; var db = SQLite.openDatabase({name : "oc.db", location: 'default'}); import CodePush from "react-native-code-push"; import I18n from 'react-native-i18n'; import translations from './translations'; I18n.fallbacks = true; export default class Grab extends Component{ constructor(props) { super(props); this.state = { terms: '', isLoading: false, isConnected: null, coursesFetched: false, registerFetched: false, }; } componentWillMount() { NetInfo.isConnected.fetch().then(isConnected =&gt; { this.setState({ isConnected: isConnected }); }); NetInfo.isConnected.addEventListener( 'change', isConnected =&gt; { this.setState({ isConnected: isConnected }); console.log('Grab: internet status is', this.state.isConnected); this.sync(); } ); this.GrabData(); } toggleAllowRestart() { this.state.restartAllowed ? CodePush.disallowRestart() : CodePush.allowRestart(); this.setState({ restartAllowed: !this.state.restartAllowed }); } sync() { console.log("Grab: Running manual code push update"); CodePush.sync( { installMode: CodePush.InstallMode.IMMEDIATE, updateDialog: false }, ); } async getUsers(){ let userlist = []; let query = ["SELECT * FROM users"]; await db.transaction(tx =&gt; { return Promise.all(query.map(async (q) =&gt; { try { let results = await tx.executeSql(q, []); console.log('Query', q, 'Executed. results:', results); for(let ind = 0; ind &lt; len; ind++ ){ userlist[ind] = { userId: results.rows.item(ind).userId, userName: results.rows.item(ind).userName, userMail: results.rows.item(ind).userMail, active: results.rows.item(ind).active, firstName: results.rows.item(ind).firstName, lastName: results.rows.item(ind).lastName, accessToken: results.rows.item(ind).access_token, host: results.rows.item(ind).host, }; } } catch(err) { console.log('Something went wrong while executing query', q, 'error is', err); } })); }); return userlist; } async getBookable(users){ let results = []; for(let n=0; n &lt; users.length; n++){ try { let host = users[n].host; let access_token = users[n].access_token; let userId = users[n].userId; let response = await fetch(host + 'event/my_events', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'language': DeviceInfo.getDeviceLocale(), 'Authorization': 'Bearer ' + access_token } }); let responseData = await response.json(); //// Get container details if(responseData.container.length &gt; 0){ for(let i=0; i &lt; responseData.container.length; i++){ let cnid = responseData.container[i].nid; let ctitle = responseData.container[i].title; results.push( "INSERT INTO containersC (userId, nid, title) VALUES ('" + userId + "','" + cnid + "', '" + ctitle + "')" ); //// Get courses for each container for(let j=0; j &lt; responseData.container[i].course.length; j++){ let course_id = responseData.container[i].course[j].nid; let title = responseData.container[i].course[j].title; let cost = responseData.container[i].course[j].cost; let status = responseData.container[i].course[j].status; let period = responseData.container[i].course[j].period.time_sys; //// Get details for each course try { let resp = await fetch(host + 'event/course_detail/' + course_id, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'language': DeviceInfo.getDeviceLocale(), 'Authorization': 'Bearer ' + access_token } }); let respData = await resp.json(); let desc = respData.data.content[0].value; let capacity = respData.data.content[1].value; let image = respData.data.image; let status = respData.data.book; let cancel = respData.data.cancel; let cd = responseData.data.dates; results.push( "INSERT INTO courses (userId, course_id, container_nid, title, cost, status, period, desc, capacity, image, cancel) VALUES ('" + userId + "','" + course_id + "', '" + cnid + "', '" + title + "', '" + cost + "', '" + status + "', '" + period + "', '" + desc + "', '" + capacity + "', '" + image + "', '" + cancel + "')" ); //// Getting lecture dates for each course for(let a=0; a &lt; cd.length; a++){ let sdate = cd[a].start_time.split(" "); let edate = cd[a].end_time.split(" "); results.push( "INSERT INTO lectures (userId, course_id, title, start_time, end_time, start_date, end_date, room, teacher) VALUES ('" + userId + "','" + course_id + "', '" + cd[a].title + "', '" + sdate[1] + "', '" + edate[1] + "', '" + sdate[0] + "', '" + edate[0] + "', '" + cd[a].room + "', '" + cd[a].teacher + "')" ); } //// End getting lecture dates for courses return true; } catch(error) { console.error(error); } //// End getting details for courses } //// End getting courses for containers } } //// End getting container details return true; } catch(error) { console.error(error); } } } redirectUser(){ Actions.tabbar({type: 'reset'}); } async runQuery(query) { await db.transaction(tx =&gt; { return Promise.all(query.map(async (q) =&gt; { try { let results = await tx.executeSql(q, []); console.log('Query', q, 'Executed. results:', results); } catch(err) { console.log('Something went wrong while executing query', q, 'error is', err); } })); }); return true; } async function GrabData(){ try { let users = await getUsers(); //let [courses, register, evaluation] = await Promise.all([getCourses(users), getRegister(users), getEvaluation(users)]); let [courses] = await Promise.all([getCourses(users)]); //let query = [courses, register, evaluation]; let query = [courses]; await runQuery(["DELETE FROM containersC", "DELETE FROM courses", "DELETE FROM lectures", "DELETE FROM containersR", "DELETE FROM register", "DELETE FROM lectures", "DELETE FROM evaluations", "DELETE FROM fields"]); await runQuery(query); this.redirectUser(); } catch(error){ console.log(error); } } render() { return( &lt;View style={styles.container}&gt;&lt;Loading/&gt;&lt;/View&gt; ); } } var styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", flexDirection: "column", }, }); Grab = CodePush(Grab);</code></pre> </div> </div> </p> <p>I'm using react-native-sqlite-storage : <a href="https://github.com/andpor/react-native-sqlite-storage" rel="nofollow">https://github.com/andpor/react-native-sqlite-storage</a></p>
<blockquote> <p><code>getMoviesFromApi</code> is declared as <code>async function</code>. which means it will execute functions one after other.</p> </blockquote> <p>No. That only means that it will return a promise when called, and that you can use the <code>await</code> operator in the function body.</p> <blockquote> <p>it will first wait for fetch to finish then call response.json, right?</p> </blockquote> <p>Yes, because it uses <code>await</code> to stop evaluation of the method until the promise resolves.</p> <blockquote> <p>I have few functions, which get data from a server via fetch, then insert them to sqlite database. so they don't return anything.</p> </blockquote> <p>They should return promises - even if they're promises for nothing, they still could be awaited.</p> <p>But in your case, they actually <em>should</em> return something. Your global static <code>query</code> array is a horrible antipattern. Instead of filling it with queries, each method should return (a promise for) a query, which then can be passed to the executor on a per-instance and per-call basis. Only then using a <em>transaction</em> actually begins to make sense.</p> <p>Your code should look like this:</p> <pre><code>class Main extends Component() { … async getBookable(){ var response = await lfetch(host, { method: 'POST', headers: … }); var responseData = await response.json(); return 'INSERT INTO bookable (data) VALUES (' + responseData + ')'); // beware of SQL injections!!! } getBooked(){ // the very same - here written without async/await: return fetch(host, { // ^^^^^^ important - return a promise method: 'POST', headers: … }) .then(response =&gt; response.json()) .then(responseData =&gt; { return 'INSERT INTO booked (data) VALUES (' + responseData + ')'; }); // don't `catch` anything, don't call `done` - just return the promise chain // errors will be handled in the try/catch below } async runQuery(query) { await db.transaction(tx =&gt; { return Promise.all(query.map(async (q) =&gt; { try { let results = await tx.executeSql(q, []); console.log('Query', q, 'Executed. results:', results); } catch(err) { console.log('Something went wrong while executing query', q, 'error is', err); } })); }); return true; } async function getStore() { try { // actually you can fetch these in parallel, right? let [bookable, booked] = await Promise.all([getBookable(), getBooked()]); let query = [bookable, booked]; await runQuery(query); redirectUser(); } catch(error) { console.error(error); } } } </code></pre>
Kotlin Jackson generation objects from JSON <p>Please help! I'm trying to generate object from JSON with jackson kotlin module. Here is json source:</p> <pre><code>{ "name": "row", "type": "layout", "subviews": [{ "type": "horizontal", "subviews": [{ "type": "image", "icon": "ic_no_photo", "styles": { "view": { "gravity": "center" } } }, { "type": "vertical", "subviews": [{ "type": "text", "fields": { "text": "Some text 1" } }, { "type": "text", "fields": { "text": "Some text 2" } }] }, { "type": "vertical", "subviews": [{ "type": "text", "fields": { "text": "Some text 3" } }, { "type": "text", "fields": { "text": "Some text 4" } }] }, { "type": "vertical", "subviews": [{ "type": "image", "icon": "ic_no_photo" }, { "type": "text", "fields": { "text": "Some text 5" } }] }] }] } </code></pre> <p>I'm trying to generate instance of Skeleton class. </p> <pre><code>data class Skeleton (val type : String, val name: String, val icon: String, val fields: List&lt;Field&gt;, val styles: Map&lt;String, Map&lt;String, Any&gt;&gt;, val subviews : List&lt;Skeleton&gt;) data class Field (val type: String, val value: Any) </code></pre> <p>As you can see, Skeleton object can have other Skeleton objects inside (and these objects can have other Skeleton objects inside too), also Skeleton can have List of Field objects</p> <pre><code>val mapper = jacksonObjectMapper() val skeleton: Skeleton = mapper.readValue(File(file)) </code></pre> <p>This code ends with exception:</p> <pre><code>com.fasterxml.jackson.databind.JsonMappingException: Instantiation of [simple type, class com.uibuilder.controllers.parser.Skeleton] value failed (java.lang.IllegalArgumentException): Parameter specified as non-null is null: method com.uibuilder.controllers.parser.Skeleton.&lt;init&gt;, parameter name at [Source: docs\layout.txt; line: 14, column: 3] (through reference chain: com.uibuilder.controllers.parser.Skeleton["subviews"]-&gt;java.util.ArrayList[0]-&gt;com.uibuilder.controllers.parser.Skeleton["subviews"]-&gt;java.util.ArrayList[0]) </code></pre>
<p>There are several issues I found about your mapping that prevent Jackson from reading the value from JSON:</p> <ul> <li><p><code>Skeleton</code> class has not-null constructor parameters (e.g. <code>val type: String</code>, not <code>String?</code>), and Jackson passes <code>null</code> to them if the value for those parameters is missing in JSON. This is what causes the exception you mentioned:</p> <blockquote> <p>Parameter specified as non-null is null: method <code>com.uibuilder.controllers.parser.Skeleton.&lt;init&gt;</code>, parameter <code>name</code></p> </blockquote> <p>To avoid it, you should mark the parameters that might might have values missing as nullable (all of the parameters in your case):</p> <pre><code>data class Skeleton(val type: String?, val name: String?, val icon: String?, val fields: List&lt;Field&gt;?, val styles: Map&lt;String, Map&lt;String, Any&gt;&gt;?, val subviews : List&lt;Skeleton&gt;?) </code></pre></li> <li><p><code>fields</code> in <code>Skeleton</code> has type <code>List&lt;Field&gt;</code>, but in JSON it's represented by a single object, not by an array. The fix would be to change the <code>fields</code> parameter type to <code>Field?</code>:</p> <pre><code>data class Skeleton(... val fields: Field?, ...) </code></pre></li> <li><p>Also, <code>Field</code> class in your code doesn't match the objects in JSON:</p> <pre><code>"fields": { "text": "Some text 1" } </code></pre> <p>You should change <code>Field</code> class as well, so that it has <code>text</code> property:</p> <pre><code>data class Field(val text: String) </code></pre></li> </ul> <p>After I made the changes I listed, Jackson could successfully read the JSON in question.</p> <hr> <p><strong>See also:</strong> <a href="https://kotlinlang.org/docs/reference/null-safety.html" rel="nofollow">"Null Safety" in Kotlin reference</a>.</p>
How to properly publish an event? <p>In a runtime only package, I've defined a TFrame descendant which publishes the OnLoaded event:</p> <pre><code>type TMyMethod = procedure() of object; TMyFrame = class(TFrame) protected FOnLoaded : TMyMethod; procedure Loaded(); override; published property OnLoaded : TMyMethod read FOnLoaded write FOnLoaded; end; implementation {$R *.dfm} procedure TMyFrame.Loaded(); begin inherited; if(Assigned(FOnLoaded)) then FOnLoaded(); end; </code></pre> <p>In a designtime only package, I've registered TMyFrame component as follows:</p> <pre><code>unit uMyRegistrations; interface uses Classes, uMyFrame; procedure Register; implementation procedure Register; begin RegisterComponents('MyTestComponents', [ TMyFrame ]); end; </code></pre> <p>I've installed the designtime package, I can find TMyFrame in the tool palette and its OnLoaded event is shown in the object inspector.</p> <p>I've dragged a TMyFrame into a form, then I've assigned the OnLoaded event by doubleclicking from the object inspector. After assigning the event, I noticed that an access violation error message appears each time I try to open the form's file in Delphi (It let me open the ".pas" file, but I can't switch to visual designer view).</p> <p><a href="http://i.stack.imgur.com/EuSnc.png" rel="nofollow"><img src="http://i.stack.imgur.com/EuSnc.png" alt="enter image description here"></a></p> <p>Did I correctly published the OnLoaded event? If so, what else is wrong?</p> <p><strong>Further Informations:</strong></p> <ol> <li>I'm using Delphi 2007 (don't know if it matters). </li> <li>The error also appears by doing the same thing with different parent classes (Not only for TFrame descendants).</li> </ol>
<h1>Updated (somewhat less bogus) answer</h1> <p>You accepted my original answer, but what I wrote was not correct. Rob Kennedy pointed to an <a href="http://community.embarcadero.com/blogs/entry/assigned-or-not-assigned-that-is-the-question-28836" rel="nofollow">article</a> by former Embarcadero developer Allen Bauer on the topic of <code>Assigned</code>. </p> <p>Allen explains that the <code>Assigned</code> function only tests one pointer of the two pointers in a method pointer. The IDE at design time takes advantage of this by assigning sentinel values to any published method properties (i.e. events). These sentinel values have <code>nil</code> for one of the two pointers in the method pointer (the one that <code>Assigned</code> checks), and an index identifying the property value in the other pointer. </p> <p>All this means that <code>False</code> is returned when you call <code>Assigned</code> at design time. So long as you check published method pointers with <code>Assigned</code> before calling them, then you will never call them at design time.</p> <p>So what I originally wrote cannot be true.</p> <p>So I dug a bit deeper. I used the following very simple code, testing with XE7:</p> <pre><code>type TMyControl = class(TGraphicControl) protected FSize: Integer; procedure Loaded; override; end; .... procedure TMyControl.Loaded; begin inherited; FSize := InstanceSize; end; .... procedure Register; begin RegisterComponents('MyTestComponents', [TMyControl]); end; </code></pre> <p>This was enough to cause an AV in the IDE at design time whenever the <code>Loaded</code> method was executed.</p> <p>My conclusion is that the IDE does some rather underhand things when streaming, and your objects are not in a fit state to use when the <code>Loaded</code> method is called. But I don't really have a better understanding than that.</p> <hr> <h1>Original (very bogus) answer</h1> <p>You must not execute event handlers at design time, and your code does just that. The reason being that at design time the event handler's code is not available.</p> <p>The control's code is available, the IDE has loaded it – but the code that implements the event handler is not. That code is not part of the design time package, it is part of the project that is currently open in the IDE. After all, it might not even compile yet!</p> <p>The <code>Loaded</code> method should defend against this like so:</p> <pre><code>procedure TMyFrame.Loaded(); begin inherited; if not (csDesigning in ComponentState) and Assigned(FOnLoaded) then FOnLoaded(); end; </code></pre>
Convert String to INT64 <p>How do I convert in the following code the string to INT64 instead of INT32</p> <pre><code> public static int TransferClient(string NRIFActual, string NRIFNuevo) { int nResult = 0; try { nResult = ws.TransferClient(int.parse(NRIFActual), int.Parse(NRIFNuevo)); } catch (System.Net.WebException ex) { throw new Exception(ex.Message); } return nResult; } </code></pre> <p>Notice that I need the same variable name because it is used in A web service, is there a way to just convert it to INT64 like the int.parse()?</p>
<p>You probably get OverflowException because the value that an int(Int32) can store is between -2,147,483,648 and 2,147,483,647.</p> <p>1) Verify that the string input you pass is the correct one.</p> <p>2) If the users shouldn't insert number this high try to add a validation to the input(text box)</p> <p>3) If the user will(can) insert bigger numbers you should use a type that can store an higher value -> long(Int64) should be enough(The range is –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807), if not go bigger -> you will find a list with C# types here : <a href="https://msdn.microsoft.com/ro-ro/library/ya5y69ds.aspx" rel="nofollow">https://msdn.microsoft.com/ro-ro/library/ya5y69ds.aspx</a></p> <p>Tip: use TryParse method instead of Parse(for any type you will use). This method will return a bool that states if the conversion succeeded or failed and the actual conversion in output parameter. This will make the exception handling much easier.</p> <p>Edit after Hans comment:</p> <p>To keep the solution simple and not dive in another topics you should do something like this:</p> <pre><code>string input = "92233720368547758071"; long result; if (!long.TryParse(input , out result)) /*error handling */ else /*Continue the flow of your program*/ </code></pre> <p>*The input may came from anywhere. This is just for example purpose. </p>
FxCop analyzers do not show warnings on the fly <p>I am using the FxCop Analyzers NuGet package (Microsoft.CodeAnalysis.FxCopAnalyzers) to get analysis results in the error list while typing.</p> <p>The issue is that the FxCop analyzers are not returning CA1707 errors (underscore) while typing (or after loading the solution) while I get the CA1707 when I select 'Enable Code Analysis on build' in the project build settings or manual run the static code analysis.</p> <p>Note that this is not specific to 1707, also CA1008 only pops up during static code analysis run. So it looks like an issue of the FxCop analyzer itself...</p> <p>What can be the issue here ?</p>
<p>If you have Visual Studio 2015 Update 3 or later, you need to <a href="https://msdn.microsoft.com/en-us/library/mt709421.aspx" rel="nofollow">enable full solution analysis</a>.</p> <p>It's in Options > Text Editor > C#/Basic > Advanced.</p>
text not rendering in div <p>I have following CSS:</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-html lang-html prettyprint-override"><code>#navigation { background-color: #ededed; text-align: center; margin: 0; font-size: 0; } #meet { position: relative; z-index: 1; display: inline-block; background-color: #088A85; width: 300px; height: 90px; margin: 0; padding: 0; } #meet p { z-index: 3; background-color: #000000; text-align: center; color: } #meet a, #develop a, #beinformed a{ color: #ffffff; text-decoration: none; } .council { background-image: url(council.png); }</code></pre> </div> </div> </p> <p>And following HTML code:</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-html lang-html prettyprint-override"><code>&lt;div id="navigation"&gt; &lt;div id="meet"&gt; &lt;p&gt;THIS TEXT IS NOT SHOWN&lt;/p&gt; &lt;span class="button council"&gt; &lt;a href="djfdf"&gt;council&lt;/a&gt; &lt;/span&gt; &lt;span class="button tacticalgroup"&gt; &lt;a href="dfkl"&gt;tactical group&lt;/a&gt; &lt;/span&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>For some reason the text in the Paragraph is not shown. I have tried various things (z-index etc), but it is not working. What am I missing here?</p>
<p>I forgot that I had put font-size to a value of 0 and that explains all why the text in the P is not shown. I have therefore set the font-size of the P element element to a higher value and that solves the problem.</p>
npm start error with create-react-app <p>I have a project who I didn't touch for 2 weeks. I take it back and now when I try to run <code>npm start</code> I got this error.</p> <pre><code>&gt; react-scripts start sh: react-scripts: command not found npm ERR! Darwin 16.0.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start" npm ERR! node v6.7.0 npm ERR! npm v3.10.3 npm ERR! file sh npm ERR! code ELIFECYCLE npm ERR! errno ENOENT npm ERR! syscall spawn npm ERR! UpScore@0.6.0 start: `react-scripts start` npm ERR! spawn ENOENT npm ERR! npm ERR! Failed at the UpScore@0.6.0 start script 'react-scripts start'. npm ERR! Make sure you have the latest version of node.js and npm installed. npm ERR! If you do, this is most likely a problem with the UpScore package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! react-scripts start npm ERR! You can get information on how to open an issue for this project with: npm ERR! npm bugs UpScore npm ERR! Or if that isn't available, you can get their info via: npm ERR! npm owner ls UpScore npm ERR! There is likely additional logging output above. </code></pre> <ul> <li>node 6.7.0</li> <li>npm 3.10.3</li> <li>mac sierra 10.12</li> </ul> <p>package.json</p> <pre><code>{ "name": "UpScore", "version": "0.6.0", "private": true, "devDependencies": { "react-addons-test-utils": "^15.3.1", "react-scripts": "0.4.1", "react-test-renderer": "^15.3.1", "redux-logger": "^2.6.1" }, "dependencies": { "@yoshokatana/medium-button": "^1.1.0", "axios": "^0.14.0", "bcrypt": "^0.8.7", "bcrypt-nodejs": "0.0.3", "bcryptjs": "^2.3.0", "body-parser": "^1.15.2", "connect-flash": "^0.1.1", "cookie-parser": "^1.4.3", "draft-js": "^0.8.1", "draft-js-editor": "^1.7.2", "draft-js-export-html": "^0.4.0", "ejs": "^2.5.2", "email-verification": "^0.4.5", "express": "^4.14.0", "express-session": "^1.14.1", "flexboxgrid": "^6.3.1", "highlight.js": "^9.6.0", "immutable": "^3.8.1", "katex": "^0.6.0", "lodash": "^4.15.0", "markdown-it-mathjax": "^1.0.3", "material-ui": "^0.15.4", "medium-editor": "^5.22.0", "minutes-seconds-milliseconds": "^1.0.3", "moment": "^2.15.0", "moment-duration-format": "^1.3.0", "mongod": "^1.3.0", "mongodb": "^2.2.9", "mongoose": "^4.6.0", "monk": "^3.1.2", "morgan": "^1.7.0", "normalize.css": "^3.0.3", "passport": "^0.3.2", "passport-local": "^1.0.0", "react": "^15.3.1", "react-dom": "^15.3.1", "react-markdown": "^2.4.2", "react-medium-editor": "^1.8.1", "react-redux": "^4.4.5", "react-redux-form": "^0.14.5", "react-rich-markdown": "^1.0.1", "react-router": "^2.7.0", "react-router-redux": "^4.0.5", "react-tap-event-plugin": "^1.0.0", "react-tinymce": "^0.5.1", "redux": "^3.6.0", "redux-form": "^6.0.5", "redux-form-material-ui": "^4.0.1", "redux-promise-middleware": "^4.0.0", "redux-thunk": "^2.1.0", "reselect": "^2.5.3", "screenfull": "^3.0.2" }, "scripts": { "start": "react-scripts start", "start:prod": "pushstate-server build", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject", "server": "cd client/api &amp;&amp; pm2 start server.js --watch", "proxy": "http://128.199.139.144:3000" }, "eslintConfig": { "extends": "./node_modules/react-scripts/config/eslint.js" } } </code></pre> <p>I try to clone my repos too and get the same error. If someone can give me some way to find what happen. Thank you</p>
<p>Author of Create React App checking in.</p> <p><strong>You absolutely should not be installing <code>react-scripts</code> globally.</strong><br> You also <strong>don't</strong> need <code>./node_modules/react-scripts/bin/</code> in <code>package.json</code> as <a href="http://stackoverflow.com/a/39960523/458193">this answer</a> implies.</p> <p>If you see this:</p> <pre><code>npm ERR! UpScore@0.6.0 start: `react-scripts start` npm ERR! spawn ENOENT </code></pre> <p>It just means something went wrong when dependencies were installed the first time.</p> <p>I suggest doing these three steps:</p> <ol> <li><code>npm install -g npm@latest</code> to update npm because it is sometimes buggy.</li> <li><code>rm -rf node_modules</code> to remove the existing modules.</li> <li><code>npm install</code> to re-install the project dependencies.</li> </ol> <p>This should fix the problem.<br> If it doesn't, please <a href="https://github.com/facebookincubator/create-react-app/issues/new" rel="nofollow">file an issue</a> with a link to your project and versions of Node and npm.</p>
Excel VBA - PivotItems returns inexsting value <p>In an Excel Workbook, I have "static" pivot table on a sheet, that is based on data from another sheet. I'm refreshing the data on my data sheet (thank you captain Obvious !), then I want to show ALL the items, exept the blank one, so I'm running throw all the PivotItems to set them to visible, and, at the end, unselecting the blank one :</p> <pre><code>i = 1 ThisWorkbook.Sheets("TCD").PivotTables(i).PivotFields("CODETAT").ClearAllFilters ThisWorkbook.Sheets("TCD").PivotTables(i).PivotCache.MissingItemsLimit = xlMissingItemsNone For Each PvI In ThisWorkbook.Sheets("TCD").PivotTables(i).PivotFields("CODETAT").PivotItems PvI.Visible = True Next ThisWorkbook.Sheets("TCD").PivotTables(i).PivotFields("CODETAT").PivotItems("(blank)").Visible = False </code></pre> <p>At the last occurs of my loop, on the 4th PivotItems, I have an error of execution '1004' (I'll translate it from french, it may me some errors, sorry) "Impossible to define the property Visible of the class PivoItem", so I checked a few things :</p> <pre><code>?ThisWorkbook.Sheets("TCD").PivotTables(i).PivotFields("CODETAT").PivotItems.count 4 </code></pre> <p>for x = 1 to 4 :</p> <pre><code>?ThisWorkbook.Sheets("TCD").PivotTables(i).PivotFields("CODETAT").PivotItems(x) (blank) SFT ACQ TEP </code></pre> <p>It look like I have 4 items in my Pivot Table, but</p> <p><a href="http://i.stack.imgur.com/rHjq9.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/rHjq9.jpg" alt="enter image description here"></a></p> <p>And also, when I check my datas, I only have 2 different stats : <a href="http://i.stack.imgur.com/NBfSg.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/NBfSg.jpg" alt="enter image description here"></a></p> <p>So where does this 4th PivotItems' element is coming from, and how can I get ride of it ? Thank you.</p>
<p>I had a surprising issue like that, you need to check in the Pivot Table options :</p> <ul> <li>Right click on the pivot table,</li> <li>Select <code>Pivot Table options</code></li> <li>Go in <code>Data</code> tab</li> <li>Find <code>Retain items deleted from the data source</code></li> <li>Choose <code>None</code> for <code>Number of items to retain per field</code>!</li> <li>Then refresh all should be in order! ;) </li> </ul> <p>(that error drove me mad for hours!^^)</p> <p><a href="http://i.stack.imgur.com/xLtWp.png" rel="nofollow"><img src="http://i.stack.imgur.com/xLtWp.png" alt="enter image description here"></a></p>
Pivot Tables & VBA <p>So I have this pivot table where I can sort upon "Plant Name". I could simply hard code functionalityin saying "Plant26", "Plant12" etc to know the plant names that can be sorted upon. However, is there a different way to access all of these names and place them in an array, instead of iterating through the few thousand lines and finding a difference in name within that column, then append them to an array?</p> <p>Example:</p> <pre><code> For i = 5 to lastrow Name = Cells(i, "A").Value If 'in array Else 'add in array End If next i </code></pre> <p>However is there a faster way? Is it possible to obtain these plant names that could be sorted upon and place them into an array? Here is a pseudo example..</p> <pre><code> With Worksheets("sheet2").PivotTables(1) For i = 1 To .PivotFields("Plant Name").Count MsgBox .PivotFields(i).Name 'Add to array Next End With </code></pre>
<p>This will get you started, it will show you all <code>PivotItems</code> in <code>PivotField</code> "Plant Name".</p> <p><strong>Note</strong>: it is recommended to avoid using <code>ActiveSheet</code>.</p> <p>Option Explicit</p> <pre><code>Sub GetAllPlantNamefromPivot() Dim PvtItm As PivotItem Dim PvtFld As PivotField Dim PlantArr() As Variant Dim count As Long Set PvtFld = ActiveSheet.PivotTables("PivotTable1").PivotFields("Plant Name") ' reset Plant Name Array count count = 0 For Each PvtItm In PvtFld.PivotItems ReDim Preserve PlantArr(0 To count) PlantArr(count) = PvtItm count = count + 1 Next PvtItm End Sub </code></pre>
How to open file in edit mode uploaded to google drive using google api service account <p>I have google api service account.I successfully upload the file on the drive, open the file on browser.But i am not able to get the edit mode.How can i open a particular file in edit mode.And the changes will reflect to original files. Currently i open the file using link "<a href="https://drive.google.com/file/d/0B6TZcMlVILILeEN2al9KanZBS1k/view?usp=drivesdk" rel="nofollow">https://drive.google.com/file/d/0B6TZcMlVILILeEN2al9KanZBS1k/view?usp=drivesdk</a>" this does not support the edit mode. When the current user sign in on the above link page then i see the edit option but it saves to the current user logged in account and not reflect the original file. You can try the above link its working now. I am developing the application in asp.net MVC and using google api v2</p>
<p>One approach is to share the files to the users (depending on type in your use case). Once the file has been uploaded (thru Service Account), additional settings will be required to share the file. Set the role as <code>writer</code> and you'll be good to go (by calling the File's <code>selfLink</code>)</p>
Create Swift framework (revisited) <p>I have read <a href="http://stackoverflow.com/questions/26460998/create-and-import-swift-framework">Create and import swift framework</a> (and many more) but it does not work. Here's what I did: I created a vanilla framework and added a simple Test.swift.</p> <p><a href="http://i.stack.imgur.com/53Qgb.png" rel="nofollow"><img src="http://i.stack.imgur.com/53Qgb.png" alt="enter image description here"></a></p> <p>This builds with no issues and I guess that this should be a valid framework containing my Test class.</p> <p>Now I import this framework to another vanilla app:</p> <p><a href="http://i.stack.imgur.com/icFnc.png" rel="nofollow"><img src="http://i.stack.imgur.com/icFnc.png" alt="enter image description here"></a></p> <p>But trying to access my framework fails:</p> <p><a href="http://i.stack.imgur.com/yxnwn.png" rel="nofollow"><img src="http://i.stack.imgur.com/yxnwn.png" alt="enter image description here"></a></p>
<p>With the information available from your question, "no such module" can mean that you either aren't linking against the framework, or the framework is not in the framework search path. Further, it looks like you have dragged the built framework directly into the dependent project, because I don't see the project where FW.framework included either as a top-level project in a workspace, or as a project dependency (i.e. you have not dragged FW.xcodeproj into the project navigator when you have FrameworkUse open). There are a few ways to resolve this:</p> <ol> <li>Drag <code>FW.xcodeproj</code> into the project navigator somewhere under the <code>FrameworkUse</code> project (this will add <code>FW.xcodeproj</code> as a subproject to the <code>FrameworkUse</code> project). Then go to build settings and a) add the <code>FW.framework</code> target as a target dependency to the <code>FrameworkUse</code> target, b) add the framework (from the Products group under <code>FW.xcodeproj</code>) as an embedded binary.</li> <li>Drag <code>FW.xcodeproj</code> to the top level in the project navigator when you have FrameworkUse project open. Xcode will ask if you want to create a new workspace (unless you already had a workspace open, at which case FW.xcodeproj will be added to the workspace). Similarly as with the above option, go to build settings and a) add the <code>FW.framework</code> target as a target dependency to the <code>FrameworkUse</code> target, b) add the framework (from the Products group under <code>FW.xcodeproj</code>) as an embedded binary.</li> <li>If you really want to depend on the built <code>FW.framework</code> instead of expressing a build dependency to it with either option 1 or 2, you need to a) add the framework as an embedded binary, and b) go to Build Settings and add the directory containing the <code>FW.framework</code> (whose location you can find by opening it in Finder into "Framework search path", for instance <code>"$(PROJECT_DIR)/Frameworks"</code> if Frameworks under the project directory is where you place built frameworks).</li> </ol>
Symfony2 - redirect logged in users when entering anonymous areas <p>I created an action that handles redirection to respected areas depending on user's type and ROLE (trainee, company or university let's say). If user is not logged in, it redirects to homepage (anonymous area), and if logged in - to their profile pages. I use it in homepage and many other cases, for example, as sign up and login success redirection. </p> <pre><code>public function authorizationAction(Request $request) { $user = $this-&gt;getUser(); $authorizationChecker = $this-&gt;get('security.authorization_checker'); $request-&gt;cookies-&gt;remove('action'); if ($user) { if ($user-&gt;getType() == 'company' &amp;&amp; $authorizationChecker-&gt;isGranted('ROLE_COMPANY_GUEST')) { /** @var Company $company */ $company = $user-&gt;getCompany(); if ($user-&gt;getState() == 'active' &amp;&amp; $company-&gt;getState() == 'active') { $response = $this-&gt;redirectToRoute('company'); } else { $response = $this-&gt;redirectToRoute('company_profile'); } } elseif ($user-&gt;getType() == 'university' &amp;&amp; $authorizationChecker-&gt;isGranted('ROLE_UNIVERSITY_GUEST')) { /** @var University $university */ $university = $user-&gt;getUniversity(); if ($user-&gt;getState() == 'active' &amp;&amp; $university-&gt;getState() == 'active') { $response = $this-&gt;redirectToRoute('university'); } else { $response = $this-&gt;redirectToRoute('university_profile'); } } elseif ($user-&gt;getType() == 'trainee' &amp;&amp; $authorizationChecker-&gt;isGranted('ROLE_TRAINEE')) { /** @var Trainee $trainee */ $trainee = $user-&gt;getTrainee(); if ($user-&gt;getState() == 'active' &amp;&amp; $trainee-&gt;getState() == 'active') { $response = $this-&gt;redirectToRoute('trainee'); } else { $response = $this-&gt;redirectToRoute('trainee_profile'); } } else { $response = $this-&gt;redirectToRoute('homepage'); } } else { $response = $this-&gt;redirectToRoute('homepage'); } return $response; } </code></pre> <p>I have seen some <a href="https://coderwall.com/p/w0yyag/redirect-authenticated-user-on-anonymous-pages-in-symfony" rel="nofollow">examples</a> recommending using symfony events (<code>kernel.request</code>) to handle it minimizing controller code. But in this case I will not be able to use this action as sign up and login success path.</p> <p>I am not using <code>FOS</code>, because of lack of user customization. I prefer handling User my self.</p> <p>Is my approach wrong and something to be worried about? </p> <p>Some things that I am concerned:</p> <ol> <li>Redirection count:</li> </ol> <p>For example. I am logged in user and I go to homepage and am redirected to my action where I am checked whether I am logged in or not and depending on user type I am redirected to respected page.</p> <pre><code>public function indexAction(Request $request) { if ($this-&gt;get('security.authorization_checker')-&gt;isGranted('IS_AUTHENTICATED_FULLY')) { return $this-&gt;redirectToRoute('authorization'); } // ... } </code></pre> <ol start="2"> <li>Slowing website:</li> </ol> <p>In the future I will be using this action in more pages and website will definatelly slow down everytime executing same code on each page.</p>
<p>The Access Control section in the Symfony <a href="http://symfony.com/doc/current/security.html" rel="nofollow">documentation</a> might offer easier solutions to restrict access. In my time using Symfony I have always been able to use it for redirection and access control. </p>
Replaceing column content with image doesnt work. It only replaces last <p><a href="http://i.stack.imgur.com/rWHy0.png" rel="nofollow">LOOK at the image PLEASE</a> There is a table that is refreshing every second with AJAX. 2nd column of table has 0 or 1 inside. I want to replace 0 with one image and 1 with another image. Currently I am looping through all the rows but only last row of one kindof image is filled in. All row shoul have a picture in them. What am I doing wrong?</p> <pre><code> var warningImg = document.createElement("IMG"); warningImg.src = "icone/ic_warning.png"; var okImg = document.createElement("IMG"); okImg.src = "icone/ic_done.png"; $(document).ready(function(){ $.ajaxSetup({ cache: false }); setInterval(function() { $.get("IOdoc.htm", function(result){ var stringArray = result.trim().split(","); $('#safety tr:eq(0) td:eq(1)').text(stringArray[0]); $('#safety tr:eq(1) td:eq(1)').text(stringArray[1]); $('#safety tr:eq(2) td:eq(1)').text(stringArray[2]); var safetyEls = document.querySelectorAll("#safety tr td:nth-child(2)"); for(var i=0; i &lt; safetyEls.length ; i++){ if (safetyEls[i].innerHTML.trim() == "1") { safetyEls[i].appendChild(okImg); } else{ safetyEls[i].appendChild(warningImg);} } }); },1000); }); </code></pre> <p>I tried something that proves that for loop is working. I replaced appendChild with textContent just wrote some text. safetyEls[i].textContent = "Warning"</p> <p>This worked. <a href="http://i.stack.imgur.com/UFyzg.png" rel="nofollow">Working table just with text</a></p>
<p>Each time you call the <code>appendChild</code>, you <strong>move</strong> the image you have created.</p> <p>Try cloning it to create new image for each row:</p> <pre><code> if (safetyEls[i].innerHTML.trim() == "1") { safetyEls[i].appendChild(okImg.cloneNode(true)); } else{ safetyEls[i].appendChild(warningImg.cloneNode(true));} } </code></pre> <p>For more details see <a href="http://www.w3schools.com/jsref/met_node_clonenode.asp" rel="nofollow">http://www.w3schools.com/jsref/met_node_clonenode.asp</a></p>
wkhtmltopdf - Hide rows with no value using CSS <p>I have a website that uses a form plugin that uses wkhtmltopdf to generate a PDF based on the values entered and emails it. A good number of the fields in the form are not required and I'd like not to display those fields in the PDF if I don't have to. My HTML looks something like this:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;First Name:&lt;/td&gt;&lt;td&gt;[FirstName]&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Last Name:&lt;/td&gt;&lt;td&gt;[LastName]&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Name Preferred:&lt;/td&gt;&lt;td&gt;[NamePreferred]&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>The text in <code>[]</code> refers to field names and the plugin I'm using replaces those with the value the user typed into that field. In the example above, <code>[NamePreferred]</code> is not a required field. If the user chose not to enter anything into that field, I'd like to keep it from showing up in the PDF. </p> <p>Unfortunately, wkhtmltopdf has limited CSS3 support so this doesn't work:</p> <pre><code>&lt;style&gt; tr[data-val=""] { display: none; } &lt;/style&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;First Name:&lt;/td&gt;&lt;td&gt;[FirstName]&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Last Name:&lt;/td&gt;&lt;td&gt;[LastName]&lt;/td&gt; &lt;/tr&gt; &lt;tr data-val="[NamePreferred]"&gt; &lt;td&gt;Name Preferred:&lt;/td&gt;&lt;td&gt;[NamePreferred]&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>It also doesn't support JavaScript. Is there a clever way to prevent rows without a value from showing up in my PDF using only HTML and CSS?</p>
<p>can you try this:</p> <pre><code>&lt;tr style="display:@( NamePreferred=="" ? "block" : "none");"&gt; &lt;td&gt;Name Preferred:&lt;/td&gt;&lt;td&gt;[NamePreferred]&lt;/td&gt; &lt;/tr&gt; </code></pre>
Linq SelectMany in Entity Framework <p>I'm using Entity Framework. My typical access functionality would be something like this:</p> <pre><code> public IEnumerable&lt;Product&gt; Category(string category, int term) { using (var uow = new UnitOfWork(Connections.LoanComparision)) { var r = new Repository&lt;Product&gt;(uow.Context); return r.Find(x =&gt; x.Category == category) .Include(x =&gt; x.ProductDetails) .Include(x =&gt; x.ProductRates) .Include(x =&gt; x.Provider) .ToList(); } } </code></pre> <p>You will note from the code above 2 things.</p> <ul> <li>The query returns a list of products with a category including linked entities.</li> <li>There are a number of ProductDetail lines for each Product.</li> </ul> <p>What I want to do (and haven't been able to work out) is to apply selection criteria on the ProductDetails table.</p> <p>The stuff inside .Find (my function) can be replaced by a standard .Where clause, but I need to filter on MinTerm and MaxTerm (which is in ProductDetails) yet still return the complete Product dataset (including linked entities), not just ProductDetails.</p> <pre><code>Where(x =&gt; term &gt;= x.MinTerm &amp;&amp; term &lt;= x.MaxTerm) </code></pre> <p>I can work out how to do it by referencing ProductDetails first and linking to other tables but can't in this configuration. Is it possible?</p>
<p>If the relationship between <code>Product</code> and <code>ProductDetail</code> is one to many you could do this:</p> <pre><code>var query= context.ProductDetails.Include(pd=&gt;pd.Product.ProductRates) .Include(pd=&gt;pd.Product.Provider) .Where(pd=&gt; pd.Product.Category == category &amp;&amp; term &gt;= pd.MinTerm &amp;&amp; term &lt;= pd.MaxTerm); </code></pre> <p>And if you want the list of products you could do the following:</p> <pre><code>var query1=query.Select(pd=&gt;pd.Product).Distinct().ToList(); </code></pre>
install package from a requirenment txt and failed <p>I read the rnn tutorial in <a href="https://github.com/dennybritz/rnn-tutorial-rnnlm" rel="nofollow">https://github.com/dennybritz/rnn-tutorial-rnnlm</a> and follow the installations to set up the environment. But I got the error which I have no idea about this. I set up it in <code>virtualenv</code> in Ubuntu 14. I have search the similar problem and use their solution but it does not work. </p> <p>The method I have tried: 1. update <code>gcc</code> 2. reinstall <code>python-dev</code> 3. install <code>libxxx</code>(sorry about this inaccurate name but there are a mess of such files so I can not remember)</p> <p>Note: 1. I am not an expert in ubuntu so if you can help me and hope you can provide a detailed explanation or solution if you are avaible. 2.I have tried to reinstall ubuntu and it does not work</p> <pre><code>creating build/temp.linux-x86_64-2.7/Modules/2.x x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -DHAVE_RL_CALLBACK -DHAVE_RL_CATCH_SIGNAL -DHAVE_RL_COMPLETION_APPEND_CHARACTER -DHAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK -DHAVE_RL_COMPLETION_MATCHES -DHAVE_RL_COMPLETION_SUPPRESS_APPEND -DHAVE_RL_PRE_INPUT_HOOK -I. -I/usr/include/python2.7 -c Modules/2.x/readline.c -o build/temp.linux-x86_64-2.7/Modules/2.x/readline.o In file included from Modules/2.x/readline.c:31:0: ./readline/readline.h:385:1: warning: function declaration isn’t a prototype [-Wstrict-prototypes] extern int rl_message (); ^ x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/Modules/2.x/readline.o readline/libreadline.a readline/libhistory.a -lncurses -o build/lib.linux-x86_64-2.7/gnureadline.so /usr/bin/ld: cannot find -lncurses collect2: error: ld returned 1 exit status error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Cleaning up... Command /home/shuyu-lyu/venv/bin/python -c "import setuptools, tokenize;__file__='/home/shuyu-lyu/venv/build/gnureadline/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-xF2y3k-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/shuyu-lyu/venv/include/site/python2.7 failed with error code 1 in /home/shuyu-lyu/venv/build/gnureadline Traceback (most recent call last): File "/home/shuyu-lyu/venv/bin/pip", line 11, in &lt;module&gt; sys.exit(main()) File "/home/shuyu-lyu/venv/local/lib/python2.7/site-packages/pip/__init__.py", line 185, in main return command.main(cmd_args) File "/home/shuyu-lyu/venv/local/lib/python2.7/site-packages/pip/basecommand.py", line 161, in main text = '\n'.join(complete_log) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 66: ordinal not in range(128) </code></pre>
<p>Looks like ncurses library is not installed. If you are on Ubuntu, you should first install it with </p> <pre><code>sudo apt-get install libncurses5-dev libncursesw5-dev </code></pre>
Angular2: Return type of public static method from exported class has or is using private name <h2>Error</h2> <pre><code>Error at /Users/user/project/.tmp/shared/validation/validators/unicode-characters.validator.ts:12:52: Return type of public static method from exported class has or is using private name 'ValidationResult'. </code></pre> <h2>Component</h2> <pre><code>import {FormControl} from "@angular/forms"; interface ValidationResult { [key:string]:boolean; } export class UnicodeCharactersValidator { /* tslint:disable:max-line-length */ private static UNICODE_CHARS_PATTERN = /^[ \u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0]*$/; public static check(formControl: FormControl): ValidationResult { if ( !UnicodeCharactersValidator.UNICODE_CHARS_PATTERN.test(formControl.value) ) { return { "invalidCharacters": true }; } return null; } } </code></pre> <p>How can I fix this?</p>
<p>You have to export the interface as well:</p> <pre><code>export interface ValidationResult { [key:string]:boolean; } </code></pre> <p>The public function returns a <code>ValidationResult</code>. Which means it is accessible from the outside. That's why you should also export the <code>ValidationResult</code> :)</p>
How to unscramble a list of words using a HashMap? <p>Basically I will be given two large input files. One will be a list of words, the other will be that list of those same words, but the words will be scrambled. I have to use a HashMap to get the list of words and scrambled words and then print the scrambled word with the real word next to it in alphabetical order.</p> <p>For example:</p> <p>rdib bird</p> <p>tca cat</p> <p>gdo dog</p> <p>etc.</p> <p>I'm having some trouble so far. I have created a method to sort and get the key from the words, but I'm not sure where to go from there. I think I still need to work with the scrambled words and then print everything out. Any help explaining these things would be much appreciated, for this is my first time using a HashMap. My current, very incomplete code is below.</p> <pre><code>import java.io.*; import java.util.*; public class Project5 { public static void main (String[] args) throws Exception { BufferedReader dictionaryList = new BufferedReader( new FileReader( args[0] ) ); BufferedReader scrambleList = new BufferedReader( new FileReader( args[1] ) ); HashMap&lt;String, String&gt; dWordMap = new HashMap&lt;String, String&gt;(); while (dictionaryList.ready()) { String word = dictionaryList.readLine(); dWordMap.put(createKey(word), word); } dictionaryList.close(); while (scrambleList.ready()) { String scrambledWords = scrambleList.readLine(); List&lt;String&gt; dictionaryWords = dWordMap.get(createKey(scrambledWords)); System.out.println(scrambledWords + " " + dictionaryWords); } scrambleList.close(); } private static String createKey(String word) { char[] characterWord = word.toCharArray(); Arrays.sort(characterWord); return new String(characterWord); } </code></pre>
<p>Make the dWordMap just <code>HashMap&lt;String, String&gt;</code>. For the line you're not sure of, do <code>dWordMap.put(createKey(word), word)</code>.</p> <p>Then loop through the scrableList and the word is <code>dWordMap.get(createKey(scrambledWord))</code>.</p> <p>You should probably also handle the case that the scrambled word is not in the original word list.</p> <hr> <p>The key concept to understand about a HashMap is that it makes it O(1) to test if the map contains a given key, and O(1) to retrieve the value associated with a given key. This means these operations take constant time--whether the map has 5 elements or 5000, it will take the same time to determine if the map contains <code>"ehllo"</code>. If you want to check these two lists (dictionary and scrambled), you need a key that will be the same for both. As you have started to do in your solution, sorting the letters in the word is a good choice. So your HashMap will look something like this:</p> <pre><code>{ "ehllo": "hello", "dlorw": "world" } </code></pre> <p>One pass through the dictionary list builds that map, then another pass through it takes the scrambled word, sorts the letters in it, then checks the map to find the unscrambled word.</p>
Python, scipy : minimize multivariable function in integral expression <p>how can I minimize a function (uncostrained), respect a[0] and a[1]? example (this is a simple example for I uderstand scipy, numpy and py):</p> <pre><code>import numpy as np from scipy.integrate import * from scipy.optimize import * def function(a): return(quad(lambda t: ((np.cos(a[0]))*(np.sin(a[1]))*t),0,3)) </code></pre> <p>i tried:</p> <pre><code>l=np.array([0.1,0.2]) res=minimize(function,l, method='nelder-mead',options={'xtol': 1e-8, 'disp': True}) </code></pre> <p>but I get errors. I get the results in matlab.</p> <p>any idea ?</p> <p>thanks in advance</p>
<p>This is just a guess, because you haven't included enough information in the question for anyone to really know what the problem is. Whenever you ask a question about code that generates an error, always include the complete error message in the question. Ideally, you should include a <a href="http://stackoverflow.com/help/mcve">minimal, complete and verifiable example</a> that we can run to reproduce the problem. Currently, you define <code>function</code>, but later you use the undefined function <code>chirplet</code>. That makes it a little bit harder for anyone to understand your problem.</p> <p>Having said that...</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html" rel="nofollow"><code>scipy.integrate.quad</code></a> returns two values: the estimate of the integral, and an estimate of the absolute error of the integral. It looks like you haven't taken this into account in <code>function</code>. Try something like this:</p> <pre><code>def function(a): intgrl, abserr = quad(lambda t: np.cos(a[0])*np.sin(a[1])*t, 0, 3) return intgrl </code></pre>
SQL duplicate values in multiple columns <p>I have a table with duplicate ID's, but other values in the second column. Instead of removing all the duplicates with DISTINCT, I need 1 row with the ID and several columns with the values from the second column.</p> <p>Here is what I mean: (has to become result)</p> <p><img src="http://i.stack.imgur.com/4z4nF.jpg" alt="Original"></p> <p><img src="http://i.stack.imgur.com/3a6Jn.jpg" alt="Result"></p>
<p>You can use PIVOT for this. Check this.</p> <pre><code>SELECT * FROM [TABLENAME] PIVOT (COUNT(category) FOR [category] IN ([A],[B],[C],[D]) AS P </code></pre>
TypeMismatchError on post <p>I'm writing an <code>aurelia</code> application with <code>aurelia-fetch-client</code> library. When I try to post an object to my api service I get the error:</p> <blockquote> <p>TypeMismatchError </p> </blockquote> <p>In console only from Edge. Other browsers (Chrome, Firefox and IE11) have no problems. There are no description or any other details about it. </p>
<p>In all but the newest versions of Edge you need to include the <strong>fetch</strong> polyfill in order for <code>aurelia-fetch-client</code> to work. I think it's supported since version 14 but I wouldn't necessarily rely on it. Edge is known to be quirky with some of these things (the Promise implementation is also horribly slow, which is why I personally always use bluebird)</p> <p>You can install it with <code>npm i whatwg-fetch --save</code> and make sure to import it + include it in your bundle config (the instructions for this depend on which build system you're using)</p>
read escaped character \t as '\t' instead of '\\t' Python ConfigParser <p>I have a config.ini file containing <code>delimiter = \t</code> which i now want to read using the python3 ConfigParser. However, the resulting string is <code>'\\t'</code> instead of <code>'\t'</code> which breaks my program. Is there a more elegant option to solve this problem instead of just manually stripping the extra '\' from every variable containing an escaped character? I cannot find an option for ConfigParser().read() to not escape the backslash it finds in the file.</p>
<p>Python3 has a 'unicode_escape' codec.</p> <pre><code>r"a\tb".decode('unicode_escape') 'a\tb' </code></pre> <p>Sources:</p> <p><a href="https://bytes.com/topic/python/answers/37952-escape-chars-string" rel="nofollow">https://bytes.com/topic/python/answers/37952-escape-chars-string</a></p> <p><a href="http://stackoverflow.com/questions/14820429/how-do-i-decodestring-escape-in-python3#14820462">how do I .decode(&#39;string-escape&#39;) in Python3?</a></p>
udf Fuction for DataType casting, Scala <p>I have next DataFrame:</p> <pre><code>df.show() +---------------+----+ | x| num| +---------------+----+ |[0.1, 0.2, 0.3]| 0| |[0.3, 0.1, 0.1]| 1| |[0.2, 0.1, 0.2]| 2| +---------------+----+ </code></pre> <p>This DataFrame has follow Datatypes of columns:</p> <pre><code>df.printSchema root |-- x: array (nullable = true) | |-- element: double (containsNull = true) |-- num: long (nullable = true) </code></pre> <p>I try to convert currently the DoubleArray inside of DataFrame to the FloatArray. I do it with the next statement of udf:</p> <pre><code>val toFloat = udf[(val line: Seq[Double]) =&gt; line.map(_.toFloat)] val test = df.withColumn("testX", toFloat(df("x"))) </code></pre> <p>This code is currently not working. Can anybody share with me the solution how to change the array Type inseide of DataFrame?</p> <p>What I want is:</p> <pre><code>df.printSchema root |-- x: array (nullable = true) | |-- element: float (containsNull = true) |-- num: long (nullable = true) </code></pre> <p>This question is based on the question <a href="http://stackoverflow.com/questions/29383107/how-to-change-column-types-in-spark-sqls-dataframe">How tho change the simple DataType in Spark SQL's DataFrame</a></p>
<p>Your <code>udf</code> is wrongly declared. You should write it as follows :</p> <pre><code>val toFloat = udf((line: Seq[Double]) =&gt; line.map(_.toFloat)) </code></pre>
Classic ASP FormatPercent ignores 100%? <p>The code below works out percentages for my data. All works fine apart from 100% which should be red (#B20000) but in fact is green (#32CD32). I added an option that specifically refers to 100% but even that has not effect. Any ideas? Thanks </p> <pre class="lang-vbs prettyprint-override"><code>R = FormatPercent( objRsStat("active_beds") / objRsStat("total_beds"), 2 ) 'R = objRsStat("percent_remaining") If R =&lt; "60%" Then CL = "#32CD32" ElseIf R =&gt; "61%" And R =&lt; "79%" Then CL = "#FF8000" ElseIf R =&gt; "80%" Then CL = "#B20000" ELSEIF R = "100%" Then CL = "#B20000" END IF </code></pre> <p>Updated Code (With Error):</p> <pre><code>If R &lt;= 0.6 Then CL = "#32CD32" ELSEIF R =&gt; 0.61 AND R &lt;= 0.79 THEN CL = "#FF8000" ELSEIF R =&gt; 0.80 THEN CL = "#B20000" END IF </code></pre>
<p>You're using the wrong syntax. <code>&lt;= "60%"</code> will compare the <strong>numeric</strong> value in <code>R</code> to the <strong>string</strong> "60%". VBScript doesn't complain about this because it's permissive by-design, but this also causes silent issues - like what you're experiencing.</p> <p>You're also using incorrect code that won't even run: the "less-than-or-equal-to" operator is <code>&lt;=</code> and not <code>=&lt;</code>).</p> <p>Try this:</p> <pre><code>If R &lt;= 0.6 Then CL = "#32CD32" </code></pre> <p>(You also need to remove the <code>FormatPercent</code> function call, otherwise you'll get a type mismatch error.)</p>
Memory padding issues using __declspec <p>based on MSDN the __declspec(align(x)) should add x bit padding after the member variables for example:</p> <pre><code>#include &lt;iostream&gt; using namespace std; void main() { struct test { __declspec(align(32))char x; __declspec(align(32))int i; __declspec(align(32)) char j; }; cout &lt;&lt; sizeof(test) &lt;&lt; endl;//will print 96 which is correct } </code></pre> <p>now consider the following case:</p> <pre><code>#include &lt;iostream&gt; using namespace std; void main() { struct test { char x; int i; char j; }; cout &lt;&lt; sizeof(test) &lt;&lt; endl;//will print 12 //1 byte for x + 3 bytes padding + 4 bytes for i + 1 byte for j +3 bytes padding =12 } </code></pre> <p>but if i change the code to this:</p> <pre><code>#include &lt;iostream&gt; using namespace std; void main() { struct test { char x; int i; __declspec(align(1)) char j; }; cout &lt;&lt; sizeof(test) &lt;&lt; endl;//will print 12 again!!!! } </code></pre> <p>why it is giving me 12 instead of 9! i am telling the compile that i don't want any padding after j.</p>
<p><code>__declspec(align(1)) char j</code> doesn't do anything - a <code>char</code> requires no special alignment with or without the <code>__declspec</code>.</p> <p>Imagine you later declare an array of <code>test</code>: <code>test arr[2];</code>. Here, both <code>arr[0].i</code> and <code>arr[1].i</code> must be aligned on the 4-byte boundary; that requires that <code>sizeof(arr[0])</code> be a multiple of 4. That's why there's padding at the end of the structure.</p>
Does c++ standard specify how to pass this pointer to member functions? <p>Most everybody knows that class member receive the <strong>this</strong> pointer as the first "invisible" parameter of the function. Is this specified in C++ standard? Can a certain compiler implementation pass it in a different way? Dedicated registry for example.</p>
<p>That's certainly how the very first versions of C++ were implemented (early C++ was transformed into C code), but be assured that the C++ standard does <strong>not</strong> mandate this.</p> <p>Passing it as the last parameter value also seems feasible, and for virtual functions, some different technique altogether.</p>